text
stringlengths
54
60.6k
<commit_before>/*********************************************************************** fields.cpp - Implements the Fields class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004-2007 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "fields.h" #include "result.h" namespace mysqlpp { Fields::size_type Fields::size() const { return res_->num_fields(); } const Field& Fields::at(int i) const { res_->field_seek(i); return res_->fetch_field(); } } // end namespace mysqlpp <commit_msg>Comment change<commit_after>/*********************************************************************** fields.cpp - Implements the Fields class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and (c) 2004-2007 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "fields.h" #include "result.h" namespace mysqlpp { Fields::size_type Fields::size() const { return res_->num_fields(); } const Field& Fields::at(int i) const { res_->field_seek(i); return res_->fetch_field(); } } // end namespace mysqlpp <|endoftext|>
<commit_before>// Author: Stefan Wunsch, Enrico Guiraud CERN 09/2020 /************************************************************************* * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_RDF_RRESULTHANDLE #define ROOT_RDF_RRESULTHANDLE #include "ROOT/RResultPtr.hxx" #include "ROOT/RDF/RLoopManager.hxx" #include "ROOT/RDF/RActionBase.hxx" #include "ROOT/RDF/Utils.hxx" // TypeID2TypeName #include <memory> #include <sstream> #include <typeinfo> #include <stdexcept> // std::runtime_error namespace ROOT { namespace RDF { class RResultHandle { ROOT::Detail::RDF::RLoopManager* fLoopManager; //< Pointer to the loop manager /// Owning pointer to the action that will produce this result. /// Ownership is shared with RResultPtrs and RResultHandles that refer to the same result. std::shared_ptr<ROOT::Internal::RDF::RActionBase> fActionPtr; std::shared_ptr<void> fObjPtr; ///< Type erased shared pointer encapsulating the wrapped result const std::type_info& fType; ///< Type of the wrapped result // The ROOT::RDF::RunGraphs helper has to access the loop manager to check whether two RResultHandles belong to the same computation graph friend void RunGraphs(std::vector<RResultHandle>); /// Get the pointer to the encapsulated result. /// Ownership is not transferred to the caller. /// Triggers event loop and execution of all actions booked in the associated RLoopManager. void* Get() { if (!fActionPtr->HasRun()) fLoopManager->Run(); return fObjPtr.get(); } /// Compare given type to the type of the wrapped result and throw if the types don't match. void CheckType(const std::type_info& type) { if (fType != type) { std::stringstream ss; ss << "Got the type " << ROOT::Internal::RDF::TypeID2TypeName(type) << " but the RResultHandle refers to a result of type " << ROOT::Internal::RDF::TypeID2TypeName(fType) << "."; throw std::runtime_error(ss.str()); } } public: template <class T> RResultHandle(const RResultPtr<T> &resultPtr) : fLoopManager(resultPtr.fLoopManager), fActionPtr(resultPtr.fActionPtr), fObjPtr(resultPtr.fObjPtr), fType(typeid(T)) {} RResultHandle(const RResultHandle&) = default; RResultHandle(RResultHandle&&) = default; /// Get the pointer to the encapsulated object. /// Triggers event loop and execution of all actions booked in the associated RLoopManager. /// \tparam T Type of the action result template <class T> T* GetPtr() { CheckType(typeid(T)); return static_cast<T*>(Get()); } /// Get a const reference to the encapsulated object. /// Triggers event loop and execution of all actions booked in the associated RLoopManager. /// \tparam T Type of the action result template <class T> const T& GetValue() { CheckType(typeid(T)); return *static_cast<T*>(Get()); } /// Check whether the result has already been computed /// /// ~~~{.cpp} /// std::vector<RResultHandle> results; /// results.emplace_back(df.Mean<double>("var")); /// res.IsReady(); // false, access will trigger event loop /// std::cout << res.GetValue<double>() << std::endl; // triggers event loop /// res.IsReady(); // true /// ~~~ bool IsReady() const { return fActionPtr->HasRun(); } bool operator==(const RResultHandle &rhs) const { return fObjPtr == rhs.fObjPtr; } bool operator!=(const RResultHandle &rhs) const { return !(fObjPtr == rhs.fObjPtr); } }; } // namespace RDF } // namespace ROOT #endif // ROOT_RDF_RRESULTHANDLE <commit_msg>[DF] Make RResultHandle default-constructible<commit_after>// Author: Stefan Wunsch, Enrico Guiraud CERN 09/2020 /************************************************************************* * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_RDF_RRESULTHANDLE #define ROOT_RDF_RRESULTHANDLE #include "ROOT/RResultPtr.hxx" #include "ROOT/RDF/RLoopManager.hxx" #include "ROOT/RDF/RActionBase.hxx" #include "ROOT/RDF/Utils.hxx" // TypeID2TypeName #include <memory> #include <sstream> #include <typeinfo> #include <stdexcept> // std::runtime_error namespace ROOT { namespace RDF { class RResultHandle { ROOT::Detail::RDF::RLoopManager *fLoopManager = nullptr; //< Pointer to the loop manager /// Owning pointer to the action that will produce this result. /// Ownership is shared with RResultPtrs and RResultHandles that refer to the same result. std::shared_ptr<ROOT::Internal::RDF::RActionBase> fActionPtr; std::shared_ptr<void> fObjPtr; ///< Type erased shared pointer encapsulating the wrapped result const std::type_info *fType = nullptr; ///< Type of the wrapped result // The ROOT::RDF::RunGraphs helper has to access the loop manager to check whether two RResultHandles belong to the same computation graph friend void RunGraphs(std::vector<RResultHandle>); /// Get the pointer to the encapsulated result. /// Ownership is not transferred to the caller. /// Triggers event loop and execution of all actions booked in the associated RLoopManager. void* Get() { if (!fActionPtr->HasRun()) fLoopManager->Run(); return fObjPtr.get(); } /// Compare given type to the type of the wrapped result and throw if the types don't match. void CheckType(const std::type_info& type) { if (*fType != type) { std::stringstream ss; ss << "Got the type " << ROOT::Internal::RDF::TypeID2TypeName(type) << " but the RResultHandle refers to a result of type " << ROOT::Internal::RDF::TypeID2TypeName(*fType) << "."; throw std::runtime_error(ss.str()); } } void ThrowIfNull() { if (fObjPtr == nullptr) throw std::runtime_error("Trying to access the contents of a null RResultHandle."); } public: template <class T> RResultHandle(const RResultPtr<T> &resultPtr) : fLoopManager(resultPtr.fLoopManager), fActionPtr(resultPtr.fActionPtr), fObjPtr(resultPtr.fObjPtr), fType(&typeid(T)) {} RResultHandle(const RResultHandle&) = default; RResultHandle(RResultHandle&&) = default; RResultHandle() = default; /// Get the pointer to the encapsulated object. /// Triggers event loop and execution of all actions booked in the associated RLoopManager. /// \tparam T Type of the action result template <class T> T* GetPtr() { ThrowIfNull(); CheckType(typeid(T)); return static_cast<T*>(Get()); } /// Get a const reference to the encapsulated object. /// Triggers event loop and execution of all actions booked in the associated RLoopManager. /// \tparam T Type of the action result template <class T> const T& GetValue() { ThrowIfNull(); CheckType(typeid(T)); return *static_cast<T*>(Get()); } /// Check whether the result has already been computed /// /// ~~~{.cpp} /// std::vector<RResultHandle> results; /// results.emplace_back(df.Mean<double>("var")); /// res.IsReady(); // false, access will trigger event loop /// std::cout << res.GetValue<double>() << std::endl; // triggers event loop /// res.IsReady(); // true /// ~~~ bool IsReady() const { if (fActionPtr == nullptr) return false; return fActionPtr->HasRun(); } bool operator==(const RResultHandle &rhs) const { return fObjPtr == rhs.fObjPtr; } bool operator!=(const RResultHandle &rhs) const { return !(fObjPtr == rhs.fObjPtr); } }; } // namespace RDF } // namespace ROOT #endif // ROOT_RDF_RRESULTHANDLE <|endoftext|>
<commit_before>#include "ProfileHandler.h" #include "SwitchHandler.h" ProfileHandler::~ProfileHandler() { Serial.println("Freeing resources"); for(int i = 0 ; i < this->inTopicsCount ; i++ ) { this->client->unsubscribe(this->inTopics[i]); free(this->inTopics[i]); } free(this->inTopics); }; void ProfileHandler::setMqttClient(MQTTClient* client) { this->client = client; }; void ProfileHandler::setup(JsonObject& config) { JsonArray& inTopics = config["in_topics"]; this->inTopicsCount = inTopics.size(); this->inTopics = (char**) malloc (this->inTopicsCount * sizeof( char* )); for(int i = 0 ; i < this->inTopicsCount ; i++) { this->inTopics[i] = strdup(inTopics[i].asString()); } this->outTopic = strdup( config["out_topic"].asString()); }; void ProfileHandler::init() { for(int i = 0 ; i < this->inTopicsCount ; i++ ) { Serial.print("Subscribe to "); Serial.println(this->inTopics[i]); this->client->subscribe(this->inTopics[i]); } }; /* Factory method for ProfileHandler's */ ProfileHandler* ProfileHandler::createHandler(short int type) { switch(type) { case YAHA_TYPE_SWITCH: return new SwitchHandler(); } return NULL; }; bool ProfileHandler::handle(char topic[], char payload[], int length) { for(int i = 0 ; i < this->inTopicsCount ; i++ ) { if (strcmp(this->inTopics[i], topic) == 0) { //I'm listening this topic, so I need to get to work this->doHandle(topic, payload, length); return true; } } return false; }; <commit_msg>Print unhandled types<commit_after>#include "ProfileHandler.h" #include "SwitchHandler.h" ProfileHandler::~ProfileHandler() { Serial.println("Freeing resources"); for(int i = 0 ; i < this->inTopicsCount ; i++ ) { this->client->unsubscribe(this->inTopics[i]); free(this->inTopics[i]); } free(this->inTopics); }; void ProfileHandler::setMqttClient(MQTTClient* client) { this->client = client; }; void ProfileHandler::setup(JsonObject& config) { JsonArray& inTopics = config["in_topics"]; this->inTopicsCount = inTopics.size(); this->inTopics = (char**) malloc (this->inTopicsCount * sizeof( char* )); for(int i = 0 ; i < this->inTopicsCount ; i++) { this->inTopics[i] = strdup(inTopics[i].asString()); } this->outTopic = strdup( config["out_topic"].asString()); }; void ProfileHandler::init() { for(int i = 0 ; i < this->inTopicsCount ; i++ ) { Serial.print("Subscribe to "); Serial.println(this->inTopics[i]); this->client->subscribe(this->inTopics[i]); } }; /* Factory method for ProfileHandler's */ ProfileHandler* ProfileHandler::createHandler(short int type) { switch(type) { case YAHA_TYPE_SWITCH: return new SwitchHandler(); } Serial.print("Unknown handler type: "); Serial.println(type); return NULL; }; bool ProfileHandler::handle(char topic[], char payload[], int length) { for(int i = 0 ; i < this->inTopicsCount ; i++ ) { if (strcmp(this->inTopics[i], topic) == 0) { //I'm listening this topic, so I need to get to work this->doHandle(topic, payload, length); return true; } } return false; }; <|endoftext|>
<commit_before>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "types.hh" #include "bytes.hh" #include <optional> #include <variant> #include <seastar/util/variant_utils.hh> #include "utils/fragmented_temporary_buffer.hh" namespace cql3 { struct null_value { }; struct unset_value { }; /// \brief View to a raw CQL protocol value. /// /// \see raw_value struct raw_value_view { std::variant<fragmented_temporary_buffer::view, null_value, unset_value> _data; raw_value_view(null_value&& data) : _data{std::move(data)} {} raw_value_view(unset_value&& data) : _data{std::move(data)} {} raw_value_view(fragmented_temporary_buffer::view data) : _data{data} {} public: static raw_value_view make_null() { return raw_value_view{std::move(null_value{})}; } static raw_value_view make_unset_value() { return raw_value_view{std::move(unset_value{})}; } static raw_value_view make_value(fragmented_temporary_buffer::view view) { return raw_value_view{view}; } bool is_null() const { return std::holds_alternative<null_value>(_data); } bool is_unset_value() const { return std::holds_alternative<unset_value>(_data); } bool is_value() const { return std::holds_alternative<fragmented_temporary_buffer::view>(_data); } std::optional<fragmented_temporary_buffer::view> data() const { if (auto pdata = std::get_if<fragmented_temporary_buffer::view>(&_data)) { return *pdata; } return {}; } explicit operator bool() const { return is_value(); } const fragmented_temporary_buffer::view* operator->() const { return &std::get<fragmented_temporary_buffer::view>(_data); } const fragmented_temporary_buffer::view& operator*() const { return std::get<fragmented_temporary_buffer::view>(_data); } bool operator==(const raw_value_view& other) const { if (_data.index() != other._data.index()) { return false; } if (is_value() && **this != *other) { return false; } return true; } bool operator!=(const raw_value_view& other) const { return !(*this == other); } friend std::ostream& operator<<(std::ostream& os, const raw_value_view& value); }; /// \brief Raw CQL protocol value. /// /// The `raw_value` type represents an uninterpreted value from the CQL wire /// protocol. A raw value can hold either a null value, an unset value, or a byte /// blob that represents the value. class raw_value { std::variant<bytes, null_value, unset_value> _data; raw_value(null_value&& data) : _data{std::move(data)} {} raw_value(unset_value&& data) : _data{std::move(data)} {} raw_value(bytes&& data) : _data{std::move(data)} {} raw_value(const bytes& data) : _data{data} {} public: static raw_value make_null() { return raw_value{std::move(null_value{})}; } static raw_value make_unset_value() { return raw_value{std::move(unset_value{})}; } static raw_value make_value(const raw_value_view& view); static raw_value make_value(bytes&& bytes) { return raw_value{std::move(bytes)}; } static raw_value make_value(const bytes& bytes) { return raw_value{bytes}; } static raw_value make_value(const bytes_opt& bytes) { if (bytes) { return make_value(*bytes); } return make_null(); } bool is_null() const { return std::holds_alternative<null_value>(_data); } bool is_unset_value() const { return std::holds_alternative<unset_value>(_data); } bool is_value() const { return std::holds_alternative<bytes>(_data); } bytes_opt data() const { if (auto pdata = std::get_if<bytes>(&_data)) { return *pdata; } return {}; } explicit operator bool() const { return is_value(); } const bytes* operator->() const { return &std::get<bytes>(_data); } const bytes& operator*() const { return std::get<bytes>(_data); } raw_value_view to_view() const; }; } inline bytes to_bytes(const cql3::raw_value_view& view) { return linearized(*view); } inline bytes_opt to_bytes_opt(const cql3::raw_value_view& view) { auto buffer_view = view.data(); if (buffer_view) { return bytes_opt(linearized(*buffer_view)); } return bytes_opt(); } inline bytes_opt to_bytes_opt(const cql3::raw_value& value) { return to_bytes_opt(value.to_view()); } <commit_msg>cql3: allow moving data out of raw_value<commit_after>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "types.hh" #include "bytes.hh" #include <optional> #include <variant> #include <seastar/util/variant_utils.hh> #include "utils/fragmented_temporary_buffer.hh" namespace cql3 { struct null_value { }; struct unset_value { }; /// \brief View to a raw CQL protocol value. /// /// \see raw_value struct raw_value_view { std::variant<fragmented_temporary_buffer::view, null_value, unset_value> _data; raw_value_view(null_value&& data) : _data{std::move(data)} {} raw_value_view(unset_value&& data) : _data{std::move(data)} {} raw_value_view(fragmented_temporary_buffer::view data) : _data{data} {} public: static raw_value_view make_null() { return raw_value_view{std::move(null_value{})}; } static raw_value_view make_unset_value() { return raw_value_view{std::move(unset_value{})}; } static raw_value_view make_value(fragmented_temporary_buffer::view view) { return raw_value_view{view}; } bool is_null() const { return std::holds_alternative<null_value>(_data); } bool is_unset_value() const { return std::holds_alternative<unset_value>(_data); } bool is_value() const { return std::holds_alternative<fragmented_temporary_buffer::view>(_data); } std::optional<fragmented_temporary_buffer::view> data() const { if (auto pdata = std::get_if<fragmented_temporary_buffer::view>(&_data)) { return *pdata; } return {}; } explicit operator bool() const { return is_value(); } const fragmented_temporary_buffer::view* operator->() const { return &std::get<fragmented_temporary_buffer::view>(_data); } const fragmented_temporary_buffer::view& operator*() const { return std::get<fragmented_temporary_buffer::view>(_data); } bool operator==(const raw_value_view& other) const { if (_data.index() != other._data.index()) { return false; } if (is_value() && **this != *other) { return false; } return true; } bool operator!=(const raw_value_view& other) const { return !(*this == other); } friend std::ostream& operator<<(std::ostream& os, const raw_value_view& value); }; /// \brief Raw CQL protocol value. /// /// The `raw_value` type represents an uninterpreted value from the CQL wire /// protocol. A raw value can hold either a null value, an unset value, or a byte /// blob that represents the value. class raw_value { std::variant<bytes, null_value, unset_value> _data; raw_value(null_value&& data) : _data{std::move(data)} {} raw_value(unset_value&& data) : _data{std::move(data)} {} raw_value(bytes&& data) : _data{std::move(data)} {} raw_value(const bytes& data) : _data{data} {} public: static raw_value make_null() { return raw_value{std::move(null_value{})}; } static raw_value make_unset_value() { return raw_value{std::move(unset_value{})}; } static raw_value make_value(const raw_value_view& view); static raw_value make_value(bytes&& bytes) { return raw_value{std::move(bytes)}; } static raw_value make_value(const bytes& bytes) { return raw_value{bytes}; } static raw_value make_value(const bytes_opt& bytes) { if (bytes) { return make_value(*bytes); } return make_null(); } bool is_null() const { return std::holds_alternative<null_value>(_data); } bool is_unset_value() const { return std::holds_alternative<unset_value>(_data); } bool is_value() const { return std::holds_alternative<bytes>(_data); } bytes_opt data() const { if (auto pdata = std::get_if<bytes>(&_data)) { return *pdata; } return {}; } explicit operator bool() const { return is_value(); } const bytes* operator->() const { return &std::get<bytes>(_data); } const bytes& operator*() const { return std::get<bytes>(_data); } bytes&& extract_value() && { auto b = std::get_if<bytes>(&_data); assert(b); return std::move(*b); } raw_value_view to_view() const; }; } inline bytes to_bytes(const cql3::raw_value_view& view) { return linearized(*view); } inline bytes_opt to_bytes_opt(const cql3::raw_value_view& view) { auto buffer_view = view.data(); if (buffer_view) { return bytes_opt(linearized(*buffer_view)); } return bytes_opt(); } inline bytes_opt to_bytes_opt(const cql3::raw_value& value) { return to_bytes_opt(value.to_view()); } <|endoftext|>
<commit_before>#include <iostream> #include <stdexcept> using namespace std; enum class Token { Invalid, Minus, Plus, Mul, Div, Number, End }; Token getToken(const char*& text, bool reverse = false, const char* limit = 0) { // function for parsing tokens // // text: the starting point // reverse: whether to move forward or backwards // limit: the point to stop at when moving backwards while (const auto c = *text) { if (limit && reverse && (text <= limit)) break; reverse ? (--text) : (++text); switch (c) { case ' ': continue; case '-': return Token::Minus; case '+': return Token::Plus; case '*': return Token::Mul; case '/': return Token::Div; } if (c >= '1' && c <= '9') { for (auto c = *text; c >= '0' && c <= '9';) { reverse ? (--text) : (++text); if (limit && reverse && (text <= limit)) break; c = *text; } return Token::Number; } return Token::Invalid; } return Token::End; } int number(const char* start, const char* end) { // function for parsing numbers int result = 0; int sign = 1; //ignore trailing minus if (*end == '-') --end; while (start <= end){ if (*start != ' '){ if (*start == '-'){ sign *= -1; } else { if (*start >= '0' && *start <= '9') result = result * 10 + *start - 48; } } ++start; } return sign * result; } int term(const char* start, const char* end) { // function for parsing terms // function invariant: start <= ptr1 <= ptr2 <= end // current token is between ptr1 and ptr2 if (start == end) return number(start, end); const char* ptr1 = end; const char* ptr2 = end; while (ptr1 > start){ // explanation why the pointer moves backwards is in the readme auto token = getToken(ptr1, true, start); if (token == Token::Mul) { return term(start, ptr1) * number(ptr2, end); } else if (token == Token::Div) { int denominator = number(ptr2, end); if (not denominator) throw std::overflow_error("Exception: zero division"); return term(start, ptr1) / denominator; } if (ptr1 == ptr2) --ptr1; ptr2 = ptr1; } return number(start, end); } int expr(const char* start, const char* end) { // function for parsing expressions // function invariant: start <= ptr1 <= ptr2 <= end // current token is between ptr1 and ptr2 if (start >= end) return 0; // binaryMinus is needed to understand if we need to split the expression bool binaryMinus = false; const char* ptr1 = start; const char* ptr2 = start; while (ptr2 < end){ auto token = getToken(ptr2); if (token == Token::Plus) { return term(start, ptr1) + expr(ptr2, end); } else if ((token == Token::Minus) && binaryMinus){ return term(start, ptr1) + expr(ptr1, end); } binaryMinus = (token == Token::Number) ? true : false; ptr1 = ptr2; } return term(start, end); } int main(int argc, char const *argv[]) { if (argc == 1){ cout << "No expression provided"; return 1; } const char* start = argv[1]; const char* end = start; bool invalid = false; bool NAN = true; auto token = getToken(end); while (token != Token::End) { switch (token) { case Token::Invalid: { invalid = true; break; } case Token::Number: { if (not NAN) invalid = true; NAN = false; break; } case Token::Minus: { NAN = true; break; } default: { if (NAN) invalid = true; NAN = true; } } if (invalid) break; token = getToken(end); } if (invalid || NAN){ cout << "Invalid expression"; return 1; } else { try { cout << expr(start, end); } catch (std::overflow_error e) { std::cout << e.what(); return 1; } } return 0; }<commit_msg>Koshman hw02: fixed numbers starting with 0<commit_after>#include <iostream> #include <stdexcept> using namespace std; enum class Token { Invalid, Minus, Plus, Mul, Div, Number, End }; Token getToken(const char*& text, bool reverse = false, const char* limit = 0) { // function for parsing tokens // // text: the starting point // reverse: whether to move forward or backwards // limit: the point to stop at when moving backwards while (const auto c = *text) { if (limit && reverse && (text <= limit)) break; reverse ? (--text) : (++text); switch (c) { case ' ': continue; case '-': return Token::Minus; case '+': return Token::Plus; case '*': return Token::Mul; case '/': return Token::Div; case '0': return Token::Number; } if (c >= '1' && c <= '9') { for (auto c = *text; c >= '0' && c <= '9';) { reverse ? (--text) : (++text); if (limit && reverse && (text <= limit)) break; c = *text; } return Token::Number; } return Token::Invalid; } return Token::End; } int number(const char* start, const char* end) { // function for parsing numbers int result = 0; int sign = 1; //ignore trailing minus if (*end == '-') --end; while (start <= end){ if (*start != ' '){ if (*start == '-'){ sign *= -1; } else { if (*start >= '0' && *start <= '9') result = result * 10 + *start - 48; } } ++start; } return sign * result; } int term(const char* start, const char* end) { // function for parsing terms // function invariant: start <= ptr1 <= ptr2 <= end // current token is between ptr1 and ptr2 if (start == end) return number(start, end); const char* ptr1 = end; const char* ptr2 = end; while (ptr1 > start){ // explanation why the pointer moves backwards is in the readme auto token = getToken(ptr1, true, start); if (token == Token::Mul) { return term(start, ptr1) * number(ptr2, end); } else if (token == Token::Div) { int denominator = number(ptr2, end); if (not denominator) throw std::overflow_error("Exception: zero division"); return term(start, ptr1) / denominator; } if (ptr1 == ptr2) --ptr1; ptr2 = ptr1; } return number(start, end); } int expr(const char* start, const char* end) { // function for parsing expressions // function invariant: start <= ptr1 <= ptr2 <= end // current token is between ptr1 and ptr2 if (start >= end) return 0; // binaryMinus is needed to understand if we need to split the expression bool binaryMinus = false; const char* ptr1 = start; const char* ptr2 = start; while (ptr2 < end){ auto token = getToken(ptr2); if (token == Token::Plus) { return term(start, ptr1) + expr(ptr2, end); } else if ((token == Token::Minus) && binaryMinus){ return term(start, ptr1) + expr(ptr1, end); } binaryMinus = (token == Token::Number) ? true : false; ptr1 = ptr2; } return term(start, end); } int main(int argc, char const *argv[]) { if (argc == 1){ cout << "No expression provided"; return 1; } const char* start = argv[1]; const char* end = start; bool invalid = false; bool NAN = true; auto token = getToken(end); while (token != Token::End) { switch (token) { case Token::Invalid: { invalid = true; break; } case Token::Number: { if (not NAN) invalid = true; NAN = false; break; } case Token::Minus: { NAN = true; break; } default: { if (NAN) invalid = true; NAN = true; } } if (invalid) break; token = getToken(end); } if (invalid || NAN){ cout << "Invalid expression"; return 1; } else { try { cout << expr(start, end); } catch (std::overflow_error e) { std::cout << e.what(); return 1; } } return 0; }<|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #if qPlatform_Windows #include <windows.h> #elif qPlatform_POSIX #include <dirent.h> #endif #include "../../Debug/Trace.h" #include "../../Execution/ErrNoException.h" #if qPlatform_Windows #include "../../Execution/Platform/Windows/Exception.h" #endif #include "../../IO/FileAccessException.h" #include "DirectoryIterator.h" // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::FileSystem; using namespace Stroika::Foundation::Traversal; #if qPlatform_Windows using Execution::Platform::Windows::ThrowIfFalseGetLastError; #endif using Execution::ThrowIfError_errno_t; class DirectoryIterator::Rep_ : public Iterator<String>::IRep { private: #if qPlatform_Windows String fDirName_; HANDLE fHandle_ { INVALID_HANDLE_VALUE }; WIN32_FIND_DATA fFindFileData_; int fSeekOffset_ { 0 }; #elif qPlatform_POSIX DIR* fDirIt_ { nullptr }; dirent fDirEntBuf_; // intentionally uninitialized (done by readdir) dirent* fCur_ { nullptr }; #endif public: Rep_ (const String& dir) #if qPlatform_Windows : fDirName_ (dir) #elif qPlatform_POSIX : fDirIt_ { ::opendir (dir.AsSDKString ().c_str ()) } #endif { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Entering DirectoryIterator::Rep_::CTOR('%s')", dir.c_str ()); #endif try { #if qPlatform_Windows (void)::memset (&fFindFileData_, 0, sizeof (fFindFileData_)); fHandle_ = ::FindFirstFile ((dir + L"\\*").AsSDKString ().c_str (), &fFindFileData_); #elif qPlatform_POSIX if (fDirIt_ == nullptr) { Execution::ThrowIfError_errno_t (); } else { ThrowIfError_errno_t (::readdir_r (fDirIt_, &fDirEntBuf_, &fCur_)); Assert (fCur_ == nullptr or fCur_ == &fDirEntBuf_); } #endif } Stroika_Foundation_IO_FileAccessException_CATCH_REBIND_FILENAMESONLY_HELPER(dir); } #if qPlatform_Windows Rep_ (const String& dir, int seekPos) : fDirName_ (dir) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Entering DirectoryIterator::Rep_::CTOR('%s',seekPos=%d)", dir.c_str (), seekPos); #endif (void)::memset (&fFindFileData_, 0, sizeof (fFindFileData_)); fHandle_ = ::FindFirstFile ((dir + L"\\*").AsSDKString ().c_str (), &fFindFileData_); for (int i = 0; i < seekPos; ++i) { if (::FindNextFile (fHandle_, &fFindFileData_) == 0) { ::FindClose (fHandle_); fHandle_ = INVALID_HANDLE_VALUE; } else { fSeekOffset_++; } } } #elif qPlatform_POSIX Rep_ (DIR* dirObj) : fDirIt_ { dirObj } { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Entering DirectoryIterator::Rep_::CTOR(dirObj=%x)", int(dirObj)); #endif if (fDirIt_ != nullptr) { ThrowIfError_errno_t (::readdir_r (fDirIt_, &fDirEntBuf_, &fCur_)); Assert (fCur_ == nullptr or fCur_ == &fDirEntBuf_); } } #endif virtual ~Rep_ () { #if qPlatform_Windows if (fHandle_ != INVALID_HANDLE_VALUE) { ::FindClose (fHandle_); } #elif qPlatform_POSIX if (fDirIt_ != nullptr) { ::closedir (fDirIt_); } #endif } virtual void More (Memory::Optional<String>* result, bool advance) override { RequireNotNull (result); result->clear (); #if qPlatform_Windows if (advance) { Require (fHandle_ != INVALID_HANDLE_VALUE); memset (&fFindFileData_, 0, sizeof (fFindFileData_)); if (::FindNextFile (fHandle_, &fFindFileData_) == 0) { ::FindClose (fHandle_); fHandle_ = INVALID_HANDLE_VALUE; } } if (fHandle_ != INVALID_HANDLE_VALUE) { *result = String::FromSDKString (fFindFileData_.cFileName); } #elif qPlatform_POSIX if (advance) { RequireNotNull (fCur_); RequireNotNull (fDirIt_); ThrowIfError_errno_t (::readdir_r (fDirIt_, &fDirEntBuf_, &fCur_)); Assert (fCur_ == nullptr or fCur_ == &fDirEntBuf_); } if (fCur_ != nullptr) { *result = String::FromSDKString (fCur_->d_name); } #endif } virtual bool Equals (const Iterator<String>::IRep* rhs) const override { RequireNotNull (rhs); RequireMember (rhs, Rep_); const Rep_& rrhs = *dynamic_cast<const Rep_*> (rhs); #if qPlatform_Windows return fHandle_ == rrhs.fHandle_; #elif qPlatform_POSIX return fDirIt_ == rrhs.fDirIt_; #endif } virtual SharedIRepPtr Clone () const override { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Entering DirectoryIterator::Rep_::Clone"); #endif #if qPlatform_Windows return SharedIRepPtr (MakeSharedPtr<Rep_> (fDirName_, fSeekOffset_)); #elif qPlatform_POSIX if (fDirIt_ == nullptr) { return SharedIRepPtr (MakeSharedPtr<Rep_> (nullptr)); } /* * must find telldir() returns the location of the NEXT read. We must pass along the value of telldir as * of the PREVIOUS read. Essentially (seek CUR_OFF, -1); * * But - this API doesn't support that. * * This leaves us with several weak alternatives: * o save the telldir, and seek to the start of the dir, and repeatedly seek until * we get the same telldir, and then return the previous stored value. * * o substract 1 from the value of telldir() * * o Before each 'readdir() - do a telldir() to capture its value. * * o When cloning - compute offset in file#s by rewinding and seeking til we find the same value by * name or some such, and then use that same process to re-seek in the cloned dirEnt. * * The 'subtract 1' approach, though cheap and simple, appears not supported by the telldir documentation, * and looking at values in the current linux/gcc, seems unpromising. * * Between the 'telldir' before each read, and re-seek approaches, the former adds overhead even when not cloning * iterators, and the later only when you use the feature. Moreover, the seek-to-start and keep looking * for telldir() approach probably works out efficeintly, as the most likely time to Clone () an iterator is * when it is 'at start' anyhow (DirectoryIterable). So we'll start with that... * -- LGP 2014-07-10 */ // Note - NOT 100% sure its OK to look for identical value telldir in another dir... DIR* dirObj = ::fdopendir (::dirfd (fDirIt_)); dirent dirEntBuf; // intentionally uninitialized (done by readdir) if (fCur_ == nullptr) { // then we're past end end, the cloned fdopen dir one SB too! dirent* d = nullptr; dirent db;// no init on purpose (void)::readdir_r (fDirIt_, &db, &d); Assert (d == nullptr); } else { ino_t aBridgeTooFar = fCur_->d_ino; ::rewinddir (dirObj); long useOffset = ::telldir (dirObj); for (;;) { //dirent* tmp = ::readdir (dirObj); dirent* tmp = nullptr; // ThrowIfError_errno_t (::readdir_r (dirObj, &dirEntBuf, &tmp)); // @todo UNSURE if we want to check error here? ::readdir_r (dirObj, &dirEntBuf, &tmp); Assert (tmp == nullptr or tmp == &dirEntBuf); if (tmp == nullptr) { // somehow the file went away, so no idea where to start, and the end is as reasonable as anywhere else??? useOffset = ::telldir (dirObj); DbgTrace (L"WARN: possible bug? - ususual, and not handled well, but this can happen if the file disappears while we're cloning"); break; } else if (tmp->d_ino == aBridgeTooFar) { // then we are now pointing at the right elt, and want to seek to the PRECEEDING one so when it does a readdir it gets that item // so DONT update useOffset - just break! break; } else { // update to this reflects the last offset before we find d_ino useOffset = ::telldir (dirObj); } } ::seekdir (dirObj, useOffset); } return SharedIRepPtr (MakeSharedPtr<Rep_> (dirObj)); #endif } virtual IteratorOwnerID GetOwner () const override { /* * This return value allows any two DiscreteRange iterators (of the same type) to be compared. */ return typeid (*this).name (); } }; /* ******************************************************************************** ******************** IO::FileSystem::DirectoryIterator ************************* ******************************************************************************** */ DirectoryIterator::DirectoryIterator (const String& directoryName) : Iterator<String> (Iterator<String>::SharedIRepPtr (MakeSharedPtr<Rep_> (directoryName))) { } <commit_msg>allow EBADF and dont throw on iterator - appears legal by docs (unclear) and happens on AIX at EOF. Just add asserts<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #if qPlatform_Windows #include <windows.h> #elif qPlatform_POSIX #include <dirent.h> #endif #include "../../Debug/Trace.h" #include "../../Execution/ErrNoException.h" #if qPlatform_Windows #include "../../Execution/Platform/Windows/Exception.h" #endif #include "../../IO/FileAccessException.h" #include "DirectoryIterator.h" // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::FileSystem; using namespace Stroika::Foundation::Traversal; #if qPlatform_Windows using Execution::Platform::Windows::ThrowIfFalseGetLastError; #endif using Execution::ThrowIfError_errno_t; class DirectoryIterator::Rep_ : public Iterator<String>::IRep { private: #if qPlatform_Windows String fDirName_; HANDLE fHandle_ { INVALID_HANDLE_VALUE }; WIN32_FIND_DATA fFindFileData_; int fSeekOffset_ { 0 }; #elif qPlatform_POSIX DIR* fDirIt_ { nullptr }; dirent fDirEntBuf_; // intentionally uninitialized (done by readdir) dirent* fCur_ { nullptr }; #endif public: Rep_ (const String& dir) #if qPlatform_Windows : fDirName_ (dir) #elif qPlatform_POSIX : fDirIt_ { ::opendir (dir.AsSDKString ().c_str ()) } #endif { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Entering DirectoryIterator::Rep_::CTOR('%s')", dir.c_str ()); #endif try { #if qPlatform_Windows (void)::memset (&fFindFileData_, 0, sizeof (fFindFileData_)); fHandle_ = ::FindFirstFile ((dir + L"\\*").AsSDKString ().c_str (), &fFindFileData_); #elif qPlatform_POSIX if (fDirIt_ == nullptr) { Execution::ThrowIfError_errno_t (); } else { ThrowIfError_errno_t (::readdir_r (fDirIt_, &fDirEntBuf_, &fCur_)); Assert (fCur_ == nullptr or fCur_ == &fDirEntBuf_); } #endif } Stroika_Foundation_IO_FileAccessException_CATCH_REBIND_FILENAMESONLY_HELPER(dir); } #if qPlatform_Windows Rep_ (const String& dir, int seekPos) : fDirName_ (dir) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Entering DirectoryIterator::Rep_::CTOR('%s',seekPos=%d)", dir.c_str (), seekPos); #endif (void)::memset (&fFindFileData_, 0, sizeof (fFindFileData_)); fHandle_ = ::FindFirstFile ((dir + L"\\*").AsSDKString ().c_str (), &fFindFileData_); for (int i = 0; i < seekPos; ++i) { if (::FindNextFile (fHandle_, &fFindFileData_) == 0) { ::FindClose (fHandle_); fHandle_ = INVALID_HANDLE_VALUE; } else { fSeekOffset_++; } } } #elif qPlatform_POSIX Rep_ (DIR* dirObj) : fDirIt_ { dirObj } { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Entering DirectoryIterator::Rep_::CTOR(dirObj=%x)", int(dirObj)); #endif if (fDirIt_ != nullptr) { ThrowIfError_errno_t (::readdir_r (fDirIt_, &fDirEntBuf_, &fCur_)); Assert (fCur_ == nullptr or fCur_ == &fDirEntBuf_); } } #endif virtual ~Rep_ () { #if qPlatform_Windows if (fHandle_ != INVALID_HANDLE_VALUE) { ::FindClose (fHandle_); } #elif qPlatform_POSIX if (fDirIt_ != nullptr) { ::closedir (fDirIt_); } #endif } virtual void More (Memory::Optional<String>* result, bool advance) override { RequireNotNull (result); result->clear (); #if qPlatform_Windows if (advance) { Require (fHandle_ != INVALID_HANDLE_VALUE); memset (&fFindFileData_, 0, sizeof (fFindFileData_)); if (::FindNextFile (fHandle_, &fFindFileData_) == 0) { ::FindClose (fHandle_); fHandle_ = INVALID_HANDLE_VALUE; } } if (fHandle_ != INVALID_HANDLE_VALUE) { *result = String::FromSDKString (fFindFileData_.cFileName); } #elif qPlatform_POSIX if (advance) { RequireNotNull (fCur_); RequireNotNull (fDirIt_); errno_t e = ::readdir_r (fDirIt_, &fDirEntBuf_, &fCur_); if (e == EBADF) { Assert (fCur_ == nullptr ); } else { ThrowIfError_errno_t (e); } Assert (fCur_ == nullptr or fCur_ == &fDirEntBuf_); } if (fCur_ != nullptr) { *result = String::FromSDKString (fCur_->d_name); } #endif } virtual bool Equals (const Iterator<String>::IRep* rhs) const override { RequireNotNull (rhs); RequireMember (rhs, Rep_); const Rep_& rrhs = *dynamic_cast<const Rep_*> (rhs); #if qPlatform_Windows return fHandle_ == rrhs.fHandle_; #elif qPlatform_POSIX return fDirIt_ == rrhs.fDirIt_; #endif } virtual SharedIRepPtr Clone () const override { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Entering DirectoryIterator::Rep_::Clone"); #endif #if qPlatform_Windows return SharedIRepPtr (MakeSharedPtr<Rep_> (fDirName_, fSeekOffset_)); #elif qPlatform_POSIX if (fDirIt_ == nullptr) { return SharedIRepPtr (MakeSharedPtr<Rep_> (nullptr)); } /* * must find telldir() returns the location of the NEXT read. We must pass along the value of telldir as * of the PREVIOUS read. Essentially (seek CUR_OFF, -1); * * But - this API doesn't support that. * * This leaves us with several weak alternatives: * o save the telldir, and seek to the start of the dir, and repeatedly seek until * we get the same telldir, and then return the previous stored value. * * o substract 1 from the value of telldir() * * o Before each 'readdir() - do a telldir() to capture its value. * * o When cloning - compute offset in file#s by rewinding and seeking til we find the same value by * name or some such, and then use that same process to re-seek in the cloned dirEnt. * * The 'subtract 1' approach, though cheap and simple, appears not supported by the telldir documentation, * and looking at values in the current linux/gcc, seems unpromising. * * Between the 'telldir' before each read, and re-seek approaches, the former adds overhead even when not cloning * iterators, and the later only when you use the feature. Moreover, the seek-to-start and keep looking * for telldir() approach probably works out efficeintly, as the most likely time to Clone () an iterator is * when it is 'at start' anyhow (DirectoryIterable). So we'll start with that... * -- LGP 2014-07-10 */ // Note - NOT 100% sure its OK to look for identical value telldir in another dir... DIR* dirObj = ::fdopendir (::dirfd (fDirIt_)); dirent dirEntBuf; // intentionally uninitialized (done by readdir) if (fCur_ == nullptr) { // then we're past end end, the cloned fdopen dir one SB too! dirent* d = nullptr; dirent db;// no init on purpose (void)::readdir_r (fDirIt_, &db, &d); Assert (d == nullptr); } else { ino_t aBridgeTooFar = fCur_->d_ino; ::rewinddir (dirObj); long useOffset = ::telldir (dirObj); for (;;) { //dirent* tmp = ::readdir (dirObj); dirent* tmp = nullptr; // ThrowIfError_errno_t (::readdir_r (dirObj, &dirEntBuf, &tmp)); // @todo UNSURE if we want to check error here? ::readdir_r (dirObj, &dirEntBuf, &tmp); Assert (tmp == nullptr or tmp == &dirEntBuf); if (tmp == nullptr) { // somehow the file went away, so no idea where to start, and the end is as reasonable as anywhere else??? useOffset = ::telldir (dirObj); DbgTrace (L"WARN: possible bug? - ususual, and not handled well, but this can happen if the file disappears while we're cloning"); break; } else if (tmp->d_ino == aBridgeTooFar) { // then we are now pointing at the right elt, and want to seek to the PRECEEDING one so when it does a readdir it gets that item // so DONT update useOffset - just break! break; } else { // update to this reflects the last offset before we find d_ino useOffset = ::telldir (dirObj); } } ::seekdir (dirObj, useOffset); } return SharedIRepPtr (MakeSharedPtr<Rep_> (dirObj)); #endif } virtual IteratorOwnerID GetOwner () const override { /* * This return value allows any two DiscreteRange iterators (of the same type) to be compared. */ return typeid (*this).name (); } }; /* ******************************************************************************** ******************** IO::FileSystem::DirectoryIterator ************************* ******************************************************************************** */ DirectoryIterator::DirectoryIterator (const String& directoryName) : Iterator<String> (Iterator<String>::SharedIRepPtr (MakeSharedPtr<Rep_> (directoryName))) { } <|endoftext|>
<commit_before>// Copyright (c) 2009-2018 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. #include "IntegratorHPMC.h" namespace py = pybind11; #include "hoomd/VectorMath.h" #include <sstream> using namespace std; /*! \file IntegratorHPMC.cc \brief Definition of common methods for HPMC integrators */ namespace hpmc { IntegratorHPMC::IntegratorHPMC(std::shared_ptr<SystemDefinition> sysdef, unsigned int seed) : Integrator(sysdef, 0.005), m_seed(seed), m_move_ratio(32768), m_nselect(4), m_nominal_width(1.0), m_extra_ghost_width(0), m_external_base(NULL), m_patch_log(false), m_jit_force_log(false), m_past_first_run(false) #ifdef ENABLE_MPI ,m_communicator_ghost_width_connected(false), m_communicator_flags_connected(false) #endif { m_exec_conf->msg->notice(5) << "Constructing IntegratorHPMC" << endl; // broadcast the seed from rank 0 to all other ranks. #ifdef ENABLE_MPI if(this->m_pdata->getDomainDecomposition()) bcast(m_seed, 0, this->m_exec_conf->getMPICommunicator()); #endif GPUArray<hpmc_counters_t> counters(1, this->m_exec_conf); m_count_total.swap(counters); GPUVector<Scalar> d(this->m_pdata->getNTypes(), this->m_exec_conf); m_d.swap(d); GPUVector<Scalar> a(this->m_pdata->getNTypes(), this->m_exec_conf); m_a.swap(a); ArrayHandle<Scalar> h_d(m_d, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_a(m_a, access_location::host, access_mode::overwrite); //set default values for(unsigned int typ=0; typ < this->m_pdata->getNTypes(); typ++) { h_d.data[typ]=0.1; h_a.data[typ]=0.1; } // Connect to number of types change signal m_pdata->getNumTypesChangeSignal().connect<IntegratorHPMC, &IntegratorHPMC::slotNumTypesChange>(this); resetStats(); } IntegratorHPMC::~IntegratorHPMC() { m_exec_conf->msg->notice(5) << "Destroying IntegratorHPMC" << endl; m_pdata->getNumTypesChangeSignal().disconnect<IntegratorHPMC, &IntegratorHPMC::slotNumTypesChange>(this); #ifdef ENABLE_MPI if (m_communicator_ghost_width_connected) m_comm->getGhostLayerWidthRequestSignal().disconnect<IntegratorHPMC, &IntegratorHPMC::getGhostLayerWidth>(this); if (m_communicator_flags_connected) m_comm->getCommFlagsRequestSignal().disconnect<IntegratorHPMC, &IntegratorHPMC::getCommFlags>(this); #endif } void IntegratorHPMC::slotNumTypesChange() { // old size of arrays unsigned int old_ntypes = m_a.size(); assert(m_a.size() == m_d.size()); unsigned int ntypes = m_pdata->getNTypes(); m_a.resize(ntypes); m_d.resize(ntypes); //set default values for newly added types ArrayHandle<Scalar> h_d(m_d, access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_a(m_a, access_location::host, access_mode::readwrite); for(unsigned int typ=old_ntypes; typ < ntypes; typ++) { h_d.data[typ]=0.1; h_a.data[typ]=0.1; } } /*! IntegratorHPMC provides: - hpmc_sweep (Number of sweeps completed) - hpmc_translate_acceptance (Ratio of translation moves accepted in the last step) - hpmc_rotate_acceptance (Ratio of rotation moves accepted in the last step) - hpmc_d (maximum move displacement) - hpmc_a (maximum rotation move) - hpmc_d_<typename> (maximum move displacement by type) - hpmc_a_<typename> (maximum rotation move by type) - hpmc_move_ratio (ratio of translation moves to rotate moves) - hpmc_overlap_count (count of the number of particle-particle overlaps) \returns a list of provided quantities */ std::vector< std::string > IntegratorHPMC::getProvidedLogQuantities() { // start with the integrator provided quantities std::vector< std::string > result = Integrator::getProvidedLogQuantities(); // then add ours result.push_back("hpmc_sweep"); result.push_back("hpmc_translate_acceptance"); result.push_back("hpmc_rotate_acceptance"); result.push_back("hpmc_d"); result.push_back("hpmc_a"); result.push_back("hpmc_move_ratio"); result.push_back("hpmc_overlap_count"); for (unsigned int typ=0; typ<m_pdata->getNTypes();typ++) { ostringstream tmp_str0; tmp_str0<<"hpmc_d_"<<m_pdata->getNameByType(typ); result.push_back(tmp_str0.str()); ostringstream tmp_str1; tmp_str1<<"hpmc_a_"<<m_pdata->getNameByType(typ); result.push_back(tmp_str1.str()); } return result; } /*! \param quantity Name of the log quantity to get \param timestep Current time step of the simulation \return the requested log quantity. */ Scalar IntegratorHPMC::getLogValue(const std::string& quantity, unsigned int timestep) { hpmc_counters_t counters = getCounters(2); if (quantity == "hpmc_sweep") { hpmc_counters_t counters_total = getCounters(0); return double(counters_total.getNMoves()) / double(m_pdata->getNGlobal()); } else if (quantity == "hpmc_translate_acceptance") { return counters.getTranslateAcceptance(); } else if (quantity == "hpmc_rotate_acceptance") { return counters.getRotateAcceptance(); } else if (quantity == "hpmc_d") { ArrayHandle<Scalar> h_d(m_d, access_location::host, access_mode::read); return h_d.data[0]; } else if (quantity == "hpmc_a") { ArrayHandle<Scalar> h_a(m_a, access_location::host, access_mode::read); return h_a.data[0]; } else if (quantity == "hpmc_move_ratio") { return getMoveRatio(); } else if (quantity == "hpmc_overlap_count") { return countOverlaps(timestep, false); } else { //loop over per particle move size quantities for (unsigned int typ=0; typ<m_pdata->getNTypes();typ++) { ostringstream tmp_str0; tmp_str0<<"hpmc_d_"<<m_pdata->getNameByType(typ); if (quantity==tmp_str0.str()) { ArrayHandle<Scalar> h_d(m_d, access_location::host, access_mode::read); return h_d.data[typ]; } ostringstream tmp_str1; tmp_str1<<"hpmc_a_"<<m_pdata->getNameByType(typ); if (quantity==tmp_str1.str()) { ArrayHandle<Scalar> h_a(m_a, access_location::host, access_mode::read); return h_a.data[typ]; } } //nothing found -> pass on to integrator return Integrator::getLogValue(quantity, timestep); } } /*! \returns True if the particle orientations are normalized */ bool IntegratorHPMC::checkParticleOrientations() { // get the orientations data array ArrayHandle<Scalar4> h_orientation(m_pdata->getOrientationArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_tag(m_pdata->getTags(), access_location::host, access_mode::read); bool result = true; // loop through particles and return false if any is out of norm for (unsigned int i = 0; i < m_pdata->getN(); i++) { quat<Scalar> o(h_orientation.data[i]); if (fabs(Scalar(1.0) - norm2(o)) > 1e-3) { m_exec_conf->msg->notice(2) << "Particle " << h_tag.data[i] << " has an unnormalized orientation" << endl; result = false; } } #ifdef ENABLE_MPI unsigned int result_int = (unsigned int)result; unsigned int result_reduced; MPI_Reduce(&result_int, &result_reduced, 1, MPI_UNSIGNED, MPI_LOR, 0, m_exec_conf->getMPICommunicator()); result = bool(result_reduced); #endif return result; } /*! Set new box with particle positions scaled from previous box and check for overlaps \param newBox new box dimensions \note The particle positions and the box dimensions are updated in any case, even if the new box dimensions result in overlaps. To restore old particle positions, they have to be backed up before calling this method. \returns false if resize results in overlaps */ bool IntegratorHPMC::attemptBoxResize(unsigned int timestep, const BoxDim& new_box) { unsigned int N = m_pdata->getN(); // Get old and new boxes; BoxDim curBox = m_pdata->getGlobalBox(); // Use lexical scope block to make sure ArrayHandles get cleaned up { // Get particle positions ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(), access_location::host, access_mode::readwrite); // move the particles to be inside the new box for (unsigned int i = 0; i < N; i++) { Scalar3 old_pos = make_scalar3(h_pos.data[i].x, h_pos.data[i].y, h_pos.data[i].z); // obtain scaled coordinates in the old global box Scalar3 f = curBox.makeFraction(old_pos); // scale particles Scalar3 scaled_pos = new_box.makeCoordinates(f); h_pos.data[i].x = scaled_pos.x; h_pos.data[i].y = scaled_pos.y; h_pos.data[i].z = scaled_pos.z; } } // end lexical scope m_pdata->setGlobalBox(new_box); // we have moved particles, communicate those changes this->communicate(false); // check overlaps return !this->countOverlaps(timestep, true); } /*! \param mode 0 -> Absolute count, 1 -> relative to the start of the run, 2 -> relative to the last executed step \return The current state of the acceptance counters IntegratorHPMC maintains a count of the number of accepted and rejected moves since instantiation. getCounters() provides the current value. The parameter *mode* controls whether the returned counts are absolute, relative to the start of the run, or relative to the start of the last executed step. */ hpmc_counters_t IntegratorHPMC::getCounters(unsigned int mode) { ArrayHandle<hpmc_counters_t> h_counters(m_count_total, access_location::host, access_mode::read); hpmc_counters_t result; if (mode == 0) result = h_counters.data[0]; else if (mode == 1) result = h_counters.data[0] - m_count_run_start; else result = h_counters.data[0] - m_count_step_start; #ifdef ENABLE_MPI if (m_comm) { // MPI Reduction to total result values on all nodes. MPI_Allreduce(MPI_IN_PLACE, &result.translate_accept_count, 1, MPI_LONG_LONG_INT, MPI_SUM, m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.translate_reject_count, 1, MPI_LONG_LONG_INT, MPI_SUM, m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.rotate_accept_count, 1, MPI_LONG_LONG_INT, MPI_SUM, m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.rotate_reject_count, 1, MPI_LONG_LONG_INT, MPI_SUM, m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.overlap_checks, 1, MPI_LONG_LONG_INT, MPI_SUM, m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.overlap_err_count, 1, MPI_UNSIGNED, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif return result; } void export_IntegratorHPMC(py::module& m) { py::class_<IntegratorHPMC, std::shared_ptr< IntegratorHPMC > >(m, "IntegratorHPMC", py::base<Integrator>()) .def(py::init< std::shared_ptr<SystemDefinition>, unsigned int >()) .def("setD", &IntegratorHPMC::setD) .def("setA", &IntegratorHPMC::setA) .def("setMoveRatio", &IntegratorHPMC::setMoveRatio) .def("setNSelect", &IntegratorHPMC::setNSelect) .def("getD", &IntegratorHPMC::getD) .def("getA", &IntegratorHPMC::getA) .def("getMoveRatio", &IntegratorHPMC::getMoveRatio) .def("getNSelect", &IntegratorHPMC::getNSelect) .def("getMaxCoreDiameter", &IntegratorHPMC::getMaxCoreDiameter) .def("countOverlaps", &IntegratorHPMC::countOverlaps) .def("checkParticleOrientations", &IntegratorHPMC::checkParticleOrientations) .def("getMPS", &IntegratorHPMC::getMPS) .def("getCounters", &IntegratorHPMC::getCounters) .def("communicate", &IntegratorHPMC::communicate) .def("slotNumTypesChange", &IntegratorHPMC::slotNumTypesChange) .def("setDeterministic", &IntegratorHPMC::setDeterministic) .def("disablePatchEnergyLogOnly", &IntegratorHPMC::disablePatchEnergyLogOnly) .def("disableForceEnergyLogOnly", &IntegratorHPMC::disablePatchEnergyLogOnly) ; py::class_< hpmc_counters_t >(m, "hpmc_counters_t") .def_readwrite("translate_accept_count", &hpmc_counters_t::translate_accept_count) .def_readwrite("translate_reject_count", &hpmc_counters_t::translate_reject_count) .def_readwrite("rotate_accept_count", &hpmc_counters_t::rotate_accept_count) .def_readwrite("rotate_reject_count", &hpmc_counters_t::rotate_reject_count) .def_readwrite("overlap_checks", &hpmc_counters_t::overlap_checks) .def("getTranslateAcceptance", &hpmc_counters_t::getTranslateAcceptance) .def("getRotateAcceptance", &hpmc_counters_t::getRotateAcceptance) .def("getNMoves", &hpmc_counters_t::getNMoves) ; } } // end namespace hpmc <commit_msg>Fix another typo<commit_after>// Copyright (c) 2009-2018 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. #include "IntegratorHPMC.h" namespace py = pybind11; #include "hoomd/VectorMath.h" #include <sstream> using namespace std; /*! \file IntegratorHPMC.cc \brief Definition of common methods for HPMC integrators */ namespace hpmc { IntegratorHPMC::IntegratorHPMC(std::shared_ptr<SystemDefinition> sysdef, unsigned int seed) : Integrator(sysdef, 0.005), m_seed(seed), m_move_ratio(32768), m_nselect(4), m_nominal_width(1.0), m_extra_ghost_width(0), m_external_base(NULL), m_patch_log(false), m_jit_force_log(false), m_past_first_run(false) #ifdef ENABLE_MPI ,m_communicator_ghost_width_connected(false), m_communicator_flags_connected(false) #endif { m_exec_conf->msg->notice(5) << "Constructing IntegratorHPMC" << endl; // broadcast the seed from rank 0 to all other ranks. #ifdef ENABLE_MPI if(this->m_pdata->getDomainDecomposition()) bcast(m_seed, 0, this->m_exec_conf->getMPICommunicator()); #endif GPUArray<hpmc_counters_t> counters(1, this->m_exec_conf); m_count_total.swap(counters); GPUVector<Scalar> d(this->m_pdata->getNTypes(), this->m_exec_conf); m_d.swap(d); GPUVector<Scalar> a(this->m_pdata->getNTypes(), this->m_exec_conf); m_a.swap(a); ArrayHandle<Scalar> h_d(m_d, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_a(m_a, access_location::host, access_mode::overwrite); //set default values for(unsigned int typ=0; typ < this->m_pdata->getNTypes(); typ++) { h_d.data[typ]=0.1; h_a.data[typ]=0.1; } // Connect to number of types change signal m_pdata->getNumTypesChangeSignal().connect<IntegratorHPMC, &IntegratorHPMC::slotNumTypesChange>(this); resetStats(); } IntegratorHPMC::~IntegratorHPMC() { m_exec_conf->msg->notice(5) << "Destroying IntegratorHPMC" << endl; m_pdata->getNumTypesChangeSignal().disconnect<IntegratorHPMC, &IntegratorHPMC::slotNumTypesChange>(this); #ifdef ENABLE_MPI if (m_communicator_ghost_width_connected) m_comm->getGhostLayerWidthRequestSignal().disconnect<IntegratorHPMC, &IntegratorHPMC::getGhostLayerWidth>(this); if (m_communicator_flags_connected) m_comm->getCommFlagsRequestSignal().disconnect<IntegratorHPMC, &IntegratorHPMC::getCommFlags>(this); #endif } void IntegratorHPMC::slotNumTypesChange() { // old size of arrays unsigned int old_ntypes = m_a.size(); assert(m_a.size() == m_d.size()); unsigned int ntypes = m_pdata->getNTypes(); m_a.resize(ntypes); m_d.resize(ntypes); //set default values for newly added types ArrayHandle<Scalar> h_d(m_d, access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_a(m_a, access_location::host, access_mode::readwrite); for(unsigned int typ=old_ntypes; typ < ntypes; typ++) { h_d.data[typ]=0.1; h_a.data[typ]=0.1; } } /*! IntegratorHPMC provides: - hpmc_sweep (Number of sweeps completed) - hpmc_translate_acceptance (Ratio of translation moves accepted in the last step) - hpmc_rotate_acceptance (Ratio of rotation moves accepted in the last step) - hpmc_d (maximum move displacement) - hpmc_a (maximum rotation move) - hpmc_d_<typename> (maximum move displacement by type) - hpmc_a_<typename> (maximum rotation move by type) - hpmc_move_ratio (ratio of translation moves to rotate moves) - hpmc_overlap_count (count of the number of particle-particle overlaps) \returns a list of provided quantities */ std::vector< std::string > IntegratorHPMC::getProvidedLogQuantities() { // start with the integrator provided quantities std::vector< std::string > result = Integrator::getProvidedLogQuantities(); // then add ours result.push_back("hpmc_sweep"); result.push_back("hpmc_translate_acceptance"); result.push_back("hpmc_rotate_acceptance"); result.push_back("hpmc_d"); result.push_back("hpmc_a"); result.push_back("hpmc_move_ratio"); result.push_back("hpmc_overlap_count"); for (unsigned int typ=0; typ<m_pdata->getNTypes();typ++) { ostringstream tmp_str0; tmp_str0<<"hpmc_d_"<<m_pdata->getNameByType(typ); result.push_back(tmp_str0.str()); ostringstream tmp_str1; tmp_str1<<"hpmc_a_"<<m_pdata->getNameByType(typ); result.push_back(tmp_str1.str()); } return result; } /*! \param quantity Name of the log quantity to get \param timestep Current time step of the simulation \return the requested log quantity. */ Scalar IntegratorHPMC::getLogValue(const std::string& quantity, unsigned int timestep) { hpmc_counters_t counters = getCounters(2); if (quantity == "hpmc_sweep") { hpmc_counters_t counters_total = getCounters(0); return double(counters_total.getNMoves()) / double(m_pdata->getNGlobal()); } else if (quantity == "hpmc_translate_acceptance") { return counters.getTranslateAcceptance(); } else if (quantity == "hpmc_rotate_acceptance") { return counters.getRotateAcceptance(); } else if (quantity == "hpmc_d") { ArrayHandle<Scalar> h_d(m_d, access_location::host, access_mode::read); return h_d.data[0]; } else if (quantity == "hpmc_a") { ArrayHandle<Scalar> h_a(m_a, access_location::host, access_mode::read); return h_a.data[0]; } else if (quantity == "hpmc_move_ratio") { return getMoveRatio(); } else if (quantity == "hpmc_overlap_count") { return countOverlaps(timestep, false); } else { //loop over per particle move size quantities for (unsigned int typ=0; typ<m_pdata->getNTypes();typ++) { ostringstream tmp_str0; tmp_str0<<"hpmc_d_"<<m_pdata->getNameByType(typ); if (quantity==tmp_str0.str()) { ArrayHandle<Scalar> h_d(m_d, access_location::host, access_mode::read); return h_d.data[typ]; } ostringstream tmp_str1; tmp_str1<<"hpmc_a_"<<m_pdata->getNameByType(typ); if (quantity==tmp_str1.str()) { ArrayHandle<Scalar> h_a(m_a, access_location::host, access_mode::read); return h_a.data[typ]; } } //nothing found -> pass on to integrator return Integrator::getLogValue(quantity, timestep); } } /*! \returns True if the particle orientations are normalized */ bool IntegratorHPMC::checkParticleOrientations() { // get the orientations data array ArrayHandle<Scalar4> h_orientation(m_pdata->getOrientationArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_tag(m_pdata->getTags(), access_location::host, access_mode::read); bool result = true; // loop through particles and return false if any is out of norm for (unsigned int i = 0; i < m_pdata->getN(); i++) { quat<Scalar> o(h_orientation.data[i]); if (fabs(Scalar(1.0) - norm2(o)) > 1e-3) { m_exec_conf->msg->notice(2) << "Particle " << h_tag.data[i] << " has an unnormalized orientation" << endl; result = false; } } #ifdef ENABLE_MPI unsigned int result_int = (unsigned int)result; unsigned int result_reduced; MPI_Reduce(&result_int, &result_reduced, 1, MPI_UNSIGNED, MPI_LOR, 0, m_exec_conf->getMPICommunicator()); result = bool(result_reduced); #endif return result; } /*! Set new box with particle positions scaled from previous box and check for overlaps \param newBox new box dimensions \note The particle positions and the box dimensions are updated in any case, even if the new box dimensions result in overlaps. To restore old particle positions, they have to be backed up before calling this method. \returns false if resize results in overlaps */ bool IntegratorHPMC::attemptBoxResize(unsigned int timestep, const BoxDim& new_box) { unsigned int N = m_pdata->getN(); // Get old and new boxes; BoxDim curBox = m_pdata->getGlobalBox(); // Use lexical scope block to make sure ArrayHandles get cleaned up { // Get particle positions ArrayHandle<Scalar4> h_pos(m_pdata->getPositions(), access_location::host, access_mode::readwrite); // move the particles to be inside the new box for (unsigned int i = 0; i < N; i++) { Scalar3 old_pos = make_scalar3(h_pos.data[i].x, h_pos.data[i].y, h_pos.data[i].z); // obtain scaled coordinates in the old global box Scalar3 f = curBox.makeFraction(old_pos); // scale particles Scalar3 scaled_pos = new_box.makeCoordinates(f); h_pos.data[i].x = scaled_pos.x; h_pos.data[i].y = scaled_pos.y; h_pos.data[i].z = scaled_pos.z; } } // end lexical scope m_pdata->setGlobalBox(new_box); // we have moved particles, communicate those changes this->communicate(false); // check overlaps return !this->countOverlaps(timestep, true); } /*! \param mode 0 -> Absolute count, 1 -> relative to the start of the run, 2 -> relative to the last executed step \return The current state of the acceptance counters IntegratorHPMC maintains a count of the number of accepted and rejected moves since instantiation. getCounters() provides the current value. The parameter *mode* controls whether the returned counts are absolute, relative to the start of the run, or relative to the start of the last executed step. */ hpmc_counters_t IntegratorHPMC::getCounters(unsigned int mode) { ArrayHandle<hpmc_counters_t> h_counters(m_count_total, access_location::host, access_mode::read); hpmc_counters_t result; if (mode == 0) result = h_counters.data[0]; else if (mode == 1) result = h_counters.data[0] - m_count_run_start; else result = h_counters.data[0] - m_count_step_start; #ifdef ENABLE_MPI if (m_comm) { // MPI Reduction to total result values on all nodes. MPI_Allreduce(MPI_IN_PLACE, &result.translate_accept_count, 1, MPI_LONG_LONG_INT, MPI_SUM, m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.translate_reject_count, 1, MPI_LONG_LONG_INT, MPI_SUM, m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.rotate_accept_count, 1, MPI_LONG_LONG_INT, MPI_SUM, m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.rotate_reject_count, 1, MPI_LONG_LONG_INT, MPI_SUM, m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.overlap_checks, 1, MPI_LONG_LONG_INT, MPI_SUM, m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.overlap_err_count, 1, MPI_UNSIGNED, MPI_SUM, m_exec_conf->getMPICommunicator()); } #endif return result; } void export_IntegratorHPMC(py::module& m) { py::class_<IntegratorHPMC, std::shared_ptr< IntegratorHPMC > >(m, "IntegratorHPMC", py::base<Integrator>()) .def(py::init< std::shared_ptr<SystemDefinition>, unsigned int >()) .def("setD", &IntegratorHPMC::setD) .def("setA", &IntegratorHPMC::setA) .def("setMoveRatio", &IntegratorHPMC::setMoveRatio) .def("setNSelect", &IntegratorHPMC::setNSelect) .def("getD", &IntegratorHPMC::getD) .def("getA", &IntegratorHPMC::getA) .def("getMoveRatio", &IntegratorHPMC::getMoveRatio) .def("getNSelect", &IntegratorHPMC::getNSelect) .def("getMaxCoreDiameter", &IntegratorHPMC::getMaxCoreDiameter) .def("countOverlaps", &IntegratorHPMC::countOverlaps) .def("checkParticleOrientations", &IntegratorHPMC::checkParticleOrientations) .def("getMPS", &IntegratorHPMC::getMPS) .def("getCounters", &IntegratorHPMC::getCounters) .def("communicate", &IntegratorHPMC::communicate) .def("slotNumTypesChange", &IntegratorHPMC::slotNumTypesChange) .def("setDeterministic", &IntegratorHPMC::setDeterministic) .def("disablePatchEnergyLogOnly", &IntegratorHPMC::disablePatchEnergyLogOnly) .def("disableForceEnergyLogOnly", &IntegratorHPMC::disableForceEnergyLogOnly) ; py::class_< hpmc_counters_t >(m, "hpmc_counters_t") .def_readwrite("translate_accept_count", &hpmc_counters_t::translate_accept_count) .def_readwrite("translate_reject_count", &hpmc_counters_t::translate_reject_count) .def_readwrite("rotate_accept_count", &hpmc_counters_t::rotate_accept_count) .def_readwrite("rotate_reject_count", &hpmc_counters_t::rotate_reject_count) .def_readwrite("overlap_checks", &hpmc_counters_t::overlap_checks) .def("getTranslateAcceptance", &hpmc_counters_t::getTranslateAcceptance) .def("getRotateAcceptance", &hpmc_counters_t::getRotateAcceptance) .def("getNMoves", &hpmc_counters_t::getNMoves) ; } } // end namespace hpmc <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: vcldata.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: ihi $ $Date: 2007-07-10 15:19:05 $ * * 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_svtools.hxx" #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _SV_SETTINGS_HXX #include <vcl/settings.hxx> #endif #ifndef _SVTOOLS_SVTDATA_HXX #include <svtools/svtdata.hxx> #endif //============================================================================ // // class ImpSvtData // //============================================================================ ResMgr * ImpSvtData::GetResMgr() { return GetResMgr(Application::GetSettings().GetUILocale()); } ResMgr * ImpSvtData::GetPatchResMgr() { return GetPatchResMgr(Application::GetSettings().GetUILocale()); } SvpResId::SvpResId( USHORT nId ) : ResId( nId, *ImpSvtData::GetSvtData().GetPatchResMgr() ) { } <commit_msg>INTEGRATION: CWS changefileheader (1.9.228); FILE MERGED 2008/04/01 15:45:20 thb 1.9.228.3: #i85898# Stripping all external header guards 2008/04/01 12:43:49 thb 1.9.228.2: #i85898# Stripping all external header guards 2008/03/31 13:02:19 rt 1.9.228.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: vcldata.cxx,v $ * $Revision: 1.10 $ * * 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_svtools.hxx" #include <vcl/svapp.hxx> #include <vcl/settings.hxx> #include <svtools/svtdata.hxx> //============================================================================ // // class ImpSvtData // //============================================================================ ResMgr * ImpSvtData::GetResMgr() { return GetResMgr(Application::GetSettings().GetUILocale()); } ResMgr * ImpSvtData::GetPatchResMgr() { return GetPatchResMgr(Application::GetSettings().GetUILocale()); } SvpResId::SvpResId( USHORT nId ) : ResId( nId, *ImpSvtData::GetSvtData().GetPatchResMgr() ) { } <|endoftext|>
<commit_before>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/gst.h> #include "KmsHttpLoop.h" #define NAME "httploop" GST_DEBUG_CATEGORY_STATIC (kms_http_loop_debug_category); #define GST_CAT_DEFAULT kms_http_loop_debug_category G_DEFINE_TYPE_WITH_CODE (KmsHttpLoop, kms_http_loop, G_TYPE_OBJECT, GST_DEBUG_CATEGORY_INIT (kms_http_loop_debug_category, NAME, 0, "debug category for kurento loop") ) #define KMS_HTTP_LOOP_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), KMS_TYPE_HTTP_LOOP, KmsHttpLoopPrivate)) struct _KmsHttpLoopPrivate { GThread *thread; GRecMutex rmutex; GMainLoop *loop; GMainContext *context; GCond cond; GMutex mutex; gboolean initialized; }; #define KMS_HTTP_LOOP_LOCK(elem) \ (g_rec_mutex_lock (&KMS_HTTP_LOOP ((elem))->priv->rmutex)) #define KMS_HTTP_LOOP_UNLOCK(elem) \ (g_rec_mutex_unlock (&KMS_HTTP_LOOP ((elem))->priv->rmutex)) /* Object properties */ enum { PROP_0, PROP_CONTEXT, N_PROPERTIES }; static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, }; static gboolean quit_main_loop (GMainLoop *loop) { GST_DEBUG ("Exiting main loop"); g_main_loop_quit (loop); return G_SOURCE_REMOVE; } static gpointer loop_thread_init (gpointer data) { KmsHttpLoop *self = KMS_HTTP_LOOP (data); GMainLoop *loop; GMainContext *context; KMS_HTTP_LOOP_LOCK (self); self->priv->context = g_main_context_new (); context = self->priv->context; self->priv->loop = g_main_loop_new (context, FALSE); loop = self->priv->loop; KMS_HTTP_LOOP_UNLOCK (self); /* unlock main process because context is already initialized */ g_mutex_lock (&self->priv->mutex); self->priv->initialized = TRUE; g_cond_signal (&self->priv->cond); g_mutex_unlock (&self->priv->mutex); if (!g_main_context_acquire (context) ) { GST_ERROR ("Can not acquire context"); goto end; } GST_DEBUG ("Running main loop"); g_main_loop_run (loop); g_main_context_release (context); end: GST_DEBUG ("Thread finished"); g_main_context_unref (context); g_main_loop_unref (loop); return NULL; } static void kms_http_loop_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { KmsHttpLoop *self = KMS_HTTP_LOOP (object); KMS_HTTP_LOOP_LOCK (self); switch (property_id) { case PROP_CONTEXT: g_value_set_boxed (value, self->priv->context); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } KMS_HTTP_LOOP_UNLOCK (self); } static void kms_http_loop_dispose (GObject *obj) { KmsHttpLoop *self = KMS_HTTP_LOOP (obj); GST_DEBUG_OBJECT (obj, "Dispose"); KMS_HTTP_LOOP_LOCK (self); if (self->priv->thread != NULL) { if (g_thread_self () != self->priv->thread) { GThread *aux = self->priv->thread; kms_http_loop_idle_add (self, (GSourceFunc) quit_main_loop, self->priv->loop); self->priv->thread = NULL; KMS_HTTP_LOOP_UNLOCK (self); g_thread_join (aux); KMS_HTTP_LOOP_LOCK (self); } else { /* self thread does not need to wait for itself */ quit_main_loop (self->priv->loop); g_thread_unref (self->priv->thread); self->priv->thread = NULL; } } KMS_HTTP_LOOP_UNLOCK (self); G_OBJECT_CLASS (kms_http_loop_parent_class)->dispose (obj); } static void kms_http_loop_finalize (GObject *obj) { KmsHttpLoop *self = KMS_HTTP_LOOP (obj); GST_DEBUG_OBJECT (obj, "Finalize"); g_rec_mutex_clear (&self->priv->rmutex); g_mutex_clear (&self->priv->mutex); g_cond_clear (&self->priv->cond); G_OBJECT_CLASS (kms_http_loop_parent_class)->finalize (obj); } static void kms_http_loop_class_init (KmsHttpLoopClass *klass) { GObjectClass *objclass = G_OBJECT_CLASS (klass); objclass->dispose = kms_http_loop_dispose; objclass->finalize = kms_http_loop_finalize; objclass->get_property = kms_http_loop_get_property; /* Install properties */ obj_properties[PROP_CONTEXT] = g_param_spec_boxed ("context", "Main loop context", "Main loop context", G_TYPE_MAIN_CONTEXT, (GParamFlags) (G_PARAM_READABLE) ); g_object_class_install_properties (objclass, N_PROPERTIES, obj_properties); /* Registers a private structure for the instantiatable type */ g_type_class_add_private (klass, sizeof (KmsHttpLoopPrivate) ); } static void kms_http_loop_init (KmsHttpLoop *self) { self->priv = KMS_HTTP_LOOP_GET_PRIVATE (self); g_rec_mutex_init (&self->priv->rmutex); g_cond_init (&self->priv->cond); g_mutex_init (&self->priv->mutex); self->priv->thread = g_thread_new ("KmsHttpLoop", loop_thread_init, self); g_mutex_lock (&self->priv->mutex); while (!self->priv->initialized) { g_cond_wait (&self->priv->cond, &self->priv->mutex); } g_mutex_unlock (&self->priv->mutex); } KmsHttpLoop * kms_http_loop_new (void) { return KMS_HTTP_LOOP (g_object_new (KMS_TYPE_HTTP_LOOP, NULL) ); } static guint kms_http_loop_attach (KmsHttpLoop *self, GSource *source, gint priority, GSourceFunc function, gpointer data, GDestroyNotify notify) { guint id; KMS_HTTP_LOOP_LOCK (self); if (self->priv->thread == NULL) { KMS_HTTP_LOOP_UNLOCK (self); return 0; } g_source_set_priority (source, priority); g_source_set_callback (source, function, data, notify); id = g_source_attach (source, self->priv->context); KMS_HTTP_LOOP_UNLOCK (self); return id; } guint kms_http_loop_idle_add_full (KmsHttpLoop *self, gint priority, GSourceFunc function, gpointer data, GDestroyNotify notify) { GSource *source; guint id; if (!KMS_IS_HTTP_LOOP (self) ) { return 0; } source = g_idle_source_new (); id = kms_http_loop_attach (self, source, priority, function, data, notify); g_source_unref (source); return id; } guint kms_http_loop_idle_add (KmsHttpLoop *self, GSourceFunc function, gpointer data) { return kms_http_loop_idle_add_full (self, G_PRIORITY_DEFAULT_IDLE, function, data, NULL); } guint kms_http_loop_timeout_add_full (KmsHttpLoop *self, gint priority, guint interval, GSourceFunc function, gpointer data, GDestroyNotify notify) { GSource *source; guint id; if (!KMS_IS_HTTP_LOOP (self) ) { return 0; } source = g_timeout_source_new (interval); id = kms_http_loop_attach (self, source, priority, function, data, notify); g_source_unref (source); return id; } guint kms_http_loop_timeout_add (KmsHttpLoop *self, guint interval, GSourceFunc function, gpointer data) { return kms_http_loop_timeout_add_full (self, G_PRIORITY_DEFAULT, interval, function, data, NULL); } gboolean kms_http_loop_remove (KmsHttpLoop *self, guint source_id) { GSource *source; source = g_main_context_find_source_by_id (self->priv->context, source_id); if (source == NULL) { return FALSE; } g_source_destroy (source); return TRUE; } gboolean kms_http_loop_is_current_thread (KmsHttpLoop *self) { return (g_thread_self() == self->priv->thread); }<commit_msg>KmsHttpLoop: Fix bad read while disposing kmsloop<commit_after>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <gst/gst.h> #include "KmsHttpLoop.h" #define NAME "httploop" GST_DEBUG_CATEGORY_STATIC (kms_http_loop_debug_category); #define GST_CAT_DEFAULT kms_http_loop_debug_category G_DEFINE_TYPE_WITH_CODE (KmsHttpLoop, kms_http_loop, G_TYPE_OBJECT, GST_DEBUG_CATEGORY_INIT (kms_http_loop_debug_category, NAME, 0, "debug category for kurento loop") ) #define KMS_HTTP_LOOP_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), KMS_TYPE_HTTP_LOOP, KmsHttpLoopPrivate)) struct _KmsHttpLoopPrivate { GThread *thread; GRecMutex rmutex; GMainLoop *loop; GMainContext *context; GCond cond; GMutex mutex; gboolean initialized; }; #define KMS_HTTP_LOOP_LOCK(elem) \ (g_rec_mutex_lock (&KMS_HTTP_LOOP ((elem))->priv->rmutex)) #define KMS_HTTP_LOOP_UNLOCK(elem) \ (g_rec_mutex_unlock (&KMS_HTTP_LOOP ((elem))->priv->rmutex)) /* Object properties */ enum { PROP_0, PROP_CONTEXT, N_PROPERTIES }; static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, }; static gboolean quit_main_loop (KmsHttpLoop *self) { GST_DEBUG ("Exiting main loop"); g_main_loop_quit (self->priv->loop); g_main_context_release (self->priv->context); return G_SOURCE_REMOVE; } static gpointer loop_thread_init (gpointer data) { KmsHttpLoop *self = KMS_HTTP_LOOP (data); GMainLoop *loop; GMainContext *context; KMS_HTTP_LOOP_LOCK (self); self->priv->context = g_main_context_new (); context = self->priv->context; self->priv->loop = g_main_loop_new (context, FALSE); loop = self->priv->loop; KMS_HTTP_LOOP_UNLOCK (self); /* unlock main process because context is already initialized */ g_mutex_lock (&self->priv->mutex); self->priv->initialized = TRUE; g_cond_signal (&self->priv->cond); g_mutex_unlock (&self->priv->mutex); if (!g_main_context_acquire (context) ) { GST_ERROR ("Can not acquire context"); goto end; } GST_DEBUG ("Running main loop"); g_main_loop_run (loop); end: GST_DEBUG ("Thread finished"); return NULL; } static void kms_http_loop_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { KmsHttpLoop *self = KMS_HTTP_LOOP (object); KMS_HTTP_LOOP_LOCK (self); switch (property_id) { case PROP_CONTEXT: g_value_set_boxed (value, self->priv->context); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } KMS_HTTP_LOOP_UNLOCK (self); } static void kms_http_loop_dispose (GObject *obj) { KmsHttpLoop *self = KMS_HTTP_LOOP (obj); GST_DEBUG_OBJECT (obj, "Dispose"); KMS_HTTP_LOOP_LOCK (self); if (self->priv->thread != NULL) { if (g_thread_self () != self->priv->thread) { GThread *aux = self->priv->thread; kms_http_loop_idle_add (self, (GSourceFunc) quit_main_loop, self); self->priv->thread = NULL; KMS_HTTP_LOOP_UNLOCK (self); g_thread_join (aux); KMS_HTTP_LOOP_LOCK (self); } else { /* self thread does not need to wait for itself */ quit_main_loop (self); g_thread_unref (self->priv->thread); self->priv->thread = NULL; } } KMS_HTTP_LOOP_UNLOCK (self); G_OBJECT_CLASS (kms_http_loop_parent_class)->dispose (obj); } static void kms_http_loop_finalize (GObject *obj) { KmsHttpLoop *self = KMS_HTTP_LOOP (obj); GST_DEBUG_OBJECT (obj, "Finalize"); if (self->priv->context != NULL) { g_main_context_unref (self->priv->context); } if (self->priv->loop != NULL) { g_main_loop_unref (self->priv->loop); } g_rec_mutex_clear (&self->priv->rmutex); g_mutex_clear (&self->priv->mutex); g_cond_clear (&self->priv->cond); G_OBJECT_CLASS (kms_http_loop_parent_class)->finalize (obj); } static void kms_http_loop_class_init (KmsHttpLoopClass *klass) { GObjectClass *objclass = G_OBJECT_CLASS (klass); objclass->dispose = kms_http_loop_dispose; objclass->finalize = kms_http_loop_finalize; objclass->get_property = kms_http_loop_get_property; /* Install properties */ obj_properties[PROP_CONTEXT] = g_param_spec_boxed ("context", "Main loop context", "Main loop context", G_TYPE_MAIN_CONTEXT, (GParamFlags) (G_PARAM_READABLE) ); g_object_class_install_properties (objclass, N_PROPERTIES, obj_properties); /* Registers a private structure for the instantiatable type */ g_type_class_add_private (klass, sizeof (KmsHttpLoopPrivate) ); } static void kms_http_loop_init (KmsHttpLoop *self) { self->priv = KMS_HTTP_LOOP_GET_PRIVATE (self); self->priv->context = NULL; self->priv->loop = NULL; g_rec_mutex_init (&self->priv->rmutex); g_cond_init (&self->priv->cond); g_mutex_init (&self->priv->mutex); self->priv->thread = g_thread_new ("KmsHttpLoop", loop_thread_init, self); g_mutex_lock (&self->priv->mutex); while (!self->priv->initialized) { g_cond_wait (&self->priv->cond, &self->priv->mutex); } g_mutex_unlock (&self->priv->mutex); } KmsHttpLoop * kms_http_loop_new (void) { return KMS_HTTP_LOOP (g_object_new (KMS_TYPE_HTTP_LOOP, NULL) ); } static guint kms_http_loop_attach (KmsHttpLoop *self, GSource *source, gint priority, GSourceFunc function, gpointer data, GDestroyNotify notify) { guint id; KMS_HTTP_LOOP_LOCK (self); if (self->priv->thread == NULL) { KMS_HTTP_LOOP_UNLOCK (self); return 0; } g_source_set_priority (source, priority); g_source_set_callback (source, function, data, notify); id = g_source_attach (source, self->priv->context); KMS_HTTP_LOOP_UNLOCK (self); return id; } guint kms_http_loop_idle_add_full (KmsHttpLoop *self, gint priority, GSourceFunc function, gpointer data, GDestroyNotify notify) { GSource *source; guint id; if (!KMS_IS_HTTP_LOOP (self) ) { return 0; } source = g_idle_source_new (); id = kms_http_loop_attach (self, source, priority, function, data, notify); g_source_unref (source); return id; } guint kms_http_loop_idle_add (KmsHttpLoop *self, GSourceFunc function, gpointer data) { return kms_http_loop_idle_add_full (self, G_PRIORITY_DEFAULT_IDLE, function, data, NULL); } guint kms_http_loop_timeout_add_full (KmsHttpLoop *self, gint priority, guint interval, GSourceFunc function, gpointer data, GDestroyNotify notify) { GSource *source; guint id; if (!KMS_IS_HTTP_LOOP (self) ) { return 0; } source = g_timeout_source_new (interval); id = kms_http_loop_attach (self, source, priority, function, data, notify); g_source_unref (source); return id; } guint kms_http_loop_timeout_add (KmsHttpLoop *self, guint interval, GSourceFunc function, gpointer data) { return kms_http_loop_timeout_add_full (self, G_PRIORITY_DEFAULT, interval, function, data, NULL); } gboolean kms_http_loop_remove (KmsHttpLoop *self, guint source_id) { GSource *source; source = g_main_context_find_source_by_id (self->priv->context, source_id); if (source == NULL) { return FALSE; } g_source_destroy (source); return TRUE; } gboolean kms_http_loop_is_current_thread (KmsHttpLoop *self) { return (g_thread_self() == self->priv->thread); } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <thread> #include <type_traits> #include "boost_cfg.hpp" #include <boost/mpl/vector.hpp> #include <boost/mpl/for_each.hpp> #include "Options.hpp" #include "PerfsTimer.hpp" #include "iterators.hpp" #include "likely.hpp" #include "logging.hpp" #include "timing.hpp" #include "GlobalContext.hpp" #include "ltac/Statement.hpp" #include "mtac/pass_traits.hpp" #include "mtac/Utils.hpp" #include "mtac/Pass.hpp" #include "mtac/Optimizer.hpp" #include "mtac/Program.hpp" #include "mtac/ControlFlowGraph.hpp" #include "mtac/Quadruple.hpp" //The custom optimizations #include "mtac/conditional_propagation.hpp" #include "mtac/remove_aliases.hpp" #include "mtac/clean_variables.hpp" #include "mtac/remove_unused_functions.hpp" #include "mtac/remove_empty_functions.hpp" #include "mtac/DeadCodeElimination.hpp" #include "mtac/merge_basic_blocks.hpp" #include "mtac/remove_dead_basic_blocks.hpp" #include "mtac/BranchOptimizations.hpp" #include "mtac/inlining.hpp" #include "mtac/loop_analysis.hpp" #include "mtac/induction_variable_optimizations.hpp" #include "mtac/loop_unrolling.hpp" #include "mtac/complete_loop_peeling.hpp" #include "mtac/remove_empty_loops.hpp" #include "mtac/loop_invariant_code_motion.hpp" #include "mtac/parameter_propagation.hpp" #include "mtac/pure_analysis.hpp" //The optimization visitors #include "mtac/ArithmeticIdentities.hpp" #include "mtac/ReduceInStrength.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/MathPropagation.hpp" #include "mtac/PointerPropagation.hpp" //The data-flow problems #include "mtac/GlobalOptimizations.hpp" #include "mtac/ConstantPropagationProblem.hpp" #include "mtac/OffsetConstantPropagationProblem.hpp" #include "mtac/CommonSubexpressionElimination.hpp" #include "ltac/Register.hpp" #include "ltac/FloatRegister.hpp" #include "ltac/PseudoRegister.hpp" #include "ltac/PseudoFloatRegister.hpp" #include "ltac/Address.hpp" using namespace eddic; namespace eddic { namespace mtac { typedef boost::mpl::vector< mtac::ConstantFolding* > basic_passes; struct all_basic_optimizations {}; template<> struct pass_traits<all_basic_optimizations> { STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB); STATIC_STRING(name, "all_basic_optimizations"); STATIC_CONSTANT(unsigned int, property_flags, 0); STATIC_CONSTANT(unsigned int, todo_after_flags, 0); typedef basic_passes sub_passes; }; typedef boost::mpl::vector< mtac::ArithmeticIdentities*, mtac::ReduceInStrength*, mtac::ConstantFolding*, mtac::conditional_propagation*, mtac::ConstantPropagationProblem*, mtac::OffsetConstantPropagationProblem*, mtac::CommonSubexpressionElimination*, mtac::PointerPropagation*, mtac::MathPropagation*, mtac::optimize_branches*, mtac::remove_dead_basic_blocks*, mtac::merge_basic_blocks*, mtac::dead_code_elimination*, mtac::remove_aliases*, mtac::loop_analysis*, mtac::loop_invariant_code_motion*, mtac::loop_induction_variables_optimization*, mtac::remove_empty_loops*, mtac::complete_loop_peeling*, mtac::loop_unrolling*, mtac::clean_variables* > passes; struct all_optimizations {}; template<> struct pass_traits<all_optimizations> { STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB); STATIC_STRING(name, "all_optimizations"); STATIC_CONSTANT(unsigned int, property_flags, 0); STATIC_CONSTANT(unsigned int, todo_after_flags, 0); typedef passes sub_passes; }; } } namespace { template<typename T, typename Sign> struct has_gate { typedef char yes[1]; typedef char no [2]; template <typename U, U> struct type_check; template <typename _1> static yes &chk(type_check<Sign, &_1::gate> *); template <typename > static no &chk(...); static bool const value = sizeof(chk<T>(0)) == sizeof(yes); }; //TODO Find a more elegant way than using pointers typedef boost::mpl::vector< mtac::all_basic_optimizations* > ipa_basic_passes; typedef boost::mpl::vector< mtac::remove_unused_functions*, mtac::pure_analysis*, mtac::all_optimizations*, mtac::remove_empty_functions*, mtac::inline_functions*, mtac::parameter_propagation* > ipa_passes; template<typename Pass> struct need_pool { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_POOL; }; template<typename Pass> struct need_platform { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PLATFORM; }; template<typename Pass> struct need_configuration { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_CONFIGURATION; }; template<typename Pass> struct need_program { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PROGRAM; }; template <bool B, typename T = void> struct disable_if { typedef T type; }; template <typename T> struct disable_if<true,T> { //SFINAE }; struct pass_runner { bool optimized = false; mtac::Program& program; mtac::Function* function; std::shared_ptr<StringPool> pool; std::shared_ptr<Configuration> configuration; Platform platform; timing_system& system; pass_runner(mtac::Program& program, std::shared_ptr<StringPool> pool, std::shared_ptr<Configuration> configuration, Platform platform, timing_system& system) : program(program), pool(pool), configuration(configuration), platform(platform), system(system) {}; template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP, void>::type remove_nop(){ for(auto& block : *function){ auto it = iterate(block->statements); while(it.has_next()){ if(it->op == mtac::Operator::NOP){ it.erase(); continue; } ++it; } } } template<typename Pass> inline typename std::enable_if<!(mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP), void>::type remove_nop(){ //NOP } template<typename Pass> inline void apply_todo(){ remove_nop<Pass>(); } template<typename Pass> inline typename std::enable_if<need_pool<Pass>::value, void>::type set_pool(Pass& pass){ pass.set_pool(pool); } template<typename Pass> inline typename disable_if<need_pool<Pass>::value, void>::type set_pool(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_platform<Pass>::value, void>::type set_platform(Pass& pass){ pass.set_platform(platform); } template<typename Pass> inline typename disable_if<need_platform<Pass>::value, void>::type set_platform(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_configuration<Pass>::value, void>::type set_configuration(Pass& pass){ pass.set_configuration(configuration); } template<typename Pass> inline typename disable_if<need_configuration<Pass>::value, void>::type set_configuration(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_program<Pass>::value, Pass>::type construct(){ return Pass(program); } template<typename Pass> inline typename disable_if<need_program<Pass>::value, Pass>::type construct(){ return Pass(); } template<typename Pass> Pass make_pass(){ auto pass = construct<Pass>(); set_pool(pass); set_platform(pass); set_configuration(pass); return pass; } template<typename Pass> inline typename std::enable_if<has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool>::type has_to_be_run(Pass& pass){ return pass.gate(configuration); } template<typename Pass> inline typename disable_if<has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool>::type has_to_be_run(Pass&){ return true; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, bool>::type apply(Pass& pass){ return pass(program); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB, bool>::type apply(Pass&){ for(auto& function : program.functions){ this->function = &function; if(log::enabled<Debug>()){ LOG<Debug>("Optimizer") << "Start optimizations on " << function.get_name() << log::endl; std::cout << function << std::endl; } boost::mpl::for_each<typename mtac::pass_traits<Pass>::sub_passes>(boost::ref(*this)); } return false; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::CUSTOM, bool>::type apply(Pass& pass){ return pass(*function); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::LOCAL, bool>::type apply(Pass& visitor){ for(auto& block : *function){ for(auto& quadruple : block->statements){ visitor(quadruple); } } return visitor.optimized; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::DATA_FLOW, bool>::type apply(Pass& problem){ auto results = mtac::data_flow(*function, problem); //Once the data-flow problem is fixed, statements can be optimized return problem.optimize(*function, results); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB, bool>::type apply(Pass& visitor){ bool optimized = false; for(auto& block : *function){ visitor.clear(); for(auto& quadruple : block->statements){ visitor(quadruple); } optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB_TWO_PASS, bool>::type apply(Pass& visitor){ bool optimized = false; for(auto& block : *function){ visitor.clear(); visitor.pass = mtac::Pass::DATA_MINING; for(auto& quadruple : block->statements){ visitor(quadruple); } visitor.pass = mtac::Pass::OPTIMIZE; for(auto& quadruple : block->statements){ visitor(quadruple); } optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline typename std::enable_if<boost::type_traits::ice_or<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB>::value, void>::type debug_local(bool local){ LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned " << local << log::endl; } template<typename Pass> inline typename std::enable_if<boost::type_traits::ice_and<mtac::pass_traits<Pass>::type != mtac::pass_type::IPA, mtac::pass_traits<Pass>::type != mtac::pass_type::IPA_SUB>::value, void>::type debug_local(bool local){ if(log::enabled<Debug>()){ if(local){ LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned true" << log::endl; //Print the function std::cout << *function << std::endl; } else { LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned false" << log::endl; } } } template<typename Pass> inline void operator()(Pass*){ auto pass = make_pass<Pass>(); if(has_to_be_run(pass)){ bool local = false; { PerfsTimer perfs_timer(mtac::pass_traits<Pass>::name()); timing_timer timer(system, mtac::pass_traits<Pass>::name()); local = apply<Pass>(pass); } if(local){ program.context->stats().inc_counter(std::string(mtac::pass_traits<Pass>::name()) + "_true"); apply_todo<Pass>(); } debug_local<Pass>(local); optimized |= local; } } }; } //end of anonymous namespace void mtac::Optimizer::optimize(mtac::Program& program, std::shared_ptr<StringPool> string_pool, Platform platform, std::shared_ptr<Configuration> configuration) const { timing_system timing_system(configuration); PerfsTimer timer("Whole optimizations"); //Build the CFG of each functions (also needed for register allocation) for(auto& function : program.functions){ mtac::build_control_flow_graph(function); } if(configuration->option_defined("fglobal-optimization")){ //Apply Interprocedural Optimizations pass_runner runner(program, string_pool, configuration, platform, timing_system); do{ runner.optimized = false; boost::mpl::for_each<ipa_passes>(boost::ref(runner)); } while(runner.optimized); } else { //Even if global optimizations are disabled, perform basic optimization (only constant folding) pass_runner runner(program, string_pool, configuration, platform, timing_system); boost::mpl::for_each<ipa_basic_passes>(boost::ref(runner)); } } <commit_msg>Build the control flow before the optimizations<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <thread> #include <type_traits> #include "boost_cfg.hpp" #include <boost/mpl/vector.hpp> #include <boost/mpl/for_each.hpp> #include "Options.hpp" #include "PerfsTimer.hpp" #include "iterators.hpp" #include "likely.hpp" #include "logging.hpp" #include "timing.hpp" #include "GlobalContext.hpp" #include "ltac/Statement.hpp" #include "mtac/pass_traits.hpp" #include "mtac/Utils.hpp" #include "mtac/Pass.hpp" #include "mtac/Optimizer.hpp" #include "mtac/Program.hpp" #include "mtac/ControlFlowGraph.hpp" #include "mtac/Quadruple.hpp" //The custom optimizations #include "mtac/conditional_propagation.hpp" #include "mtac/remove_aliases.hpp" #include "mtac/clean_variables.hpp" #include "mtac/remove_unused_functions.hpp" #include "mtac/remove_empty_functions.hpp" #include "mtac/DeadCodeElimination.hpp" #include "mtac/merge_basic_blocks.hpp" #include "mtac/remove_dead_basic_blocks.hpp" #include "mtac/BranchOptimizations.hpp" #include "mtac/inlining.hpp" #include "mtac/loop_analysis.hpp" #include "mtac/induction_variable_optimizations.hpp" #include "mtac/loop_unrolling.hpp" #include "mtac/complete_loop_peeling.hpp" #include "mtac/remove_empty_loops.hpp" #include "mtac/loop_invariant_code_motion.hpp" #include "mtac/parameter_propagation.hpp" #include "mtac/pure_analysis.hpp" //The optimization visitors #include "mtac/ArithmeticIdentities.hpp" #include "mtac/ReduceInStrength.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/MathPropagation.hpp" #include "mtac/PointerPropagation.hpp" //The data-flow problems #include "mtac/GlobalOptimizations.hpp" #include "mtac/ConstantPropagationProblem.hpp" #include "mtac/OffsetConstantPropagationProblem.hpp" #include "mtac/CommonSubexpressionElimination.hpp" #include "ltac/Register.hpp" #include "ltac/FloatRegister.hpp" #include "ltac/PseudoRegister.hpp" #include "ltac/PseudoFloatRegister.hpp" #include "ltac/Address.hpp" using namespace eddic; namespace eddic { namespace mtac { typedef boost::mpl::vector< mtac::ConstantFolding* > basic_passes; struct all_basic_optimizations {}; template<> struct pass_traits<all_basic_optimizations> { STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB); STATIC_STRING(name, "all_basic_optimizations"); STATIC_CONSTANT(unsigned int, property_flags, 0); STATIC_CONSTANT(unsigned int, todo_after_flags, 0); typedef basic_passes sub_passes; }; typedef boost::mpl::vector< mtac::ArithmeticIdentities*, mtac::ReduceInStrength*, mtac::ConstantFolding*, mtac::conditional_propagation*, mtac::ConstantPropagationProblem*, mtac::OffsetConstantPropagationProblem*, mtac::CommonSubexpressionElimination*, mtac::PointerPropagation*, mtac::MathPropagation*, mtac::optimize_branches*, mtac::remove_dead_basic_blocks*, mtac::merge_basic_blocks*, mtac::dead_code_elimination*, mtac::remove_aliases*, mtac::loop_analysis*, mtac::loop_invariant_code_motion*, mtac::loop_induction_variables_optimization*, mtac::remove_empty_loops*, mtac::complete_loop_peeling*, mtac::loop_unrolling*, mtac::clean_variables* > passes; struct all_optimizations {}; template<> struct pass_traits<all_optimizations> { STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB); STATIC_STRING(name, "all_optimizations"); STATIC_CONSTANT(unsigned int, property_flags, 0); STATIC_CONSTANT(unsigned int, todo_after_flags, 0); typedef passes sub_passes; }; } } namespace { template<typename T, typename Sign> struct has_gate { typedef char yes[1]; typedef char no [2]; template <typename U, U> struct type_check; template <typename _1> static yes &chk(type_check<Sign, &_1::gate> *); template <typename > static no &chk(...); static bool const value = sizeof(chk<T>(0)) == sizeof(yes); }; //TODO Find a more elegant way than using pointers typedef boost::mpl::vector< mtac::all_basic_optimizations* > ipa_basic_passes; typedef boost::mpl::vector< mtac::remove_unused_functions*, mtac::pure_analysis*, mtac::all_optimizations*, mtac::remove_empty_functions*, mtac::inline_functions*, mtac::parameter_propagation* > ipa_passes; template<typename Pass> struct need_pool { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_POOL; }; template<typename Pass> struct need_platform { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PLATFORM; }; template<typename Pass> struct need_configuration { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_CONFIGURATION; }; template<typename Pass> struct need_program { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PROGRAM; }; template <bool B, typename T = void> struct disable_if { typedef T type; }; template <typename T> struct disable_if<true,T> { //SFINAE }; struct pass_runner { bool optimized = false; mtac::Program& program; mtac::Function* function; std::shared_ptr<StringPool> pool; std::shared_ptr<Configuration> configuration; Platform platform; timing_system& system; pass_runner(mtac::Program& program, std::shared_ptr<StringPool> pool, std::shared_ptr<Configuration> configuration, Platform platform, timing_system& system) : program(program), pool(pool), configuration(configuration), platform(platform), system(system) {}; template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP, void>::type remove_nop(){ for(auto& block : *function){ auto it = iterate(block->statements); while(it.has_next()){ if(it->op == mtac::Operator::NOP){ it.erase(); continue; } ++it; } } } template<typename Pass> inline typename std::enable_if<!(mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP), void>::type remove_nop(){ //NOP } template<typename Pass> inline void apply_todo(){ remove_nop<Pass>(); } template<typename Pass> inline typename std::enable_if<need_pool<Pass>::value, void>::type set_pool(Pass& pass){ pass.set_pool(pool); } template<typename Pass> inline typename disable_if<need_pool<Pass>::value, void>::type set_pool(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_platform<Pass>::value, void>::type set_platform(Pass& pass){ pass.set_platform(platform); } template<typename Pass> inline typename disable_if<need_platform<Pass>::value, void>::type set_platform(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_configuration<Pass>::value, void>::type set_configuration(Pass& pass){ pass.set_configuration(configuration); } template<typename Pass> inline typename disable_if<need_configuration<Pass>::value, void>::type set_configuration(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_program<Pass>::value, Pass>::type construct(){ return Pass(program); } template<typename Pass> inline typename disable_if<need_program<Pass>::value, Pass>::type construct(){ return Pass(); } template<typename Pass> Pass make_pass(){ auto pass = construct<Pass>(); set_pool(pass); set_platform(pass); set_configuration(pass); return pass; } template<typename Pass> inline typename std::enable_if<has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool>::type has_to_be_run(Pass& pass){ return pass.gate(configuration); } template<typename Pass> inline typename disable_if<has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool>::type has_to_be_run(Pass&){ return true; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, bool>::type apply(Pass& pass){ return pass(program); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB, bool>::type apply(Pass&){ for(auto& function : program.functions){ this->function = &function; if(log::enabled<Debug>()){ LOG<Debug>("Optimizer") << "Start optimizations on " << function.get_name() << log::endl; std::cout << function << std::endl; } boost::mpl::for_each<typename mtac::pass_traits<Pass>::sub_passes>(boost::ref(*this)); } return false; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::CUSTOM, bool>::type apply(Pass& pass){ return pass(*function); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::LOCAL, bool>::type apply(Pass& visitor){ for(auto& block : *function){ for(auto& quadruple : block->statements){ visitor(quadruple); } } return visitor.optimized; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::DATA_FLOW, bool>::type apply(Pass& problem){ auto results = mtac::data_flow(*function, problem); //Once the data-flow problem is fixed, statements can be optimized return problem.optimize(*function, results); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB, bool>::type apply(Pass& visitor){ bool optimized = false; for(auto& block : *function){ visitor.clear(); for(auto& quadruple : block->statements){ visitor(quadruple); } optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB_TWO_PASS, bool>::type apply(Pass& visitor){ bool optimized = false; for(auto& block : *function){ visitor.clear(); visitor.pass = mtac::Pass::DATA_MINING; for(auto& quadruple : block->statements){ visitor(quadruple); } visitor.pass = mtac::Pass::OPTIMIZE; for(auto& quadruple : block->statements){ visitor(quadruple); } optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline typename std::enable_if<boost::type_traits::ice_or<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB>::value, void>::type debug_local(bool local){ LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned " << local << log::endl; } template<typename Pass> inline typename std::enable_if<boost::type_traits::ice_and<mtac::pass_traits<Pass>::type != mtac::pass_type::IPA, mtac::pass_traits<Pass>::type != mtac::pass_type::IPA_SUB>::value, void>::type debug_local(bool local){ if(log::enabled<Debug>()){ if(local){ LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned true" << log::endl; //Print the function std::cout << *function << std::endl; } else { LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned false" << log::endl; } } } template<typename Pass> inline void operator()(Pass*){ auto pass = make_pass<Pass>(); if(has_to_be_run(pass)){ bool local = false; { PerfsTimer perfs_timer(mtac::pass_traits<Pass>::name()); timing_timer timer(system, mtac::pass_traits<Pass>::name()); local = apply<Pass>(pass); } if(local){ program.context->stats().inc_counter(std::string(mtac::pass_traits<Pass>::name()) + "_true"); apply_todo<Pass>(); } debug_local<Pass>(local); optimized |= local; } } }; } //end of anonymous namespace void mtac::Optimizer::optimize(mtac::Program& program, std::shared_ptr<StringPool> string_pool, Platform platform, std::shared_ptr<Configuration> configuration) const { timing_system timing_system(configuration); PerfsTimer timer("Whole optimizations"); //Build the CFG of each functions (also needed for register allocation) for(auto& function : program.functions){ mtac::build_control_flow_graph(function); } //Build the call graph (will be used for code generation as well) mtac::build_call_graph(program); if(configuration->option_defined("fglobal-optimization")){ //Apply Interprocedural Optimizations pass_runner runner(program, string_pool, configuration, platform, timing_system); do{ runner.optimized = false; boost::mpl::for_each<ipa_passes>(boost::ref(runner)); } while(runner.optimized); } else { //Even if global optimizations are disabled, perform basic optimization (only constant folding) pass_runner runner(program, string_pool, configuration, platform, timing_system); boost::mpl::for_each<ipa_basic_passes>(boost::ref(runner)); } } <|endoftext|>
<commit_before><commit_msg>#i10000#: remove extra semicolon after macro<commit_after><|endoftext|>
<commit_before>#include <string> #include <unistd.h> #include <signal.h> #include <include/wrapper/cef_helpers.h> #include <sys/stat.h> #include "helper.h" namespace { // Set the calling thread's signal mask to new_sigmask and return // the previous signal mask. sigset_t SetSignalMask(const sigset_t& new_sigmask) { sigset_t old_sigmask; pthread_sigmask(SIG_SETMASK, &new_sigmask, &old_sigmask); return old_sigmask; } bool LaunchProcess(const std::vector<std::string>& argv) { const size_t command_size = argv.size(); char** command = new char*[command_size+1]; // extra space for terminating NULL sigset_t full_sigset; sigfillset(&full_sigset); const sigset_t orig_sigmask = SetSignalMask(full_sigset); pid_t pid; pid = fork(); // Always restore the original signal mask in the parent. if (pid != 0) { SetSignalMask(orig_sigmask); } if (pid < 0) { LOG(ERROR) << "LaunchProcess: failed fork"; return false; } else if (pid == 0) { // Child process // DANGER: no calls to malloc or locks are allowed from now on: // http://crbug.com/36678 // DANGER: fork() rule: in the child, if you don't end up doing exec*(), // you call _exit() instead of exit(). This is because _exit() does not // call any previously-registered (in the parent) exit handlers, which // might do things like block waiting for threads that don't even exist // in the child. for (size_t i = 0; i < command_size; ++i) { command[i] = strdup(argv[i].c_str()); } command[command_size] = NULL; // ToDo: Put environment like Google chrome // options.allow_new_privs = true; // // xdg-open can fall back on mailcap which eventually might plumb through // // to a command that needs a terminal. Set the environment variable telling // // it that we definitely don't have a terminal available and that it should // // bring up a new terminal if necessary. See "man mailcap". // options.environ["MM_NOTTTY"] = "1"; // // // We do not let GNOME's bug-buddy intercept our crashes. // char* disable_gnome_bug_buddy = getenv("GNOME_DISABLE_CRASH_DIALOG"); // if (disable_gnome_bug_buddy && // disable_gnome_bug_buddy == std::string("SET_BY_GOOGLE_CHROME")) // options.environ["GNOME_DISABLE_CRASH_DIALOG"] = std::string(); execvp(command[0], command); LOG(ERROR) << "LaunchProcess: failed to execvp:" << command[0]; _exit(127); } return true; } void XDGUtil(const std::string& util, const std::string& arg) { std::vector<std::string> argv; argv.push_back(util.c_str()); argv.push_back(arg.c_str()); LaunchProcess(argv); } void XDGOpen(const std::string& path) { XDGUtil("xdg-open", path); } void XDGEmail(const std::string& email) { XDGUtil("xdg-email", email); } } // namespace namespace platform_util { void OpenExternal(std::string url) { if (url.find("mailto:") == 0) XDGEmail(url); else XDGOpen(url); } bool IsPathExists(std::string path) { struct stat stat_data; return stat(path.c_str(), &stat_data) != -1; } bool MakeDirectory(std::string path) { if (IsPathExists(path)) return true; size_t pre=0, pos; std::string dir; if (path[path.size()-1] != '/'){ // force trailing / so we can handle everything in loop path += '/'; } while ((pos = path.find_first_of('/', pre)) !=std::string::npos){ dir = path.substr(0, pos++); pre = pos; if (dir.size()==0) continue; if (mkdir(dir.c_str(), 0700) && errno != EEXIST) { return false; } } return true; } } // namespace platform_util <commit_msg>Fixed possible leak in LaunchProcess<commit_after>#include <string> #include <unistd.h> #include <signal.h> #include <include/wrapper/cef_helpers.h> #include <sys/stat.h> #include "helper.h" namespace { // Set the calling thread's signal mask to new_sigmask and return // the previous signal mask. sigset_t SetSignalMask(const sigset_t& new_sigmask) { sigset_t old_sigmask; pthread_sigmask(SIG_SETMASK, &new_sigmask, &old_sigmask); return old_sigmask; } bool LaunchProcess(const std::vector<std::string>& args) { sigset_t full_sigset; sigfillset(&full_sigset); const sigset_t orig_sigmask = SetSignalMask(full_sigset); pid_t pid; pid = fork(); // Always restore the original signal mask in the parent. if (pid != 0) { SetSignalMask(orig_sigmask); } if (pid < 0) { LOG(ERROR) << "LaunchProcess: failed fork"; return false; } else if (pid == 0) { // Child process // DANGER: fork() rule: in the child, if you don't end up doing exec*(), // you call _exit() instead of exit(). This is because _exit() does not // call any previously-registered (in the parent) exit handlers, which // might do things like block waiting for threads that don't even exist // in the child. // ToDo: Put environment like Google chrome // options.allow_new_privs = true; // // xdg-open can fall back on mailcap which eventually might plumb through // // to a command that needs a terminal. Set the environment variable telling // // it that we definitely don't have a terminal available and that it should // // bring up a new terminal if necessary. See "man mailcap". // options.environ["MM_NOTTTY"] = "1"; // // // We do not let GNOME's bug-buddy intercept our crashes. // char* disable_gnome_bug_buddy = getenv("GNOME_DISABLE_CRASH_DIALOG"); // if (disable_gnome_bug_buddy && // disable_gnome_bug_buddy == std::string("SET_BY_GOOGLE_CHROME")) // options.environ["GNOME_DISABLE_CRASH_DIALOG"] = std::string(); std::vector<char*> argv(args.size() + 1, NULL); for (size_t i = 0; i < args.size(); ++i) { argv[i] = const_cast<char*>(args[i].c_str()); } execvp(argv[0], &argv[0]); LOG(ERROR) << "LaunchProcess: failed to execvp:" << argv[0]; _exit(127); } return true; } void XDGUtil(const std::string& util, const std::string& arg) { std::vector<std::string> argv; argv.push_back(util.c_str()); argv.push_back(arg.c_str()); LaunchProcess(argv); } void XDGOpen(const std::string& path) { XDGUtil("xdg-open", path); } void XDGEmail(const std::string& email) { XDGUtil("xdg-email", email); } } // namespace namespace platform_util { void OpenExternal(std::string url) { if (url.find("mailto:") == 0) XDGEmail(url); else XDGOpen(url); } bool IsPathExists(std::string path) { struct stat stat_data; return stat(path.c_str(), &stat_data) != -1; } bool MakeDirectory(std::string path) { if (IsPathExists(path)) return true; size_t pre=0, pos; std::string dir; if (path[path.size()-1] != '/'){ // force trailing / so we can handle everything in loop path += '/'; } while ((pos = path.find_first_of('/', pre)) !=std::string::npos){ dir = path.substr(0, pos++); pre = pos; if (dir.size()==0) continue; if (mkdir(dir.c_str(), 0700) && errno != EEXIST) { return false; } } return true; } } // namespace platform_util <|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]> * * Hook-setup code provided by Ruslan * * 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 "oxygenargbhelper.h" #include "oxygengtktypenames.h" #include "config.h" #include <gtk/gtk.h> #include <sys/stat.h> #include <cassert> #include <fstream> #include <iostream> #include <string> #include <vector> namespace Oxygen { //__________________________________________________________________ ArgbHelper::ArgbHelper( void ): _hooksInitialized( false ), _logId( 0 ) {} //_____________________________________________________ ArgbHelper::~ArgbHelper( void ) { // disconnect hooks _colormapHook.disconnect(); _styleHook.disconnect(); if( _logId > 0 ) { g_log_remove_handler( "GLib-GObject", _logId ); g_log_set_handler( "GLib-GObject", G_LOG_LEVEL_CRITICAL, g_log_default_handler, 0L ); } } //_____________________________________________________ void ArgbHelper::initializeHooks( void ) { if( _hooksInitialized ) return; // lookup relevant signal const guint signalId( g_signal_lookup("style-set", GTK_TYPE_WINDOW ) ); if( signalId <= 0 ) return; // install hooks _colormapHook.connect( "style-set", (GSignalEmissionHook)colormapHook, 0L ); _styleHook.connect( "parent-set", (GSignalEmissionHook)styleHook, 0L ); /* the installation of "parent-set" hook triggers some glib critical error when destructing ComboBoxEntry. a glib/gtk bug has been filed. In the meanwhile, and since the error is apparently harmless, we simply disable the corresponding log */ _logId = g_log_set_handler( "GLib-GObject", G_LOG_LEVEL_CRITICAL, logHandler, 0L ); _hooksInitialized = true; return; } //_____________________________________________________ gboolean ArgbHelper::colormapHook( GSignalInvocationHint*, guint, const GValue* params, gpointer ) { // get widget from params GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) ); // check type if( !GTK_IS_WIDGET( widget ) ) return FALSE; if( !GTK_IS_WINDOW( widget ) ) return TRUE; // make sure widget has not been realized already if( gtk_widget_get_realized( widget ) ) return TRUE; // cast to window GtkWindow* window( GTK_WINDOW( widget ) ); // check type hint GdkWindowTypeHint hint = gtk_window_get_type_hint( window ); // screen GdkScreen* screen = gdk_screen_get_default(); if( !screen ) return TRUE; if( hint == GDK_WINDOW_TYPE_HINT_DROPDOWN_MENU || hint == GDK_WINDOW_TYPE_HINT_POPUP_MENU || hint == GDK_WINDOW_TYPE_HINT_TOOLTIP || hint == GDK_WINDOW_TYPE_HINT_COMBO ) { #if OXYGEN_DEBUG std::cerr << "Oxygen::ArgbHelper::colormapHook - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << " hint: " << Gtk::TypeNames::windowTypeHint( hint ) << std::endl; #endif GdkColormap* cmap=gdk_screen_get_rgba_colormap( screen ); gtk_widget_push_colormap( cmap ); gtk_widget_set_colormap( widget, cmap ); } return TRUE; } //_____________________________________________________ gboolean ArgbHelper::styleHook( GSignalInvocationHint*, guint, const GValue* params, gpointer ) { // get widget from params GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) ); // check type if( !GTK_IS_WIDGET( widget ) ) return FALSE; // retrieve widget style and check GtkStyle* style( widget->style ); if( !( style && style->depth >= 0 ) ) return TRUE; // retrieve parent window and check GdkWindow* window( gtk_widget_get_parent_window( widget ) ); if( !window ) return TRUE; // adjust depth if( style->depth != gdk_drawable_get_depth( window ) ) { #if OXYGEN_DEBUG std::cerr << "Oxygen::ArgbHelper::styleHook -" << " widget: " << widget << " (" <<G_OBJECT_TYPE_NAME( widget ) << ")" << " style depth: " << style->depth << " window depth: " << gdk_drawable_get_depth( window ) << std::endl; #endif widget->style = gtk_style_attach( style, window ); } return TRUE; } //_________________________________________________________ void ArgbHelper::logHandler( const gchar* domain, GLogLevelFlags flags, const gchar* message, gpointer data ) { /* discard all messages containing "IA__gtk_box_reorder_child:" and fallback to default handler otherwise */ if( std::string( message ).find( "g_object_ref" ) == std::string::npos ) { g_log_default_handler( domain, flags, message, data ); } } } <commit_msg>Removed gtk_widget_push_colormap call. It is useless and dangerous.<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]> * * Hook-setup code provided by Ruslan * * 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 "oxygenargbhelper.h" #include "oxygengtktypenames.h" #include "config.h" #include <gtk/gtk.h> #include <sys/stat.h> #include <cassert> #include <fstream> #include <iostream> #include <string> #include <vector> namespace Oxygen { //__________________________________________________________________ ArgbHelper::ArgbHelper( void ): _hooksInitialized( false ), _logId( 0 ) {} //_____________________________________________________ ArgbHelper::~ArgbHelper( void ) { // disconnect hooks _colormapHook.disconnect(); _styleHook.disconnect(); if( _logId > 0 ) { g_log_remove_handler( "GLib-GObject", _logId ); g_log_set_handler( "GLib-GObject", G_LOG_LEVEL_CRITICAL, g_log_default_handler, 0L ); } } //_____________________________________________________ void ArgbHelper::initializeHooks( void ) { if( _hooksInitialized ) return; // lookup relevant signal const guint signalId( g_signal_lookup("style-set", GTK_TYPE_WINDOW ) ); if( signalId <= 0 ) return; // install hooks _colormapHook.connect( "style-set", (GSignalEmissionHook)colormapHook, 0L ); _styleHook.connect( "parent-set", (GSignalEmissionHook)styleHook, 0L ); /* the installation of "parent-set" hook triggers some glib critical error when destructing ComboBoxEntry. a glib/gtk bug has been filed. In the meanwhile, and since the error is apparently harmless, we simply disable the corresponding log */ _logId = g_log_set_handler( "GLib-GObject", G_LOG_LEVEL_CRITICAL, logHandler, 0L ); _hooksInitialized = true; return; } //_____________________________________________________ gboolean ArgbHelper::colormapHook( GSignalInvocationHint*, guint, const GValue* params, gpointer ) { // get widget from params GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) ); // check type if( !GTK_IS_WIDGET( widget ) ) return FALSE; if( !GTK_IS_WINDOW( widget ) ) return TRUE; // make sure widget has not been realized already if( gtk_widget_get_realized( widget ) ) return TRUE; // cast to window GtkWindow* window( GTK_WINDOW( widget ) ); // check type hint GdkWindowTypeHint hint = gtk_window_get_type_hint( window ); // screen GdkScreen* screen = gdk_screen_get_default(); if( !screen ) return TRUE; if( hint == GDK_WINDOW_TYPE_HINT_DROPDOWN_MENU || hint == GDK_WINDOW_TYPE_HINT_POPUP_MENU || hint == GDK_WINDOW_TYPE_HINT_TOOLTIP || hint == GDK_WINDOW_TYPE_HINT_COMBO ) { #if OXYGEN_DEBUG std::cerr << "Oxygen::ArgbHelper::colormapHook - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << " hint: " << Gtk::TypeNames::windowTypeHint( hint ) << std::endl; #endif GdkColormap* cmap=gdk_screen_get_rgba_colormap( screen ); gtk_widget_set_colormap( widget, cmap ); } return TRUE; } //_____________________________________________________ gboolean ArgbHelper::styleHook( GSignalInvocationHint*, guint, const GValue* params, gpointer ) { // get widget from params GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) ); // check type if( !GTK_IS_WIDGET( widget ) ) return FALSE; // retrieve widget style and check GtkStyle* style( widget->style ); if( !( style && style->depth >= 0 ) ) return TRUE; // retrieve parent window and check GdkWindow* window( gtk_widget_get_parent_window( widget ) ); if( !window ) return TRUE; // adjust depth if( style->depth != gdk_drawable_get_depth( window ) ) { #if OXYGEN_DEBUG std::cerr << "Oxygen::ArgbHelper::styleHook -" << " widget: " << widget << " (" <<G_OBJECT_TYPE_NAME( widget ) << ")" << " style depth: " << style->depth << " window depth: " << gdk_drawable_get_depth( window ) << std::endl; #endif widget->style = gtk_style_attach( style, window ); } return TRUE; } //_________________________________________________________ void ArgbHelper::logHandler( const gchar* domain, GLogLevelFlags flags, const gchar* message, gpointer data ) { /* discard all messages containing "IA__gtk_box_reorder_child:" and fallback to default handler otherwise */ if( std::string( message ).find( "g_object_ref" ) == std::string::npos ) { g_log_default_handler( domain, flags, message, data ); } } } <|endoftext|>
<commit_before>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include <libsoup/soup.h> #include "KmsHttpPost.h" #define OBJECT_NAME "HttpPost" #define MIME_MULTIPART_FORM_DATA "multipart/form-data" #define GST_CAT_DEFAULT kms_http_post_debug_category GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define KMS_HTTP_POST_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), KMS_TYPE_HTTP_POST, KmsHttpPostPrivate)) typedef struct _KmsHttpPostMultipart { gchar *boundary; gboolean got_boundary; gboolean got_last_boundary; } KmsHttpPostMultipart; struct _KmsHttpPostPrivate { KmsHttpPostMultipart *multipart; SoupMessage *msg; gulong handler_id; }; /* class initialization */ G_DEFINE_TYPE_WITH_CODE (KmsHttpPost, kms_http_post, G_TYPE_OBJECT, GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, OBJECT_NAME, 0, "debug category for " OBJECT_NAME " element") ) /* properties */ enum { PROP_0, PROP_MESSAGE, N_PROPERTIES }; #define KMS_HTTP_PORT_DEFAULT_MESSAGE NULL static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, }; /* signals */ enum { GOT_DATA, LAST_SIGNAL }; static guint obj_signals[LAST_SIGNAL] = { 0 }; static void got_chunk_cb (SoupMessage *msg, SoupBuffer *chunk, gpointer data) { GST_DEBUG ("TODO: Process data"); } static void kms_http_post_destroy_multipart (KmsHttpPost *self) { if (self->priv->multipart == NULL) return; if (self->priv->multipart->boundary != NULL) g_free (self->priv->multipart->boundary); g_slice_free (KmsHttpPostMultipart, self->priv->multipart); self->priv->multipart = NULL; } static void kms_http_post_init_multipart (KmsHttpPost *self) { if (self->priv->multipart != NULL) { GST_WARNING ("Multipart data is already initialized"); kms_http_post_destroy_multipart (self); } self->priv->multipart = g_slice_new0 (KmsHttpPostMultipart); } static void kms_http_post_configure_msg (KmsHttpPost *self) { const gchar *content_type; GHashTable *params = NULL; content_type = soup_message_headers_get_content_type (self->priv->msg->request_headers, &params); if (content_type == NULL) { GST_WARNING ("Content-type header is not present in request"); soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE); goto end; } if (g_strcmp0 (content_type, MIME_MULTIPART_FORM_DATA) == 0) { kms_http_post_init_multipart (self); self->priv->multipart->boundary = g_strdup ( (gchar *) g_hash_table_lookup (params, "boundary") ); if (self->priv->multipart->boundary == NULL) { GST_WARNING ("Malformed multipart POST request"); kms_http_post_destroy_multipart (self); soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE); goto end; } } soup_message_set_status (self->priv->msg, SOUP_STATUS_OK); /* Get chunks without filling-in body's data field after */ /* the body is fully sent/received */ soup_message_body_set_accumulate (self->priv->msg->request_body, FALSE); self->priv->handler_id = g_signal_connect (self->priv->msg, "got-chunk", G_CALLBACK (got_chunk_cb), self); end: if (params != NULL) g_hash_table_destroy (params); } static void kms_http_post_release_message (KmsHttpPost *self) { if (self->priv->msg == NULL) return; if (self->priv->handler_id != 0L) { g_signal_handler_disconnect (self->priv->msg, self->priv->handler_id); self->priv->handler_id = 0L; } g_object_unref (self->priv->msg); self->priv->msg = NULL; } static void kms_http_post_set_property (GObject *obj, guint prop_id, const GValue *value, GParamSpec *pspec) { KmsHttpPost *self = KMS_HTTP_POST (obj); switch (prop_id) { case PROP_MESSAGE: kms_http_post_release_message (self); kms_http_post_destroy_multipart (self); self->priv->msg = SOUP_MESSAGE (g_object_ref (g_value_get_object (value) ) ); kms_http_post_configure_msg (self); break; default: /* We don't have any other property... */ G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec); break; } } static void kms_http_post_get_property (GObject *obj, guint prop_id, GValue *value, GParamSpec *pspec) { KmsHttpPost *self = KMS_HTTP_POST (obj); switch (prop_id) { case PROP_MESSAGE: g_value_set_object (value, self->priv->msg); break; default: /* We don't have any other property... */ G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec); break; } } static void kms_http_post_dispose (GObject *obj) { KmsHttpPost *self = KMS_HTTP_POST (obj); kms_http_post_release_message (self); /* Chain up to the parent class */ G_OBJECT_CLASS (kms_http_post_parent_class)->dispose (obj); } static void kms_http_post_finalize (GObject *obj) { KmsHttpPost *self = KMS_HTTP_POST (obj); kms_http_post_destroy_multipart (self); /* Chain up to the parent class */ G_OBJECT_CLASS (kms_http_post_parent_class)->finalize (obj); } static void kms_http_post_class_init (KmsHttpPostClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gobject_class->set_property = kms_http_post_set_property; gobject_class->get_property = kms_http_post_get_property; gobject_class->dispose = kms_http_post_dispose; gobject_class->finalize = kms_http_post_finalize; obj_properties[PROP_MESSAGE] = g_param_spec_object ("soup-message", "Soup message object", "Message to get data from", SOUP_TYPE_MESSAGE, (GParamFlags) (G_PARAM_READWRITE) ); g_object_class_install_properties (gobject_class, N_PROPERTIES, obj_properties); obj_signals[GOT_DATA] = g_signal_new ("got-data", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (KmsHttpPostClass, got_data), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); /* Registers a private structure for an instantiatable type */ g_type_class_add_private (klass, sizeof (KmsHttpPostPrivate) ); } static void kms_http_post_init (KmsHttpPost *self) { self->priv = KMS_HTTP_POST_GET_PRIVATE (self); self->priv->handler_id = 0L; }<commit_msg>KmsHttpPost: Read boundary<commit_after>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include <string.h> #include <libsoup/soup.h> #include "KmsHttpPost.h" #define OBJECT_NAME "HttpPost" #define MIME_MULTIPART_FORM_DATA "multipart/form-data" #define GST_CAT_DEFAULT kms_http_post_debug_category GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define KMS_HTTP_POST_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), KMS_TYPE_HTTP_POST, KmsHttpPostPrivate)) typedef enum { MULTIPART_FIND_BOUNDARY, MULTIPART_READ_HEADERS } ParseState; typedef struct _KmsHttpPostMultipart { gchar *boundary; ParseState state; gchar *tmp_buff; guint len; } KmsHttpPostMultipart; struct _KmsHttpPostPrivate { KmsHttpPostMultipart *multipart; SoupMessage *msg; gulong handler_id; }; /* class initialization */ G_DEFINE_TYPE_WITH_CODE (KmsHttpPost, kms_http_post, G_TYPE_OBJECT, GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, OBJECT_NAME, 0, "debug category for " OBJECT_NAME " element") ) /* properties */ enum { PROP_0, PROP_MESSAGE, N_PROPERTIES }; #define KMS_HTTP_PORT_DEFAULT_MESSAGE NULL static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, }; /* signals */ enum { GOT_DATA, LAST_SIGNAL }; static guint obj_signals[LAST_SIGNAL] = { 0 }; static void kms_http_post_concat_previous_buffer (KmsHttpPost *self, const char **start, const char **end) { if (self->priv->multipart->tmp_buff == NULL) return; self->priv->multipart->tmp_buff = (char *) g_realloc ( self->priv->multipart->tmp_buff, self->priv->multipart->len + (*end - *start) ); memmove (self->priv->multipart->tmp_buff + self->priv->multipart->len, *start, *end - *start); self->priv->multipart->len += (*end - *start); *start = self->priv->multipart->tmp_buff; *end = self->priv->multipart->tmp_buff + self->priv->multipart->len; } static void kms_http_post_find_boundary (KmsHttpPost *self, const char **start, const char **end, const char *boundary, int boundary_len) { const char *b; if (self->priv->multipart->tmp_buff != NULL) kms_http_post_concat_previous_buffer (self, start, end); for (b = (const char *) memchr (*start, '-', *end - *start); b != NULL; b = (const char *) memchr (b + 2, '-', *end - (b + 2) ) ) { if (b + boundary_len + 4 > *end) { /* boundary does not fit in this buffer */ gchar *mem = NULL; if (self->priv->multipart->tmp_buff != NULL) mem = self->priv->multipart->tmp_buff; self->priv->multipart->tmp_buff = (gchar *) g_memdup (b, *end - b); self->priv->multipart->len = *end - b; if (mem != NULL) g_free (mem); return; } /* Check for "--boundary" */ if (b[1] != '-' || memcmp (b + 2, boundary, boundary_len) != 0) continue; /* Check for "--" or "\r\n" after boundary */ if ( (b[boundary_len + 2] == '-' && b[boundary_len + 3] == '-') || (b[boundary_len + 2] == '\r' && b[boundary_len + 3] == '\n') ) { self->priv->multipart->state = MULTIPART_READ_HEADERS; if (*end <= b + boundary_len + 4) { /* Free temporal buffer */ break; } *start = b + boundary_len + 4; return; } } if (self->priv->multipart->tmp_buff != NULL) { g_free (self->priv->multipart->tmp_buff); self->priv->multipart->tmp_buff = NULL; } } static void kms_http_post_parse_multipart_data (KmsHttpPost *self, const char *data, const char *end) { switch (self->priv->multipart->state) { case MULTIPART_FIND_BOUNDARY: /* skip preamble */ kms_http_post_find_boundary (self, &data, &end, self->priv->multipart->boundary, strlen (self->priv->multipart->boundary) ); if (self->priv->multipart->state == MULTIPART_FIND_BOUNDARY) break; case MULTIPART_READ_HEADERS: /* TODO: Read headers */ ; } } static void got_chunk_cb (SoupMessage *msg, SoupBuffer *chunk, gpointer data) { KmsHttpPost *self = KMS_HTTP_POST (data); if (self->priv->multipart == NULL) GST_DEBUG ("Process raw data"); else kms_http_post_parse_multipart_data (self, chunk->data, chunk->data + chunk->length); } static void kms_http_post_destroy_multipart (KmsHttpPost *self) { if (self->priv->multipart == NULL) return; if (self->priv->multipart->boundary != NULL) g_free (self->priv->multipart->boundary); if (self->priv->multipart->tmp_buff != NULL) g_free (self->priv->multipart->tmp_buff); g_slice_free (KmsHttpPostMultipart, self->priv->multipart); self->priv->multipart = NULL; } static void kms_http_post_init_multipart (KmsHttpPost *self) { if (self->priv->multipart != NULL) { GST_WARNING ("Multipart data is already initialized"); kms_http_post_destroy_multipart (self); } self->priv->multipart = g_slice_new0 (KmsHttpPostMultipart); } static void kms_http_post_configure_msg (KmsHttpPost *self) { const gchar *content_type; GHashTable *params = NULL; content_type = soup_message_headers_get_content_type (self->priv->msg->request_headers, &params); if (content_type == NULL) { GST_WARNING ("Content-type header is not present in request"); soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE); goto end; } if (g_strcmp0 (content_type, MIME_MULTIPART_FORM_DATA) == 0) { kms_http_post_init_multipart (self); self->priv->multipart->boundary = g_strdup ( (gchar *) g_hash_table_lookup (params, "boundary") ); if (self->priv->multipart->boundary == NULL) { GST_WARNING ("Malformed multipart POST request"); kms_http_post_destroy_multipart (self); soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE); goto end; } } soup_message_set_status (self->priv->msg, SOUP_STATUS_OK); /* Get chunks without filling-in body's data field after */ /* the body is fully sent/received */ soup_message_body_set_accumulate (self->priv->msg->request_body, FALSE); self->priv->handler_id = g_signal_connect (self->priv->msg, "got-chunk", G_CALLBACK (got_chunk_cb), self); end: if (params != NULL) g_hash_table_destroy (params); } static void kms_http_post_release_message (KmsHttpPost *self) { if (self->priv->msg == NULL) return; if (self->priv->handler_id != 0L) { g_signal_handler_disconnect (self->priv->msg, self->priv->handler_id); self->priv->handler_id = 0L; } g_object_unref (self->priv->msg); self->priv->msg = NULL; } static void kms_http_post_set_property (GObject *obj, guint prop_id, const GValue *value, GParamSpec *pspec) { KmsHttpPost *self = KMS_HTTP_POST (obj); switch (prop_id) { case PROP_MESSAGE: kms_http_post_release_message (self); kms_http_post_destroy_multipart (self); self->priv->msg = SOUP_MESSAGE (g_object_ref (g_value_get_object (value) ) ); kms_http_post_configure_msg (self); break; default: /* We don't have any other property... */ G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec); break; } } static void kms_http_post_get_property (GObject *obj, guint prop_id, GValue *value, GParamSpec *pspec) { KmsHttpPost *self = KMS_HTTP_POST (obj); switch (prop_id) { case PROP_MESSAGE: g_value_set_object (value, self->priv->msg); break; default: /* We don't have any other property... */ G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec); break; } } static void kms_http_post_dispose (GObject *obj) { KmsHttpPost *self = KMS_HTTP_POST (obj); kms_http_post_release_message (self); /* Chain up to the parent class */ G_OBJECT_CLASS (kms_http_post_parent_class)->dispose (obj); } static void kms_http_post_finalize (GObject *obj) { KmsHttpPost *self = KMS_HTTP_POST (obj); kms_http_post_destroy_multipart (self); /* Chain up to the parent class */ G_OBJECT_CLASS (kms_http_post_parent_class)->finalize (obj); } static void kms_http_post_class_init (KmsHttpPostClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gobject_class->set_property = kms_http_post_set_property; gobject_class->get_property = kms_http_post_get_property; gobject_class->dispose = kms_http_post_dispose; gobject_class->finalize = kms_http_post_finalize; obj_properties[PROP_MESSAGE] = g_param_spec_object ("soup-message", "Soup message object", "Message to get data from", SOUP_TYPE_MESSAGE, (GParamFlags) (G_PARAM_READWRITE) ); g_object_class_install_properties (gobject_class, N_PROPERTIES, obj_properties); obj_signals[GOT_DATA] = g_signal_new ("got-data", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (KmsHttpPostClass, got_data), NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); /* Registers a private structure for an instantiatable type */ g_type_class_add_private (klass, sizeof (KmsHttpPostPrivate) ); } static void kms_http_post_init (KmsHttpPost *self) { self->priv = KMS_HTTP_POST_GET_PRIVATE (self); self->priv->handler_id = 0L; }<|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011-2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <thread> #include <type_traits> #include "boost_cfg.hpp" #include <boost/mpl/vector.hpp> #include <boost/mpl/for_each.hpp> #include "Options.hpp" #include "PerfsTimer.hpp" #include "iterators.hpp" #include "likely.hpp" #include "logging.hpp" #include "timing.hpp" #include "GlobalContext.hpp" #include "ltac/Statement.hpp" #include "mtac/pass_traits.hpp" #include "mtac/Utils.hpp" #include "mtac/Pass.hpp" #include "mtac/Optimizer.hpp" #include "mtac/Program.hpp" #include "mtac/ControlFlowGraph.hpp" #include "mtac/Quadruple.hpp" //The custom optimizations #include "mtac/conditional_propagation.hpp" #include "mtac/remove_aliases.hpp" #include "mtac/clean_variables.hpp" #include "mtac/remove_unused_functions.hpp" #include "mtac/remove_empty_functions.hpp" #include "mtac/DeadCodeElimination.hpp" #include "mtac/merge_basic_blocks.hpp" #include "mtac/remove_dead_basic_blocks.hpp" #include "mtac/BranchOptimizations.hpp" #include "mtac/inlining.hpp" #include "mtac/loop_analysis.hpp" #include "mtac/induction_variable_optimizations.hpp" #include "mtac/loop_unrolling.hpp" #include "mtac/complete_loop_peeling.hpp" #include "mtac/remove_empty_loops.hpp" #include "mtac/loop_invariant_code_motion.hpp" #include "mtac/parameter_propagation.hpp" #include "mtac/pure_analysis.hpp" //The optimization visitors #include "mtac/ArithmeticIdentities.hpp" #include "mtac/ReduceInStrength.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/MathPropagation.hpp" #include "mtac/PointerPropagation.hpp" //The data-flow problems #include "mtac/GlobalOptimizations.hpp" #include "mtac/ConstantPropagationProblem.hpp" #include "mtac/OffsetConstantPropagationProblem.hpp" #include "mtac/CommonSubexpressionElimination.hpp" #include "ltac/Register.hpp" #include "ltac/FloatRegister.hpp" #include "ltac/PseudoRegister.hpp" #include "ltac/PseudoFloatRegister.hpp" #include "ltac/Address.hpp" using namespace eddic; namespace eddic { namespace mtac { typedef boost::mpl::vector< mtac::ConstantFolding* > basic_passes; struct all_basic_optimizations {}; template<> struct pass_traits<all_basic_optimizations> { STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB); STATIC_STRING(name, "all_basic_optimizations"); STATIC_CONSTANT(unsigned int, property_flags, 0); STATIC_CONSTANT(unsigned int, todo_after_flags, 0); typedef basic_passes sub_passes; }; typedef boost::mpl::vector< mtac::ArithmeticIdentities*, mtac::ReduceInStrength*, mtac::ConstantFolding*, mtac::conditional_propagation*, mtac::ConstantPropagationProblem*, mtac::OffsetConstantPropagationProblem*, mtac::CommonSubexpressionElimination*, mtac::PointerPropagation*, mtac::MathPropagation*, mtac::optimize_branches*, mtac::remove_dead_basic_blocks*, mtac::merge_basic_blocks*, mtac::dead_code_elimination*, mtac::remove_aliases*, mtac::loop_analysis*, mtac::loop_invariant_code_motion*, mtac::loop_induction_variables_optimization*, mtac::remove_empty_loops*, mtac::complete_loop_peeling*, mtac::loop_unrolling*, mtac::clean_variables* > passes; struct all_optimizations {}; template<> struct pass_traits<all_optimizations> { STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB); STATIC_STRING(name, "all_optimizations"); STATIC_CONSTANT(unsigned int, property_flags, 0); STATIC_CONSTANT(unsigned int, todo_after_flags, 0); typedef passes sub_passes; }; } } namespace { template<typename T, typename Sign> struct has_gate { typedef char yes[1]; typedef char no [2]; template <typename U, U> struct type_check; template <typename _1> static yes &chk(type_check<Sign, &_1::gate> *); template <typename > static no &chk(...); static bool const value = sizeof(chk<T>(0)) == sizeof(yes); }; typedef boost::mpl::vector< mtac::remove_unused_functions*, mtac::all_basic_optimizations* > ipa_basic_passes; typedef boost::mpl::vector< mtac::remove_unused_functions*, mtac::pure_analysis*, mtac::all_optimizations*, mtac::remove_empty_functions*, mtac::remove_unused_functions*, mtac::inline_functions*, mtac::parameter_propagation* > ipa_passes; template<typename Pass> struct need_pool { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_POOL; }; template<typename Pass> struct need_platform { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PLATFORM; }; template<typename Pass> struct need_configuration { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_CONFIGURATION; }; template<typename Pass> struct need_program { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PROGRAM; }; template <bool B, typename T = void> struct disable_if { typedef T type; }; template <typename T> struct disable_if<true,T> { //SFINAE }; struct pass_runner { bool optimized = false; mtac::Program& program; mtac::Function* function; std::shared_ptr<StringPool> pool; std::shared_ptr<Configuration> configuration; Platform platform; timing_system& system; pass_runner(mtac::Program& program, std::shared_ptr<StringPool> pool, std::shared_ptr<Configuration> configuration, Platform platform, timing_system& system) : program(program), pool(pool), configuration(configuration), platform(platform), system(system) {}; template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP, void>::type remove_nop(){ for(auto& block : *function){ auto it = iterate(block->statements); while(it.has_next()){ if(it->op == mtac::Operator::NOP){ it.erase(); continue; } ++it; } } } template<typename Pass> inline typename std::enable_if<!(mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP), void>::type remove_nop(){ //NOP } template<typename Pass> inline void apply_todo(){ remove_nop<Pass>(); } template<typename Pass> inline typename std::enable_if<need_pool<Pass>::value, void>::type set_pool(Pass& pass){ pass.set_pool(pool); } template<typename Pass> inline typename disable_if<need_pool<Pass>::value, void>::type set_pool(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_platform<Pass>::value, void>::type set_platform(Pass& pass){ pass.set_platform(platform); } template<typename Pass> inline typename disable_if<need_platform<Pass>::value, void>::type set_platform(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_configuration<Pass>::value, void>::type set_configuration(Pass& pass){ pass.set_configuration(configuration); } template<typename Pass> inline typename disable_if<need_configuration<Pass>::value, void>::type set_configuration(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_program<Pass>::value, Pass>::type construct(){ return Pass(program); } template<typename Pass> inline typename disable_if<need_program<Pass>::value, Pass>::type construct(){ return Pass(); } template<typename Pass> Pass make_pass(){ auto pass = construct<Pass>(); set_pool(pass); set_platform(pass); set_configuration(pass); return pass; } template<typename Pass> inline typename std::enable_if<has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool>::type has_to_be_run(Pass& pass){ return pass.gate(configuration); } template<typename Pass> inline typename disable_if<has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool>::type has_to_be_run(Pass&){ return true; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, bool>::type apply(Pass& pass){ return pass(program); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB, bool>::type apply(Pass&){ for(auto& function : program.functions){ this->function = &function; if(log::enabled<Debug>()){ LOG<Debug>("Optimizer") << "Start optimizations on " << function.get_name() << log::endl; std::cout << function << std::endl; } boost::mpl::for_each<typename mtac::pass_traits<Pass>::sub_passes>(boost::ref(*this)); } return false; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::CUSTOM, bool>::type apply(Pass& pass){ return pass(*function); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::LOCAL, bool>::type apply(Pass& visitor){ for(auto& block : *function){ for(auto& quadruple : block->statements){ visitor(quadruple); } } return visitor.optimized; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::DATA_FLOW, bool>::type apply(Pass& problem){ auto results = mtac::data_flow(*function, problem); //Once the data-flow problem is fixed, statements can be optimized return problem.optimize(*function, results); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB, bool>::type apply(Pass& visitor){ bool optimized = false; for(auto& block : *function){ visitor.clear(); for(auto& quadruple : block->statements){ visitor(quadruple); } optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB_TWO_PASS, bool>::type apply(Pass& visitor){ bool optimized = false; for(auto& block : *function){ visitor.clear(); visitor.pass = mtac::Pass::DATA_MINING; for(auto& quadruple : block->statements){ visitor(quadruple); } visitor.pass = mtac::Pass::OPTIMIZE; for(auto& quadruple : block->statements){ visitor(quadruple); } optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline typename std::enable_if<boost::type_traits::ice_or<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB>::value, void>::type debug_local(bool local){ LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned " << local << log::endl; } template<typename Pass> inline typename std::enable_if<boost::type_traits::ice_and<mtac::pass_traits<Pass>::type != mtac::pass_type::IPA, mtac::pass_traits<Pass>::type != mtac::pass_type::IPA_SUB>::value, void>::type debug_local(bool local){ if(log::enabled<Debug>()){ if(local){ LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned true" << log::endl; //Print the function std::cout << *function << std::endl; } else { LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned false" << log::endl; } } } template<typename Pass> inline void operator()(Pass*){ auto pass = make_pass<Pass>(); if(has_to_be_run(pass)){ bool local = false; { PerfsTimer perfs_timer(mtac::pass_traits<Pass>::name()); timing_timer timer(system, mtac::pass_traits<Pass>::name()); local = apply<Pass>(pass); } if(local){ program.context->stats().inc_counter(std::string(mtac::pass_traits<Pass>::name()) + "_true"); apply_todo<Pass>(); } debug_local<Pass>(local); optimized |= local; } } }; } //end of anonymous namespace void mtac::Optimizer::optimize(mtac::Program& program, std::shared_ptr<StringPool> string_pool, Platform platform, std::shared_ptr<Configuration> configuration) const { timing_timer timer(program.context->timing(), "whole_optimizations"); //Build the CFG of each functions (also needed for register allocation) for(auto& function : program.functions){ timing_timer timer(program.context->timing(), "build_cfg"); mtac::build_control_flow_graph(function); } if(configuration->option_defined("fglobal-optimization")){ //Apply Interprocedural Optimizations pass_runner runner(program, string_pool, configuration, platform, program.context->timing()); do{ runner.optimized = false; boost::mpl::for_each<ipa_passes>(boost::ref(runner)); } while(runner.optimized); } else { //Even if global optimizations are disabled, perform basic optimization (only constant folding) pass_runner runner(program, string_pool, configuration, platform, program.context->timing()); boost::mpl::for_each<ipa_basic_passes>(boost::ref(runner)); } } <commit_msg>Include TODO in the timing of the passes<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011-2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <thread> #include <type_traits> #include "boost_cfg.hpp" #include <boost/mpl/vector.hpp> #include <boost/mpl/for_each.hpp> #include "Options.hpp" #include "PerfsTimer.hpp" #include "iterators.hpp" #include "likely.hpp" #include "logging.hpp" #include "timing.hpp" #include "GlobalContext.hpp" #include "ltac/Statement.hpp" #include "mtac/pass_traits.hpp" #include "mtac/Utils.hpp" #include "mtac/Pass.hpp" #include "mtac/Optimizer.hpp" #include "mtac/Program.hpp" #include "mtac/ControlFlowGraph.hpp" #include "mtac/Quadruple.hpp" //The custom optimizations #include "mtac/conditional_propagation.hpp" #include "mtac/remove_aliases.hpp" #include "mtac/clean_variables.hpp" #include "mtac/remove_unused_functions.hpp" #include "mtac/remove_empty_functions.hpp" #include "mtac/DeadCodeElimination.hpp" #include "mtac/merge_basic_blocks.hpp" #include "mtac/remove_dead_basic_blocks.hpp" #include "mtac/BranchOptimizations.hpp" #include "mtac/inlining.hpp" #include "mtac/loop_analysis.hpp" #include "mtac/induction_variable_optimizations.hpp" #include "mtac/loop_unrolling.hpp" #include "mtac/complete_loop_peeling.hpp" #include "mtac/remove_empty_loops.hpp" #include "mtac/loop_invariant_code_motion.hpp" #include "mtac/parameter_propagation.hpp" #include "mtac/pure_analysis.hpp" //The optimization visitors #include "mtac/ArithmeticIdentities.hpp" #include "mtac/ReduceInStrength.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/MathPropagation.hpp" #include "mtac/PointerPropagation.hpp" //The data-flow problems #include "mtac/GlobalOptimizations.hpp" #include "mtac/ConstantPropagationProblem.hpp" #include "mtac/OffsetConstantPropagationProblem.hpp" #include "mtac/CommonSubexpressionElimination.hpp" #include "ltac/Register.hpp" #include "ltac/FloatRegister.hpp" #include "ltac/PseudoRegister.hpp" #include "ltac/PseudoFloatRegister.hpp" #include "ltac/Address.hpp" using namespace eddic; namespace eddic { namespace mtac { typedef boost::mpl::vector< mtac::ConstantFolding* > basic_passes; struct all_basic_optimizations {}; template<> struct pass_traits<all_basic_optimizations> { STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB); STATIC_STRING(name, "all_basic_optimizations"); STATIC_CONSTANT(unsigned int, property_flags, 0); STATIC_CONSTANT(unsigned int, todo_after_flags, 0); typedef basic_passes sub_passes; }; typedef boost::mpl::vector< mtac::ArithmeticIdentities*, mtac::ReduceInStrength*, mtac::ConstantFolding*, mtac::conditional_propagation*, mtac::ConstantPropagationProblem*, mtac::OffsetConstantPropagationProblem*, mtac::CommonSubexpressionElimination*, mtac::PointerPropagation*, mtac::MathPropagation*, mtac::optimize_branches*, mtac::remove_dead_basic_blocks*, mtac::merge_basic_blocks*, mtac::dead_code_elimination*, mtac::remove_aliases*, mtac::loop_analysis*, mtac::loop_invariant_code_motion*, mtac::loop_induction_variables_optimization*, mtac::remove_empty_loops*, mtac::complete_loop_peeling*, mtac::loop_unrolling*, mtac::clean_variables* > passes; struct all_optimizations {}; template<> struct pass_traits<all_optimizations> { STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB); STATIC_STRING(name, "all_optimizations"); STATIC_CONSTANT(unsigned int, property_flags, 0); STATIC_CONSTANT(unsigned int, todo_after_flags, 0); typedef passes sub_passes; }; } } namespace { template<typename T, typename Sign> struct has_gate { typedef char yes[1]; typedef char no [2]; template <typename U, U> struct type_check; template <typename _1> static yes &chk(type_check<Sign, &_1::gate> *); template <typename > static no &chk(...); static bool const value = sizeof(chk<T>(0)) == sizeof(yes); }; typedef boost::mpl::vector< mtac::remove_unused_functions*, mtac::all_basic_optimizations* > ipa_basic_passes; typedef boost::mpl::vector< mtac::remove_unused_functions*, mtac::pure_analysis*, mtac::all_optimizations*, mtac::remove_empty_functions*, mtac::remove_unused_functions*, mtac::inline_functions*, mtac::parameter_propagation* > ipa_passes; template<typename Pass> struct need_pool { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_POOL; }; template<typename Pass> struct need_platform { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PLATFORM; }; template<typename Pass> struct need_configuration { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_CONFIGURATION; }; template<typename Pass> struct need_program { static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PROGRAM; }; template <bool B, typename T = void> struct disable_if { typedef T type; }; template <typename T> struct disable_if<true,T> { //SFINAE }; struct pass_runner { bool optimized = false; mtac::Program& program; mtac::Function* function; std::shared_ptr<StringPool> pool; std::shared_ptr<Configuration> configuration; Platform platform; timing_system& system; pass_runner(mtac::Program& program, std::shared_ptr<StringPool> pool, std::shared_ptr<Configuration> configuration, Platform platform, timing_system& system) : program(program), pool(pool), configuration(configuration), platform(platform), system(system) {}; template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP, void>::type remove_nop(){ for(auto& block : *function){ auto it = iterate(block->statements); while(it.has_next()){ if(it->op == mtac::Operator::NOP){ it.erase(); continue; } ++it; } } } template<typename Pass> inline typename std::enable_if<!(mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP), void>::type remove_nop(){ //NOP } template<typename Pass> inline void apply_todo(){ remove_nop<Pass>(); } template<typename Pass> inline typename std::enable_if<need_pool<Pass>::value, void>::type set_pool(Pass& pass){ pass.set_pool(pool); } template<typename Pass> inline typename disable_if<need_pool<Pass>::value, void>::type set_pool(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_platform<Pass>::value, void>::type set_platform(Pass& pass){ pass.set_platform(platform); } template<typename Pass> inline typename disable_if<need_platform<Pass>::value, void>::type set_platform(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_configuration<Pass>::value, void>::type set_configuration(Pass& pass){ pass.set_configuration(configuration); } template<typename Pass> inline typename disable_if<need_configuration<Pass>::value, void>::type set_configuration(Pass&){ //NOP } template<typename Pass> inline typename std::enable_if<need_program<Pass>::value, Pass>::type construct(){ return Pass(program); } template<typename Pass> inline typename disable_if<need_program<Pass>::value, Pass>::type construct(){ return Pass(); } template<typename Pass> Pass make_pass(){ auto pass = construct<Pass>(); set_pool(pass); set_platform(pass); set_configuration(pass); return pass; } template<typename Pass> inline typename std::enable_if<has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool>::type has_to_be_run(Pass& pass){ return pass.gate(configuration); } template<typename Pass> inline typename disable_if<has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool>::type has_to_be_run(Pass&){ return true; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, bool>::type apply(Pass& pass){ return pass(program); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB, bool>::type apply(Pass&){ for(auto& function : program.functions){ this->function = &function; if(log::enabled<Debug>()){ LOG<Debug>("Optimizer") << "Start optimizations on " << function.get_name() << log::endl; std::cout << function << std::endl; } boost::mpl::for_each<typename mtac::pass_traits<Pass>::sub_passes>(boost::ref(*this)); } return false; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::CUSTOM, bool>::type apply(Pass& pass){ return pass(*function); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::LOCAL, bool>::type apply(Pass& visitor){ for(auto& block : *function){ for(auto& quadruple : block->statements){ visitor(quadruple); } } return visitor.optimized; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::DATA_FLOW, bool>::type apply(Pass& problem){ auto results = mtac::data_flow(*function, problem); //Once the data-flow problem is fixed, statements can be optimized return problem.optimize(*function, results); } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB, bool>::type apply(Pass& visitor){ bool optimized = false; for(auto& block : *function){ visitor.clear(); for(auto& quadruple : block->statements){ visitor(quadruple); } optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB_TWO_PASS, bool>::type apply(Pass& visitor){ bool optimized = false; for(auto& block : *function){ visitor.clear(); visitor.pass = mtac::Pass::DATA_MINING; for(auto& quadruple : block->statements){ visitor(quadruple); } visitor.pass = mtac::Pass::OPTIMIZE; for(auto& quadruple : block->statements){ visitor(quadruple); } optimized |= visitor.optimized; } return optimized; } template<typename Pass> inline typename std::enable_if<boost::type_traits::ice_or<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB>::value, void>::type debug_local(bool local){ LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned " << local << log::endl; } template<typename Pass> inline typename std::enable_if<boost::type_traits::ice_and<mtac::pass_traits<Pass>::type != mtac::pass_type::IPA, mtac::pass_traits<Pass>::type != mtac::pass_type::IPA_SUB>::value, void>::type debug_local(bool local){ if(log::enabled<Debug>()){ if(local){ LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned true" << log::endl; //Print the function std::cout << *function << std::endl; } else { LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned false" << log::endl; } } } template<typename Pass> inline void operator()(Pass*){ auto pass = make_pass<Pass>(); if(has_to_be_run(pass)){ timing_timer timer(system, mtac::pass_traits<Pass>::name()); bool local = local = apply<Pass>(pass); if(local){ program.context->stats().inc_counter(std::string(mtac::pass_traits<Pass>::name()) + "_true"); apply_todo<Pass>(); } debug_local<Pass>(local); optimized |= local; } } }; } //end of anonymous namespace void mtac::Optimizer::optimize(mtac::Program& program, std::shared_ptr<StringPool> string_pool, Platform platform, std::shared_ptr<Configuration> configuration) const { timing_timer timer(program.context->timing(), "whole_optimizations"); //Build the CFG of each functions (also needed for register allocation) for(auto& function : program.functions){ timing_timer timer(program.context->timing(), "build_cfg"); mtac::build_control_flow_graph(function); } if(configuration->option_defined("fglobal-optimization")){ //Apply Interprocedural Optimizations pass_runner runner(program, string_pool, configuration, platform, program.context->timing()); do{ runner.optimized = false; boost::mpl::for_each<ipa_passes>(boost::ref(runner)); } while(runner.optimized); } else { //Even if global optimizations are disabled, perform basic optimization (only constant folding) pass_runner runner(program, string_pool, configuration, platform, program.context->timing()); boost::mpl::for_each<ipa_basic_passes>(boost::ref(runner)); } } <|endoftext|>
<commit_before><commit_msg>something<commit_after><|endoftext|>
<commit_before>#include "ospray/common/OSPCommon.h" #include "ospray/common/Thread.h" #include "common/sys/sync/barrier.h" namespace ospray { using namespace std; volatile size_t sum = 0; volatile int nextFreeID = 0; volatile bool done = 0; double timeToRun = 1.f; embree::MutexSys mutex; embree::BarrierSys barrier; struct MyThread : public Thread { MyThread(int numThreads) { } virtual void run() { mutex.lock(); int myID = nextFreeID++; mutex.unlock(); barrier.wait(); double t0 = getSysTime(); int lastPing = 0; while (1) { barrier.wait(); if (done) { break; } mutex.lock(); sum += 1; mutex.unlock(); barrier.wait(); double t1 = getSysTime(); if (myID == 0) { int numSecs = int(t1-t0); if (numSecs > lastPing) { printf("after t=%5.f2s: num ops =%8li, that's %f ops/sec\n", t1-t0,sum,sum/(t1-t0)); } } if (myID == 0 && (t1 - t0) >= timeToRun) done = true; } if (myID == 0) cout << "total number of OPs: " << sum << endl; } }; extern "C" int main(int ac, char **av) { int numThreads = 10; int firstThreadID = 1; for (int i=1;i<ac;i++) { const std::string arg = av[i]; if (arg == "-nt") numThreads = atoi(av[++i]); else if (arg == "-ft") firstThreadID = atoi(av[++i]); else if (arg == "-ns") timeToRun = atof(av[++i]); else throw std::runtime_error("unknown parameter '"+arg+"'"); } barrier.init(numThreads); MyThread **thread = new MyThread *[numThreads]; for (int i=0;i<numThreads;i++) { thread[i] = new MyThread(numThreads); thread[i]->start(firstThreadID+i); } for (int i=0;i<numThreads;i++) thread[i]->join(); return 0; } } <commit_msg>bugfix in output<commit_after>#include "ospray/common/OSPCommon.h" #include "ospray/common/Thread.h" #include "common/sys/sync/barrier.h" namespace ospray { using namespace std; volatile size_t sum = 0; volatile int nextFreeID = 0; volatile bool done = 0; double timeToRun = 1.f; embree::MutexSys mutex; embree::BarrierSys barrier; struct MyThread : public Thread { MyThread(int numThreads) { } virtual void run() { mutex.lock(); int myID = nextFreeID++; mutex.unlock(); barrier.wait(); double t0 = getSysTime(); int lastPing = 0; while (1) { barrier.wait(); if (done) { break; } mutex.lock(); sum += 1; mutex.unlock(); barrier.wait(); double t1 = getSysTime(); if (myID == 0) { int numSecs = int(t1-t0); if (numSecs > lastPing) { printf("after t=%5.f2s: num ops =%8li, that's %f ops/sec\n", t1-t0,sum,sum/(t1-t0)); lastPing = numSecs; } } if (myID == 0 && (t1 - t0) >= timeToRun) done = true; } if (myID == 0) cout << "total number of OPs: " << sum << endl; } }; extern "C" int main(int ac, char **av) { int numThreads = 10; int firstThreadID = 1; for (int i=1;i<ac;i++) { const std::string arg = av[i]; if (arg == "-nt") numThreads = atoi(av[++i]); else if (arg == "-ft") firstThreadID = atoi(av[++i]); else if (arg == "-ns") timeToRun = atof(av[++i]); else throw std::runtime_error("unknown parameter '"+arg+"'"); } barrier.init(numThreads); MyThread **thread = new MyThread *[numThreads]; for (int i=0;i<numThreads;i++) { thread[i] = new MyThread(numThreads); thread[i]->start(firstThreadID+i); } for (int i=0;i<numThreads;i++) thread[i]->join(); return 0; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: regexp.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:19:17 $ * * 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 _UCB_REGEXP_HXX_ #include <regexp.hxx> #endif #include <cstddef> #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _VOS_DIAGNOSE_H_ #include <vos/diagnose.hxx> #endif namespace unnamed_ucb_regexp {} using namespace unnamed_ucb_regexp; // unnamed namespaces don't work well yet... using namespace com::sun::star; using namespace ucb; //============================================================================ // // Regexp // //============================================================================ inline Regexp::Regexp(Kind eTheKind, rtl::OUString const & rThePrefix, bool bTheEmptyDomain, rtl::OUString const & rTheInfix, bool bTheTranslation, rtl::OUString const & rTheReversePrefix): m_eKind(eTheKind), m_aPrefix(rThePrefix), m_aInfix(rTheInfix), m_aReversePrefix(rTheReversePrefix), m_bEmptyDomain(bTheEmptyDomain), m_bTranslation(bTheTranslation) { VOS_ASSERT(m_eKind == KIND_DOMAIN || !m_bEmptyDomain && m_aInfix.getLength() == 0); VOS_ASSERT(m_bTranslation || m_aReversePrefix.getLength() == 0); } //============================================================================ namespace unnamed_ucb_regexp { bool matchStringIgnoreCase(sal_Unicode const ** pBegin, sal_Unicode const * pEnd, rtl::OUString const & rString) { sal_Unicode const * p = *pBegin; sal_Unicode const * q = rString.getStr(); sal_Unicode const * qEnd = q + rString.getLength(); if (pEnd - p < qEnd - q) return false; while (q != qEnd) { sal_Unicode c1 = *p++; sal_Unicode c2 = *q++; if (c1 >= 'a' && c1 <= 'z') c1 -= 'a' - 'A'; if (c2 >= 'a' && c2 <= 'z') c2 -= 'a' - 'A'; if (c1 != c2) return false; } *pBegin = p; return true; } } bool Regexp::matches(rtl::OUString const & rString, rtl::OUString * pTranslation, bool * pTranslated) const { sal_Unicode const * pBegin = rString.getStr(); sal_Unicode const * pEnd = pBegin + rString.getLength(); bool bMatches = false; sal_Unicode const * p = pBegin; if (matchStringIgnoreCase(&p, pEnd, m_aPrefix)) { sal_Unicode const * pBlock1Begin = p; sal_Unicode const * pBlock1End = pEnd; sal_Unicode const * pBlock2Begin = 0; sal_Unicode const * pBlock2End = 0; switch (m_eKind) { case KIND_PREFIX: bMatches = true; break; case KIND_AUTHORITY: bMatches = p == pEnd || *p == '/' || *p == '?' || *p == '#'; break; case KIND_DOMAIN: if (!m_bEmptyDomain) { if (p == pEnd || *p == '/' || *p == '?' || *p == '#') break; ++p; } for (;;) { sal_Unicode const * q = p; if (matchStringIgnoreCase(&q, pEnd, m_aInfix) && (q == pEnd || *q == '/' || *q == '?' || *q == '#')) { bMatches = true; pBlock1End = p; pBlock2Begin = q; pBlock2End = pEnd; break; } if (p == pEnd) break; sal_Unicode c = *p++; if (c == '/' || c == '?' || c == '#') break; } break; } if (bMatches) if (m_bTranslation) { if (pTranslation) { rtl::OUStringBuffer aBuffer(m_aReversePrefix); aBuffer.append(pBlock1Begin, pBlock1End - pBlock1Begin); aBuffer.append(m_aInfix); aBuffer.append(pBlock2Begin, pBlock2End - pBlock2Begin); *pTranslation = aBuffer.makeStringAndClear(); } if (pTranslated) *pTranslated = true; } else { if (pTranslation) *pTranslation = rString; if (pTranslated) *pTranslated = false; } } return bMatches; } //============================================================================ namespace unnamed_ucb_regexp { inline bool isAlpha(sal_Unicode c) { return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'; } inline bool isDigit(sal_Unicode c) { return c >= '0' && c <= '9'; } bool isScheme(rtl::OUString const & rString, bool bColon) { // Return true if rString matches <scheme> (plus a trailing ":" if bColon // is true) from RFC 2396: sal_Unicode const * p = rString.getStr(); sal_Unicode const * pEnd = p + rString.getLength(); if (p != pEnd && isAlpha(*p)) for (++p;;) { if (p == pEnd) return !bColon; sal_Unicode c = *p++; if (!(isAlpha(c) || isDigit(c) || c == '+' || c == '-' || c == '.')) return bColon && c == ':' && p == pEnd; } return false; } void appendStringLiteral(rtl::OUStringBuffer * pBuffer, rtl::OUString const & rString) { VOS_ASSERT(pBuffer); pBuffer->append(sal_Unicode('"')); sal_Unicode const * p = rString.getStr(); sal_Unicode const * pEnd = p + rString.getLength(); while (p != pEnd) { sal_Unicode c = *p++; if (c == '"' || c == '\\') pBuffer->append(sal_Unicode('\\')); pBuffer->append(c); } pBuffer->append(sal_Unicode('"')); } } rtl::OUString Regexp::getRegexp(bool bReverse) const { if (m_bTranslation) { rtl::OUStringBuffer aBuffer; if (bReverse) { if (m_aReversePrefix.getLength() != 0) appendStringLiteral(&aBuffer, m_aReversePrefix); } else { if (m_aPrefix.getLength() != 0) appendStringLiteral(&aBuffer, m_aPrefix); } switch (m_eKind) { case KIND_PREFIX: aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("(.*)")); break; case KIND_AUTHORITY: aBuffer. appendAscii(RTL_CONSTASCII_STRINGPARAM("(([/?#].*)?)")); break; case KIND_DOMAIN: aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([^/?#]")); aBuffer.append(sal_Unicode(m_bEmptyDomain ? '*' : '+')); if (m_aInfix.getLength() != 0) appendStringLiteral(&aBuffer, m_aInfix); aBuffer. appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?)")); break; } aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("->")); if (bReverse) { if (m_aPrefix.getLength() != 0) appendStringLiteral(&aBuffer, m_aPrefix); } else { if (m_aReversePrefix.getLength() != 0) appendStringLiteral(&aBuffer, m_aReversePrefix); } aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("\\1")); return aBuffer.makeStringAndClear(); } else if (m_eKind == KIND_PREFIX && isScheme(m_aPrefix, true)) return m_aPrefix.copy(0, m_aPrefix.getLength() - 1); else { rtl::OUStringBuffer aBuffer; if (m_aPrefix.getLength() != 0) appendStringLiteral(&aBuffer, m_aPrefix); switch (m_eKind) { case KIND_PREFIX: aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM(".*")); break; case KIND_AUTHORITY: aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?")); break; case KIND_DOMAIN: aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("[^/?#]")); aBuffer.append(sal_Unicode(m_bEmptyDomain ? '*' : '+')); if (m_aInfix.getLength() != 0) appendStringLiteral(&aBuffer, m_aInfix); aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?")); break; } return aBuffer.makeStringAndClear(); } } //============================================================================ namespace unnamed_ucb_regexp { bool matchString(sal_Unicode const ** pBegin, sal_Unicode const * pEnd, sal_Char const * pString, size_t nStringLength) { sal_Unicode const * p = *pBegin; sal_uChar const * q = reinterpret_cast< sal_uChar const * >(pString); sal_uChar const * qEnd = q + nStringLength; if (pEnd - p < qEnd - q) return false; while (q != qEnd) { sal_Unicode c1 = *p++; sal_Unicode c2 = *q++; if (c1 != c2) return false; } *pBegin = p; return true; } bool scanStringLiteral(sal_Unicode const ** pBegin, sal_Unicode const * pEnd, rtl::OUString * pString) { sal_Unicode const * p = *pBegin; if (p == pEnd || *p++ != '"') return false; rtl::OUStringBuffer aBuffer; for (;;) { if (p == pEnd) return false; sal_Unicode c = *p++; if (c == '"') break; if (c == '\\') { if (p == pEnd) return false; c = *p++; if (c != '"' && c != '\\') return false; } aBuffer.append(c); } *pBegin = p; *pString = aBuffer.makeStringAndClear(); return true; } } Regexp Regexp::parse(rtl::OUString const & rRegexp) { // Detect an input of '<scheme>' as an abbreviation of '"<scheme>:".*' // where <scheme> is as defined in RFC 2396: if (isScheme(rRegexp, false)) return Regexp(Regexp::KIND_PREFIX, rRegexp + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(":")), false, rtl::OUString(), false, rtl::OUString()); sal_Unicode const * p = rRegexp.getStr(); sal_Unicode const * pEnd = p + rRegexp.getLength(); rtl::OUString aPrefix; scanStringLiteral(&p, pEnd, &aPrefix); if (p == pEnd) throw lang::IllegalArgumentException(); if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM(".*"))) { if (p != pEnd) throw lang::IllegalArgumentException(); return Regexp(Regexp::KIND_PREFIX, aPrefix, false, rtl::OUString(), false, rtl::OUString()); } else if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("(.*)->"))) { rtl::OUString aReversePrefix; scanStringLiteral(&p, pEnd, &aReversePrefix); if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1")) || p != pEnd) throw lang::IllegalArgumentException(); return Regexp(Regexp::KIND_PREFIX, aPrefix, false, rtl::OUString(), true, aReversePrefix); } else if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("([/?#].*)?"))) { if (p != pEnd) throw lang::IllegalArgumentException(); return Regexp(Regexp::KIND_AUTHORITY, aPrefix, false, rtl::OUString(), false, rtl::OUString()); } else if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("(([/?#].*)?)->"))) { rtl::OUString aReversePrefix; if (!(scanStringLiteral(&p, pEnd, &aReversePrefix) && matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1")) && p == pEnd)) throw lang::IllegalArgumentException(); return Regexp(Regexp::KIND_AUTHORITY, aPrefix, false, rtl::OUString(), true, aReversePrefix); } else { bool bOpen = false; if (p != pEnd && *p == '(') { ++p; bOpen = true; } if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("[^/?#]"))) throw lang::IllegalArgumentException(); if (p == pEnd || *p != '*' && *p != '+') throw lang::IllegalArgumentException(); bool bEmptyDomain = *p++ == '*'; rtl::OUString aInfix; scanStringLiteral(&p, pEnd, &aInfix); if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("([/?#].*)?"))) throw lang::IllegalArgumentException(); rtl::OUString aReversePrefix; if (bOpen && !(matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM(")->")) && scanStringLiteral(&p, pEnd, &aReversePrefix) && matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1")))) throw lang::IllegalArgumentException(); if (p != pEnd) throw lang::IllegalArgumentException(); return Regexp(Regexp::KIND_DOMAIN, aPrefix, bEmptyDomain, aInfix, bOpen, aReversePrefix); } throw lang::IllegalArgumentException(); } <commit_msg>INTEGRATION: CWS warnings01 (1.4.10); FILE MERGED 2005/11/09 21:01:42 sb 1.4.10.1: #i53898# Made code warning-free.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: regexp.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-20 05:17:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _UCB_REGEXP_HXX_ #include <regexp.hxx> #endif #include <cstddef> #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _VOS_DIAGNOSE_H_ #include <vos/diagnose.hxx> #endif namespace unnamed_ucb_regexp {} using namespace unnamed_ucb_regexp; // unnamed namespaces don't work well yet... using namespace com::sun::star; using namespace ucb; //============================================================================ // // Regexp // //============================================================================ inline Regexp::Regexp(Kind eTheKind, rtl::OUString const & rThePrefix, bool bTheEmptyDomain, rtl::OUString const & rTheInfix, bool bTheTranslation, rtl::OUString const & rTheReversePrefix): m_eKind(eTheKind), m_aPrefix(rThePrefix), m_aInfix(rTheInfix), m_aReversePrefix(rTheReversePrefix), m_bEmptyDomain(bTheEmptyDomain), m_bTranslation(bTheTranslation) { VOS_ASSERT(m_eKind == KIND_DOMAIN || !m_bEmptyDomain && m_aInfix.getLength() == 0); VOS_ASSERT(m_bTranslation || m_aReversePrefix.getLength() == 0); } //============================================================================ namespace unnamed_ucb_regexp { bool matchStringIgnoreCase(sal_Unicode const ** pBegin, sal_Unicode const * pEnd, rtl::OUString const & rString) { sal_Unicode const * p = *pBegin; sal_Unicode const * q = rString.getStr(); sal_Unicode const * qEnd = q + rString.getLength(); if (pEnd - p < qEnd - q) return false; while (q != qEnd) { sal_Unicode c1 = *p++; sal_Unicode c2 = *q++; if (c1 >= 'a' && c1 <= 'z') c1 -= 'a' - 'A'; if (c2 >= 'a' && c2 <= 'z') c2 -= 'a' - 'A'; if (c1 != c2) return false; } *pBegin = p; return true; } } bool Regexp::matches(rtl::OUString const & rString, rtl::OUString * pTranslation, bool * pTranslated) const { sal_Unicode const * pBegin = rString.getStr(); sal_Unicode const * pEnd = pBegin + rString.getLength(); bool bMatches = false; sal_Unicode const * p = pBegin; if (matchStringIgnoreCase(&p, pEnd, m_aPrefix)) { sal_Unicode const * pBlock1Begin = p; sal_Unicode const * pBlock1End = pEnd; sal_Unicode const * pBlock2Begin = 0; sal_Unicode const * pBlock2End = 0; switch (m_eKind) { case KIND_PREFIX: bMatches = true; break; case KIND_AUTHORITY: bMatches = p == pEnd || *p == '/' || *p == '?' || *p == '#'; break; case KIND_DOMAIN: if (!m_bEmptyDomain) { if (p == pEnd || *p == '/' || *p == '?' || *p == '#') break; ++p; } for (;;) { sal_Unicode const * q = p; if (matchStringIgnoreCase(&q, pEnd, m_aInfix) && (q == pEnd || *q == '/' || *q == '?' || *q == '#')) { bMatches = true; pBlock1End = p; pBlock2Begin = q; pBlock2End = pEnd; break; } if (p == pEnd) break; sal_Unicode c = *p++; if (c == '/' || c == '?' || c == '#') break; } break; } if (bMatches) if (m_bTranslation) { if (pTranslation) { rtl::OUStringBuffer aBuffer(m_aReversePrefix); aBuffer.append(pBlock1Begin, pBlock1End - pBlock1Begin); aBuffer.append(m_aInfix); aBuffer.append(pBlock2Begin, pBlock2End - pBlock2Begin); *pTranslation = aBuffer.makeStringAndClear(); } if (pTranslated) *pTranslated = true; } else { if (pTranslation) *pTranslation = rString; if (pTranslated) *pTranslated = false; } } return bMatches; } //============================================================================ namespace unnamed_ucb_regexp { inline bool isAlpha(sal_Unicode c) { return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'; } inline bool isDigit(sal_Unicode c) { return c >= '0' && c <= '9'; } bool isScheme(rtl::OUString const & rString, bool bColon) { // Return true if rString matches <scheme> (plus a trailing ":" if bColon // is true) from RFC 2396: sal_Unicode const * p = rString.getStr(); sal_Unicode const * pEnd = p + rString.getLength(); if (p != pEnd && isAlpha(*p)) for (++p;;) { if (p == pEnd) return !bColon; sal_Unicode c = *p++; if (!(isAlpha(c) || isDigit(c) || c == '+' || c == '-' || c == '.')) return bColon && c == ':' && p == pEnd; } return false; } void appendStringLiteral(rtl::OUStringBuffer * pBuffer, rtl::OUString const & rString) { VOS_ASSERT(pBuffer); pBuffer->append(sal_Unicode('"')); sal_Unicode const * p = rString.getStr(); sal_Unicode const * pEnd = p + rString.getLength(); while (p != pEnd) { sal_Unicode c = *p++; if (c == '"' || c == '\\') pBuffer->append(sal_Unicode('\\')); pBuffer->append(c); } pBuffer->append(sal_Unicode('"')); } } rtl::OUString Regexp::getRegexp(bool bReverse) const { if (m_bTranslation) { rtl::OUStringBuffer aBuffer; if (bReverse) { if (m_aReversePrefix.getLength() != 0) appendStringLiteral(&aBuffer, m_aReversePrefix); } else { if (m_aPrefix.getLength() != 0) appendStringLiteral(&aBuffer, m_aPrefix); } switch (m_eKind) { case KIND_PREFIX: aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("(.*)")); break; case KIND_AUTHORITY: aBuffer. appendAscii(RTL_CONSTASCII_STRINGPARAM("(([/?#].*)?)")); break; case KIND_DOMAIN: aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([^/?#]")); aBuffer.append(sal_Unicode(m_bEmptyDomain ? '*' : '+')); if (m_aInfix.getLength() != 0) appendStringLiteral(&aBuffer, m_aInfix); aBuffer. appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?)")); break; } aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("->")); if (bReverse) { if (m_aPrefix.getLength() != 0) appendStringLiteral(&aBuffer, m_aPrefix); } else { if (m_aReversePrefix.getLength() != 0) appendStringLiteral(&aBuffer, m_aReversePrefix); } aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("\\1")); return aBuffer.makeStringAndClear(); } else if (m_eKind == KIND_PREFIX && isScheme(m_aPrefix, true)) return m_aPrefix.copy(0, m_aPrefix.getLength() - 1); else { rtl::OUStringBuffer aBuffer; if (m_aPrefix.getLength() != 0) appendStringLiteral(&aBuffer, m_aPrefix); switch (m_eKind) { case KIND_PREFIX: aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM(".*")); break; case KIND_AUTHORITY: aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?")); break; case KIND_DOMAIN: aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("[^/?#]")); aBuffer.append(sal_Unicode(m_bEmptyDomain ? '*' : '+')); if (m_aInfix.getLength() != 0) appendStringLiteral(&aBuffer, m_aInfix); aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?")); break; } return aBuffer.makeStringAndClear(); } } //============================================================================ namespace unnamed_ucb_regexp { bool matchString(sal_Unicode const ** pBegin, sal_Unicode const * pEnd, sal_Char const * pString, size_t nStringLength) { sal_Unicode const * p = *pBegin; sal_uChar const * q = reinterpret_cast< sal_uChar const * >(pString); sal_uChar const * qEnd = q + nStringLength; if (pEnd - p < qEnd - q) return false; while (q != qEnd) { sal_Unicode c1 = *p++; sal_Unicode c2 = *q++; if (c1 != c2) return false; } *pBegin = p; return true; } bool scanStringLiteral(sal_Unicode const ** pBegin, sal_Unicode const * pEnd, rtl::OUString * pString) { sal_Unicode const * p = *pBegin; if (p == pEnd || *p++ != '"') return false; rtl::OUStringBuffer aBuffer; for (;;) { if (p == pEnd) return false; sal_Unicode c = *p++; if (c == '"') break; if (c == '\\') { if (p == pEnd) return false; c = *p++; if (c != '"' && c != '\\') return false; } aBuffer.append(c); } *pBegin = p; *pString = aBuffer.makeStringAndClear(); return true; } } Regexp Regexp::parse(rtl::OUString const & rRegexp) { // Detect an input of '<scheme>' as an abbreviation of '"<scheme>:".*' // where <scheme> is as defined in RFC 2396: if (isScheme(rRegexp, false)) return Regexp(Regexp::KIND_PREFIX, rRegexp + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(":")), false, rtl::OUString(), false, rtl::OUString()); sal_Unicode const * p = rRegexp.getStr(); sal_Unicode const * pEnd = p + rRegexp.getLength(); rtl::OUString aPrefix; scanStringLiteral(&p, pEnd, &aPrefix); if (p == pEnd) throw lang::IllegalArgumentException(); if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM(".*"))) { if (p != pEnd) throw lang::IllegalArgumentException(); return Regexp(Regexp::KIND_PREFIX, aPrefix, false, rtl::OUString(), false, rtl::OUString()); } else if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("(.*)->"))) { rtl::OUString aReversePrefix; scanStringLiteral(&p, pEnd, &aReversePrefix); if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1")) || p != pEnd) throw lang::IllegalArgumentException(); return Regexp(Regexp::KIND_PREFIX, aPrefix, false, rtl::OUString(), true, aReversePrefix); } else if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("([/?#].*)?"))) { if (p != pEnd) throw lang::IllegalArgumentException(); return Regexp(Regexp::KIND_AUTHORITY, aPrefix, false, rtl::OUString(), false, rtl::OUString()); } else if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("(([/?#].*)?)->"))) { rtl::OUString aReversePrefix; if (!(scanStringLiteral(&p, pEnd, &aReversePrefix) && matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1")) && p == pEnd)) throw lang::IllegalArgumentException(); return Regexp(Regexp::KIND_AUTHORITY, aPrefix, false, rtl::OUString(), true, aReversePrefix); } else { bool bOpen = false; if (p != pEnd && *p == '(') { ++p; bOpen = true; } if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("[^/?#]"))) throw lang::IllegalArgumentException(); if (p == pEnd || *p != '*' && *p != '+') throw lang::IllegalArgumentException(); bool bEmptyDomain = *p++ == '*'; rtl::OUString aInfix; scanStringLiteral(&p, pEnd, &aInfix); if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("([/?#].*)?"))) throw lang::IllegalArgumentException(); rtl::OUString aReversePrefix; if (bOpen && !(matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM(")->")) && scanStringLiteral(&p, pEnd, &aReversePrefix) && matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1")))) throw lang::IllegalArgumentException(); if (p != pEnd) throw lang::IllegalArgumentException(); return Regexp(Regexp::KIND_DOMAIN, aPrefix, bEmptyDomain, aInfix, bOpen, aReversePrefix); } } <|endoftext|>
<commit_before>#include <string.h> #include <Wire.h> #include "MPU6050.h" #include "nt.h" int main(void) { tNTBusGetImuData imuData; memset(&imuData, 0, sizeof(imuData)); imuData.ImuStatus = NTBUS_IMU_IMUSTATUS_BASE | NTBUS_IMU_IMUSTATUS_GYRODATA_OK | NTBUS_IMU_IMUSTATUS_ACCDATA_OK; Wire.begin(); MPU6050 imu = MPU6050(); imu.initialize(); imu.setClockSource(MPU6050_CLOCK_PLL_ZGYRO); imu.setFullScaleGyroRange(MPU6050_GYRO_FS_1000); imu.setExternalFrameSync(MPU6050_EXT_SYNC_DISABLED); imu.setDLPFMode(MPU6050_DLPF_BW_256); imu.setRate(0); // sample at full speed NtNodeImu ntNode = NtNodeImu::getNodeWithNtBuffer(NTBUS_ID_IMU1, "ArduNT IMU", &imuData, NTBUS_IMU_CONFIG_MPU6000); for (;;) { imu.getMotion6(&imuData.AccX, &imuData.AccY, &imuData.AccZ, &imuData.GyroX, &imuData.GyroY, &imuData.GyroZ); imuData.Temp = imu.getTemperature(); uint8_t recv; ntNode.processBusData(&recv); } sei(); return 0; } <commit_msg>Interrupts start before starting I2C library.<commit_after>#include <string.h> #include <Wire.h> #include "MPU6050.h" #include "nt.h" int main(void) { tNTBusGetImuData imuData; memset(&imuData, 0, sizeof(imuData)); imuData.ImuStatus = NTBUS_IMU_IMUSTATUS_BASE | NTBUS_IMU_IMUSTATUS_GYRODATA_OK | NTBUS_IMU_IMUSTATUS_ACCDATA_OK; sei(); Wire.begin(); MPU6050 imu = MPU6050(); imu.initialize(); imu.setClockSource(MPU6050_CLOCK_PLL_ZGYRO); imu.setFullScaleGyroRange(MPU6050_GYRO_FS_1000); imu.setExternalFrameSync(MPU6050_EXT_SYNC_DISABLED); imu.setDLPFMode(MPU6050_DLPF_BW_256); imu.setRate(0); // sample at full speed NtNodeImu ntNode = NtNodeImu::getNodeWithNtBuffer(NTBUS_ID_IMU1, "ArduNT IMU", &imuData, NTBUS_IMU_CONFIG_MPU6000); for (;;) { imu.getMotion6(&imuData.AccX, &imuData.AccY, &imuData.AccZ, &imuData.GyroX, &imuData.GyroY, &imuData.GyroZ); imuData.Temp = imu.getTemperature(); uint8_t recv; ntNode.processBusData(&recv); } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) ICG. All rights reserved. * * Institute for Computer Graphics and Vision * Graz University of Technology / Austria * * * 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. * * * Project : ImageUtilities * Module : Core * Class : ImagePyramid * Language : C++ * Description : Implementation of multiresolution imagepyramid * * Author : Manuel Werlberger * EMail : [email protected] * */ #include <math.h> #include "coredefs.h" #include "memorydefs.h" #include "iutransform/reduce.h" #include "copy.h" #include "imagepyramid.h" namespace iu { //--------------------------------------------------------------------------- ImagePyramid::ImagePyramid() : images_(0), pixel_type_(IU_UNKNOWN_PIXEL_TYPE), scale_factors_(0), num_levels_(0), max_num_levels_(0), scale_factor_(0.0f), size_bound_(0) { } //--------------------------------------------------------------------------- ImagePyramid::ImagePyramid(unsigned int& max_num_levels, const IuSize& size, const float& scale_factor, unsigned int size_bound) : images_(0), pixel_type_(IU_UNKNOWN_PIXEL_TYPE), scale_factors_(0), num_levels_(0), max_num_levels_(0), scale_factor_(0.0f), size_bound_(0) { max_num_levels = this->init(max_num_levels, size, scale_factor, size_bound); printf("max_num_levels = %d, num_levels_ = %d\n", max_num_levels, num_levels_); } //--------------------------------------------------------------------------- ImagePyramid::~ImagePyramid() { this->reset(); } //--------------------------------------------------------------------------- unsigned int ImagePyramid::init(unsigned int max_num_levels, const IuSize& size, const float& scale_factor, unsigned int size_bound) { if ((scale_factor <= 0) || (scale_factor >=1)) { fprintf(stderr, "ImagePyramid::init: scale_factor must be in the interval (0,1). Init failed."); return 0; } if (images_ != 0) this->reset(); max_num_levels_ = IUMAX(1u, max_num_levels); num_levels_ = max_num_levels_; size_bound_ = IUMAX(1u, size_bound); // calculate the maximum number of levels unsigned int shorter_side = (size.width<size.height) ? size.width : size.height; float ratio = static_cast<float>(shorter_side)/static_cast<float>(size_bound_); // +1 because the original size is level 0 unsigned int possible_num_levels = static_cast<int>( -logf(ratio)/logf(scale_factor)) + 1; if(num_levels_ > possible_num_levels) num_levels_ = possible_num_levels; // init rate for each level scale_factors_ = new float[num_levels_]; for (unsigned int i=0; i<num_levels_; i++) { scale_factors_[i] = pow(scale_factor, static_cast<float>(i)); printf("scale_factors[%d]=%f\n", i, scale_factors_[i]); } return num_levels_; } //--------------------------------------------------------------------------- /** Resets the image pyramid. Deletes all the data. */ void ImagePyramid::reset() { printf("reset\n"); if(images_ != 0) { printf("delete images[i]\n"); // delete all arrays and hold elements! for (unsigned int i=0; i<num_levels_; i++) { delete(images_[i]); images_[i] = 0; } } delete[] images_; images_ = 0; pixel_type_ = IU_UNKNOWN_PIXEL_TYPE; delete[] scale_factors_; scale_factors_ = 0; num_levels_ = 0; } //--------------------------------------------------------------------------- unsigned int ImagePyramid::setImage(iu::Image* image, IuInterpolationType interp_type) { if (image == 0) { fprintf(stderr, "ImagePyramid::setImage: input image is 0."); return 0; } if (!image->onDevice()) { fprintf(stderr, "ImagePyramid::setImage: currently only device images supported."); return 0; } if ((images_ != 0) && ( (images_[0]->size() != image->size()) || (images_[0]->pixelType() != image->pixelType()) )) { this->reset(); this->init(max_num_levels_, image->size(), scale_factor_, size_bound_); } pixel_type_ = image->pixelType(); printf("ImagePyramid::setImage: image pixel_type = %d\n", image->pixelType()); printf("ImagePyramid::setImage: pyr pixel_type = %d\n", pixel_type_); printf("ImagePyramid::setImage: pyr pixel_type = %d\n", this->pixelType()); switch (pixel_type_) { case IU_32F_C1: { printf("32f_C1\n"); printf("images=%p\n", images_); iu::ImageGpu_32f_C1** cur_images = 0; printf("cur_images=%p\n", cur_images); if (images_ == 0) { printf("create array\n"); cur_images = new iu::ImageGpu_32f_C1*[num_levels_]; } else cur_images = reinterpret_cast<iu::ImageGpu_32f_C1**>(images_); images_ = reinterpret_cast<iu::Image**>(cur_images); printf("cur_images=%p\n", cur_images); printf("images=%p\n", images_); cur_images[0] = new iu::ImageGpu_32f_C1(image->size()); iuprivate::copy(reinterpret_cast<iu::ImageGpu_32f_C1*>(image), cur_images[0]); printf("1\n"); for (unsigned int i=1; i<num_levels_; i++) { IuSize sz(static_cast<int>(floor(0.5+static_cast<double>(image->width())*static_cast<double>(scale_factors_[i]))), static_cast<int>(floor(0.5+static_cast<double>(image->height())*static_cast<double>(scale_factors_[i])))); printf("i=%d: sz=%d/%d\n", i, sz.width, sz.height); cur_images[i] = new iu::ImageGpu_32f_C1(sz); iuprivate::reduce(reinterpret_cast<iu::ImageGpu_32f_C1*>(cur_images[i-1]), reinterpret_cast<iu::ImageGpu_32f_C1*>(cur_images[i]), interp_type, 1, 0); } printf("2\n"); break; } default: fprintf(stderr, "ImagePyramid::setImage: unsupported pixel type (currently only 32F_C1 supported)\n"); return 0; } return num_levels_; } } // namespace iu <commit_msg><commit_after>/* * Copyright (c) ICG. All rights reserved. * * Institute for Computer Graphics and Vision * Graz University of Technology / Austria * * * 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. * * * Project : ImageUtilities * Module : Core * Class : ImagePyramid * Language : C++ * Description : Implementation of multiresolution imagepyramid * * Author : Manuel Werlberger * EMail : [email protected] * */ #include <math.h> #include "coredefs.h" #include "memorydefs.h" #include "iutransform/reduce.h" #include "copy.h" #include "imagepyramid.h" namespace iu { //--------------------------------------------------------------------------- ImagePyramid::ImagePyramid() : images_(0), pixel_type_(IU_UNKNOWN_PIXEL_TYPE), scale_factors_(0), num_levels_(0), max_num_levels_(0), scale_factor_(0.0f), size_bound_(0) { } //--------------------------------------------------------------------------- ImagePyramid::ImagePyramid(unsigned int& max_num_levels, const IuSize& size, const float& scale_factor, unsigned int size_bound) : images_(0), pixel_type_(IU_UNKNOWN_PIXEL_TYPE), scale_factors_(0), num_levels_(0), max_num_levels_(0), scale_factor_(0.0f), size_bound_(0) { max_num_levels = this->init(max_num_levels, size, scale_factor, size_bound); printf("max_num_levels = %d, num_levels_ = %d\n", max_num_levels, num_levels_); } //--------------------------------------------------------------------------- ImagePyramid::~ImagePyramid() { this->reset(); } //--------------------------------------------------------------------------- unsigned int ImagePyramid::init(unsigned int max_num_levels, const IuSize& size, const float& scale_factor, unsigned int size_bound) { if ((scale_factor <= 0) || (scale_factor >=1)) { fprintf(stderr, "ImagePyramid::init: scale_factor must be in the interval (0,1). Init failed."); return 0; } if (images_ != 0) this->reset(); max_num_levels_ = IUMAX(1u, max_num_levels); num_levels_ = max_num_levels_; size_bound_ = IUMAX(1u, size_bound); // calculate the maximum number of levels unsigned int shorter_side = (size.width<size.height) ? size.width : size.height; float ratio = static_cast<float>(shorter_side)/static_cast<float>(size_bound_); // +1 because the original size is level 0 unsigned int possible_num_levels = static_cast<int>( -logf(ratio)/logf(scale_factor)) + 1; if(num_levels_ > possible_num_levels) num_levels_ = possible_num_levels; // init rate for each level scale_factors_ = new float[num_levels_]; for (unsigned int i=0; i<num_levels_; i++) { scale_factors_[i] = pow(scale_factor, static_cast<float>(i)); printf("scale_factors[%d]=%f\n", i, scale_factors_[i]); } return num_levels_; } //--------------------------------------------------------------------------- /** Resets the image pyramid. Deletes all the data. */ void ImagePyramid::reset() { printf("reset\n"); if(images_ != 0) { printf("delete images[i]\n"); // delete all arrays and hold elements! for (unsigned int i=0; i<num_levels_; i++) { delete(images_[i]); images_[i] = 0; } } delete[] images_; images_ = 0; pixel_type_ = IU_UNKNOWN_PIXEL_TYPE; delete[] scale_factors_; scale_factors_ = 0; num_levels_ = 0; } //--------------------------------------------------------------------------- unsigned int ImagePyramid::setImage(iu::Image* image, IuInterpolationType interp_type) { if (image == 0) { fprintf(stderr, "ImagePyramid::setImage: input image is 0."); return 0; } if (!image->onDevice()) { fprintf(stderr, "ImagePyramid::setImage: currently only device images supported."); return 0; } if ((images_ != 0) && ( (images_[0]->size() != image->size()) || (images_[0]->pixelType() != image->pixelType()) )) { this->reset(); this->init(max_num_levels_, image->size(), scale_factor_, size_bound_); } pixel_type_ = image->pixelType(); printf("ImagePyramid::setImage: image pixel_type = %d\n", image->pixelType()); printf("ImagePyramid::setImage: pyr pixel_type = %d\n", pixel_type_); printf("ImagePyramid::setImage: pyr pixel_type = %d\n", this->pixelType()); switch (pixel_type_) { case IU_32F_C1: { printf("32f_C1\n"); printf("images=%p\n", images_); iu::ImageGpu_32f_C1*** cur_images = reinterpret_cast<iu::ImageGpu_32f_C1***>(&images_); // *** needed so that always the same mem is used. printf("cur_images=%p\n", *cur_images); if (images_ == 0) { printf("create array\n"); (*cur_images) = new iu::ImageGpu_32f_C1*[num_levels_]; for (unsigned int i=0; i<num_levels_; i++) { IuSize sz(static_cast<int>(floor(0.5+static_cast<double>(image->width())*static_cast<double>(scale_factors_[i]))), static_cast<int>(floor(0.5+static_cast<double>(image->height())*static_cast<double>(scale_factors_[i])))); printf("i=%d: sz=%d/%d\n", i, sz.width, sz.height); (*cur_images)[i] = new iu::ImageGpu_32f_C1(sz); } } printf("cur_images=%p\n", (*cur_images)); printf("images=%p\n", images_); printf("i=0: sz=%d/%d\n", image->size().width, image->size().height); iuprivate::copy(reinterpret_cast<iu::ImageGpu_32f_C1*>(image), (*cur_images)[0]); for (unsigned int i=1; i<num_levels_; i++) { printf("i=%d, reduction\n", i); iuprivate::reduce((*cur_images)[i-1], (*cur_images)[i], interp_type, 1, 0); } printf("2\n"); break; } default: fprintf(stderr, "ImagePyramid::setImage: unsupported pixel type (currently only 32F_C1 supported)\n"); return 0; } return num_levels_; } } // namespace iu <|endoftext|>
<commit_before>/* Copyright (c) 2017 Maksim Galkin This file is subject to the terms and conditions of the MIT license, distributed with this code package in the LICENSE file, also available at: https://github.com/yacoder/allo-cpp/blob/master/LICENSE */ #pragma once #include "allo_private_allocator.hpp" #include "allocation_strategies/allo_never_look_back_strategy.hpp" namespace allo { template <typename T, typename TInnerAllocator = std::allocator> using never_look_back_allocator = private_allocator<T, strategies::never_look_back_strategy, TInnerAllocator>; } // namespace allo <commit_msg>Fix a build problem on OS X, wrong template syntax in never_look_back_allocator<commit_after>/* Copyright (c) 2017 Maksim Galkin This file is subject to the terms and conditions of the MIT license, distributed with this code package in the LICENSE file, also available at: https://github.com/yacoder/allo-cpp/blob/master/LICENSE */ #pragma once #include "allo_private_allocator.hpp" #include "allocation_strategies/allo_never_look_back_strategy.hpp" namespace allo { template <typename T, typename TInnerAllocator = std::allocator<T>> using never_look_back_allocator = private_allocator<T, strategies::never_look_back_strategy, TInnerAllocator>; } // namespace allo <|endoftext|>
<commit_before>//@author A0097630B #include "stdafx.h" #include "../internal/test_helpers.h" #include "internal/query_executor.h" #include "internal/query_executor_builder_visitor.h" #include "../mocks/task_list.h" #include "../mocks/query.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace Controller { namespace Internal { namespace UnitTests { namespace Mocks { using namespace You::Controller::UnitTests::Mocks; // NOLINT } TEST_CLASS(QueryExecutorBuilderVisitorTests) { TEST_METHOD(getsCorrectTypeForAddQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::ADD_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); ADD_RESULT result( boost::get<ADD_RESULT>(executor->execute())); Assert::AreEqual( Mocks::Queries::ADD_QUERY.description, result.task.getDescription() ); Assert::AreEqual( Mocks::Queries::ADD_QUERY.due.get(), result.task.getDeadline() ); You::NLP::ADD_QUERY queryWithoutDeadline(Mocks::Queries::ADD_QUERY); queryWithoutDeadline.due = You::Utils::Option<boost::posix_time::ptime>(); query = queryWithoutDeadline; executor = boost::apply_visitor(visitor, query); result = boost::get<ADD_RESULT>(executor->execute()); Assert::AreEqual( Mocks::Queries::ADD_QUERY.description, result.task.getDescription() ); } TEST_METHOD(getsCorrectTypeForEditQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::EDIT_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); EDIT_RESULT result( boost::get<EDIT_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task); You::NLP::EDIT_QUERY queryWithoutDeadline(Mocks::Queries::EDIT_QUERY); queryWithoutDeadline.due = You::Utils::Option<boost::posix_time::ptime>(); query = queryWithoutDeadline; executor = boost::apply_visitor(visitor, query); result = boost::get<EDIT_RESULT>(executor->execute()); Assert::AreEqual(taskList.front().getID(), result.task); } TEST_METHOD(getsCorrectTypeForDeleteQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::DELETE_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); DELETE_RESULT result( boost::get<DELETE_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task); } }; } // namespace UnitTests } // namespace Internal } // namespace Controller } // namespace You <commit_msg>Test not updating the description of a task.<commit_after>//@author A0097630B #include "stdafx.h" #include "../internal/test_helpers.h" #include "internal/query_executor.h" #include "internal/query_executor_builder_visitor.h" #include "../mocks/task_list.h" #include "../mocks/query.h" using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert; namespace You { namespace Controller { namespace Internal { namespace UnitTests { namespace Mocks { using namespace You::Controller::UnitTests::Mocks; // NOLINT } TEST_CLASS(QueryExecutorBuilderVisitorTests) { TEST_METHOD(getsCorrectTypeForAddQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::ADD_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); ADD_RESULT result( boost::get<ADD_RESULT>(executor->execute())); Assert::AreEqual( Mocks::Queries::ADD_QUERY.description, result.task.getDescription() ); Assert::AreEqual( Mocks::Queries::ADD_QUERY.due.get(), result.task.getDeadline() ); You::NLP::ADD_QUERY queryWithoutDeadline(Mocks::Queries::ADD_QUERY); queryWithoutDeadline.due = You::Utils::Option<boost::posix_time::ptime>(); query = queryWithoutDeadline; executor = boost::apply_visitor(visitor, query); result = boost::get<ADD_RESULT>(executor->execute()); Assert::AreEqual( Mocks::Queries::ADD_QUERY.description, result.task.getDescription() ); } TEST_METHOD(getsCorrectTypeForEditQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::EDIT_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); EDIT_RESULT result( boost::get<EDIT_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task); You::NLP::EDIT_QUERY queryWithoutDeadline(Mocks::Queries::EDIT_QUERY); queryWithoutDeadline.due = You::Utils::Option<boost::posix_time::ptime>(); query = queryWithoutDeadline; executor = boost::apply_visitor(visitor, query); result = boost::get<EDIT_RESULT>(executor->execute()); Assert::AreEqual(taskList.front().getID(), result.task); queryWithoutDeadline = Mocks::Queries::EDIT_QUERY; queryWithoutDeadline.description = You::Utils::Option<std::wstring>(); query = queryWithoutDeadline; executor = boost::apply_visitor(visitor, query); result = boost::get<EDIT_RESULT>(executor->execute()); Assert::AreEqual(taskList.front().getID(), result.task); } TEST_METHOD(getsCorrectTypeForDeleteQueries) { Mocks::TaskList taskList; QueryExecutorBuilderVisitor visitor(taskList); You::NLP::QUERY query(Mocks::Queries::DELETE_QUERY); std::unique_ptr<QueryExecutor> executor( boost::apply_visitor(visitor, query)); DELETE_RESULT result( boost::get<DELETE_RESULT>(executor->execute())); Assert::AreEqual(taskList.front().getID(), result.task); } }; } // namespace UnitTests } // namespace Internal } // namespace Controller } // namespace You <|endoftext|>
<commit_before>#include "realm/array_integer.hpp" #include "realm/column.hpp" #include <vector> using namespace realm; // Find max and min value, but break search if difference exceeds 'maxdiff' (in which case *min and *max is set to 0) // Useful for counting-sort functions template <size_t w> bool ArrayInteger::minmax(size_t from, size_t to, uint64_t maxdiff, int64_t *min, int64_t *max) const { int64_t min2; int64_t max2; size_t t; max2 = Array::get<w>(from); min2 = max2; for (t = from + 1; t < to; t++) { int64_t v = Array::get<w>(t); // Utilizes that range test is only needed if max2 or min2 were changed if (v < min2) { min2 = v; if (uint64_t(max2 - min2) > maxdiff) break; } else if (v > max2) { max2 = v; if (uint64_t(max2 - min2) > maxdiff) break; } } if (t < to) { *max = 0; *min = 0; return false; } else { *max = max2; *min = min2; return true; } } std::vector<int64_t> ArrayInteger::ToVector() const { std::vector<int64_t> v; const size_t count = size(); for (size_t t = 0; t < count; ++t) v.push_back(Array::get(t)); return v; } MemRef ArrayIntNull::create_array(Type type, bool context_flag, std::size_t size, int_fast64_t value, Allocator& alloc) { MemRef r = Array::create(type, context_flag, wtype_Bits, size + 1, value, alloc); ArrayIntNull arr(alloc); arr.Array::init_from_mem(r); if (arr.m_width == 64) { int_fast64_t null_value = value ^ 1; // Just anything different from value. arr.Array::set(0, null_value); } else { arr.Array::set(0, arr.m_ubound); } return r; } void ArrayIntNull::init_from_ref(ref_type ref) REALM_NOEXCEPT { REALM_ASSERT_DEBUG(ref); char* header = m_alloc.translate(ref); init_from_mem(MemRef{header, ref}); } void ArrayIntNull::init_from_mem(MemRef mem) REALM_NOEXCEPT { Array::init_from_mem(mem); if (m_size == 0) { // This can only happen when mem is being reused from another // array (which happens when shrinking the B+tree), so we need // to add the "magic" null value to the beginning. // Since init_* functions are noexcept, but insert() isn't, we // need to ensure that insert() will not allocate. REALM_ASSERT(m_capacity != 0); Array::insert(0, m_ubound); } } void ArrayIntNull::init_from_parent() REALM_NOEXCEPT { init_from_ref(get_ref_from_parent()); } namespace { int64_t next_null_candidate(int64_t previous_candidate) { uint64_t x = static_cast<uint64_t>(previous_candidate); // Increment by a prime number. This guarantees that we will // eventually hit every possible integer in the 2^64 range. x += 0xfffffffbULL; return static_cast<int64_t>(x); } } int_fast64_t ArrayIntNull::choose_random_null(int64_t incoming) { // We just need any number -- it could have been `rand()`, but // random numbers are hard, and we don't want to risk locking mutices // or saving state. The top of the stack should be "random enough". int64_t candidate = reinterpret_cast<int64_t>(&candidate); while (true) { candidate = next_null_candidate(candidate); if (candidate == incoming) { continue; } if (can_use_as_null(candidate)) { return candidate; } } } bool ArrayIntNull::can_use_as_null(int64_t candidate) { return find_first(candidate) == npos; } void ArrayIntNull::replace_nulls_with(int64_t new_null) { int64_t old_null = Array::get(0); Array::set(0, new_null); std::size_t i = 1; while (true) { std::size_t found = Array::find_first(old_null, i); if (found < Array::size()) { Array::set(found, new_null); i = found + 1; } else { break; } } } void ArrayIntNull::ensure_not_null(int64_t value) { if (m_width == 64) { if (value == null_value()) { int_fast64_t new_null = choose_random_null(value); replace_nulls_with(new_null); } } else { if (value <= m_lbound || value >= m_ubound) { size_t new_width = bit_width(value); int64_t new_upper_bound = Array::ubound_for_width(new_width); // We're using upper bound as magic NULL value, so we have to check // explicitly that the incoming value doesn't happen to be the new // NULL value. If it is, we upgrade one step further. if (new_width < 64 && value == new_upper_bound) { new_width = (new_width == 0 ? 1 : new_width * 2); new_upper_bound = Array::ubound_for_width(new_width); } int64_t new_null; if (new_width == 64) { // Width will be upgraded to 64, so we need to pick a random NULL. new_null = choose_random_null(value); } else { new_null = new_upper_bound; } replace_nulls_with(new_null); // Expands array } } } void ArrayIntNull::find_all(Column* result, int64_t value, std::size_t col_offset, std::size_t begin, std::size_t end) const { // FIXME: We can't use the fast Array::find_all here, because it would put the wrong indices // in the result column. Since find_all may be invoked many times for different leaves in the // B+tree with the same result column, we also can't simply adjust indices after finding them // (because then the first indices would be adjusted multiple times for each subsequent leaf) if (end == npos) { end = size(); } for (size_t i = begin; i < end; ++i) { if (get(i) == value) { result->add(col_offset + i); } } } namespace { // FIXME: Move this logic to BpTree. struct ArrayIntNullLeafInserter { template <class T> static ref_type leaf_insert(Allocator& alloc, ArrayIntNull& self, std::size_t ndx, T value, Array::TreeInsertBase& state) { size_t leaf_size = self.size(); REALM_ASSERT_DEBUG(leaf_size <= REALM_MAX_BPNODE_SIZE); if (leaf_size < ndx) ndx = leaf_size; if (REALM_LIKELY(leaf_size < REALM_MAX_BPNODE_SIZE)) { self.insert(ndx, value); // Throws return 0; // Leaf was not split } // Split leaf node ArrayIntNull new_leaf(alloc); new_leaf.create(Array::type_Normal); // Throws if (ndx == leaf_size) { new_leaf.add(value); // Throws state.m_split_offset = ndx; } else { for (size_t i = ndx; i != leaf_size; ++i) { if (self.is_null(i)) { new_leaf.add(null{}); // Throws } else { new_leaf.add(self.get(i)); // Throws } } self.truncate(ndx); // Throws self.add(value); // Throws state.m_split_offset = ndx + 1; } state.m_split_size = leaf_size + 1; return new_leaf.get_ref(); } }; } // anonymous namespace ref_type ArrayIntNull::bptree_leaf_insert(std::size_t ndx, int64_t value, Array::TreeInsertBase& state) { return ArrayIntNullLeafInserter::leaf_insert(get_alloc(), *this, ndx, value, state); } ref_type ArrayIntNull::bptree_leaf_insert(std::size_t ndx, null, Array::TreeInsertBase& state) { return ArrayIntNullLeafInserter::leaf_insert(get_alloc(), *this, ndx, null{}, state); } MemRef ArrayIntNull::slice(std::size_t offset, std::size_t size, Allocator& target_alloc) const { // NOTE: It would be nice to consolidate this with Array::slice somehow. REALM_ASSERT(is_attached()); Array slice(target_alloc); _impl::DeepArrayDestroyGuard dg(&slice); Type type = get_type(); slice.create(type, m_context_flag); // Throws slice.add(null_value()); size_t begin = offset + 1; size_t end = offset + size + 1; for (size_t i = begin; i != end; ++i) { int_fast64_t value = Array::get(i); slice.add(value); // Throws } dg.release(); return slice.get_mem(); } MemRef ArrayIntNull::slice_and_clone_children(size_t offset, size_t size, Allocator& target_alloc) const { // NOTE: It would be nice to consolidate this with Array::slice_and_clone_children somehow. REALM_ASSERT(is_attached()); REALM_ASSERT(!has_refs()); return slice(offset, size, target_alloc); } <commit_msg>use < in loop condition instead of !=<commit_after>#include "realm/array_integer.hpp" #include "realm/column.hpp" #include <vector> using namespace realm; // Find max and min value, but break search if difference exceeds 'maxdiff' (in which case *min and *max is set to 0) // Useful for counting-sort functions template <size_t w> bool ArrayInteger::minmax(size_t from, size_t to, uint64_t maxdiff, int64_t *min, int64_t *max) const { int64_t min2; int64_t max2; size_t t; max2 = Array::get<w>(from); min2 = max2; for (t = from + 1; t < to; t++) { int64_t v = Array::get<w>(t); // Utilizes that range test is only needed if max2 or min2 were changed if (v < min2) { min2 = v; if (uint64_t(max2 - min2) > maxdiff) break; } else if (v > max2) { max2 = v; if (uint64_t(max2 - min2) > maxdiff) break; } } if (t < to) { *max = 0; *min = 0; return false; } else { *max = max2; *min = min2; return true; } } std::vector<int64_t> ArrayInteger::ToVector() const { std::vector<int64_t> v; const size_t count = size(); for (size_t t = 0; t < count; ++t) v.push_back(Array::get(t)); return v; } MemRef ArrayIntNull::create_array(Type type, bool context_flag, std::size_t size, int_fast64_t value, Allocator& alloc) { MemRef r = Array::create(type, context_flag, wtype_Bits, size + 1, value, alloc); ArrayIntNull arr(alloc); arr.Array::init_from_mem(r); if (arr.m_width == 64) { int_fast64_t null_value = value ^ 1; // Just anything different from value. arr.Array::set(0, null_value); } else { arr.Array::set(0, arr.m_ubound); } return r; } void ArrayIntNull::init_from_ref(ref_type ref) REALM_NOEXCEPT { REALM_ASSERT_DEBUG(ref); char* header = m_alloc.translate(ref); init_from_mem(MemRef{header, ref}); } void ArrayIntNull::init_from_mem(MemRef mem) REALM_NOEXCEPT { Array::init_from_mem(mem); if (m_size == 0) { // This can only happen when mem is being reused from another // array (which happens when shrinking the B+tree), so we need // to add the "magic" null value to the beginning. // Since init_* functions are noexcept, but insert() isn't, we // need to ensure that insert() will not allocate. REALM_ASSERT(m_capacity != 0); Array::insert(0, m_ubound); } } void ArrayIntNull::init_from_parent() REALM_NOEXCEPT { init_from_ref(get_ref_from_parent()); } namespace { int64_t next_null_candidate(int64_t previous_candidate) { uint64_t x = static_cast<uint64_t>(previous_candidate); // Increment by a prime number. This guarantees that we will // eventually hit every possible integer in the 2^64 range. x += 0xfffffffbULL; return static_cast<int64_t>(x); } } int_fast64_t ArrayIntNull::choose_random_null(int64_t incoming) { // We just need any number -- it could have been `rand()`, but // random numbers are hard, and we don't want to risk locking mutices // or saving state. The top of the stack should be "random enough". int64_t candidate = reinterpret_cast<int64_t>(&candidate); while (true) { candidate = next_null_candidate(candidate); if (candidate == incoming) { continue; } if (can_use_as_null(candidate)) { return candidate; } } } bool ArrayIntNull::can_use_as_null(int64_t candidate) { return find_first(candidate) == npos; } void ArrayIntNull::replace_nulls_with(int64_t new_null) { int64_t old_null = Array::get(0); Array::set(0, new_null); std::size_t i = 1; while (true) { std::size_t found = Array::find_first(old_null, i); if (found < Array::size()) { Array::set(found, new_null); i = found + 1; } else { break; } } } void ArrayIntNull::ensure_not_null(int64_t value) { if (m_width == 64) { if (value == null_value()) { int_fast64_t new_null = choose_random_null(value); replace_nulls_with(new_null); } } else { if (value <= m_lbound || value >= m_ubound) { size_t new_width = bit_width(value); int64_t new_upper_bound = Array::ubound_for_width(new_width); // We're using upper bound as magic NULL value, so we have to check // explicitly that the incoming value doesn't happen to be the new // NULL value. If it is, we upgrade one step further. if (new_width < 64 && value == new_upper_bound) { new_width = (new_width == 0 ? 1 : new_width * 2); new_upper_bound = Array::ubound_for_width(new_width); } int64_t new_null; if (new_width == 64) { // Width will be upgraded to 64, so we need to pick a random NULL. new_null = choose_random_null(value); } else { new_null = new_upper_bound; } replace_nulls_with(new_null); // Expands array } } } void ArrayIntNull::find_all(Column* result, int64_t value, std::size_t col_offset, std::size_t begin, std::size_t end) const { // FIXME: We can't use the fast Array::find_all here, because it would put the wrong indices // in the result column. Since find_all may be invoked many times for different leaves in the // B+tree with the same result column, we also can't simply adjust indices after finding them // (because then the first indices would be adjusted multiple times for each subsequent leaf) if (end == npos) { end = size(); } for (size_t i = begin; i < end; ++i) { if (get(i) == value) { result->add(col_offset + i); } } } namespace { // FIXME: Move this logic to BpTree. struct ArrayIntNullLeafInserter { template <class T> static ref_type leaf_insert(Allocator& alloc, ArrayIntNull& self, std::size_t ndx, T value, Array::TreeInsertBase& state) { size_t leaf_size = self.size(); REALM_ASSERT_DEBUG(leaf_size <= REALM_MAX_BPNODE_SIZE); if (leaf_size < ndx) ndx = leaf_size; if (REALM_LIKELY(leaf_size < REALM_MAX_BPNODE_SIZE)) { self.insert(ndx, value); // Throws return 0; // Leaf was not split } // Split leaf node ArrayIntNull new_leaf(alloc); new_leaf.create(Array::type_Normal); // Throws if (ndx == leaf_size) { new_leaf.add(value); // Throws state.m_split_offset = ndx; } else { for (size_t i = ndx; i < leaf_size; ++i) { if (self.is_null(i)) { new_leaf.add(null{}); // Throws } else { new_leaf.add(self.get(i)); // Throws } } self.truncate(ndx); // Throws self.add(value); // Throws state.m_split_offset = ndx + 1; } state.m_split_size = leaf_size + 1; return new_leaf.get_ref(); } }; } // anonymous namespace ref_type ArrayIntNull::bptree_leaf_insert(std::size_t ndx, int64_t value, Array::TreeInsertBase& state) { return ArrayIntNullLeafInserter::leaf_insert(get_alloc(), *this, ndx, value, state); } ref_type ArrayIntNull::bptree_leaf_insert(std::size_t ndx, null, Array::TreeInsertBase& state) { return ArrayIntNullLeafInserter::leaf_insert(get_alloc(), *this, ndx, null{}, state); } MemRef ArrayIntNull::slice(std::size_t offset, std::size_t size, Allocator& target_alloc) const { // NOTE: It would be nice to consolidate this with Array::slice somehow. REALM_ASSERT(is_attached()); Array slice(target_alloc); _impl::DeepArrayDestroyGuard dg(&slice); Type type = get_type(); slice.create(type, m_context_flag); // Throws slice.add(null_value()); size_t begin = offset + 1; size_t end = offset + size + 1; for (size_t i = begin; i != end; ++i) { int_fast64_t value = Array::get(i); slice.add(value); // Throws } dg.release(); return slice.get_mem(); } MemRef ArrayIntNull::slice_and_clone_children(size_t offset, size_t size, Allocator& target_alloc) const { // NOTE: It would be nice to consolidate this with Array::slice_and_clone_children somehow. REALM_ASSERT(is_attached()); REALM_ASSERT(!has_refs()); return slice(offset, size, target_alloc); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/utils.hpp> #include <mapnik/projection.hpp> #include <mapnik/scale_denominator.hpp> #ifdef MAPNIK_DEBUG //#include <mapnik/wall_clock_timer.hpp> #endif //stl #include <vector> namespace mapnik { template <typename Processor> class feature_style_processor { struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output, Feature const& f, proj_transform const& prj_trans) : output_(output), f_(f), prj_trans_(prj_trans) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_,prj_trans_); } Processor & output_; Feature const& f_; proj_transform const& prj_trans_; }; public: feature_style_processor(Map const& m) : m_(m) {} void apply() { #ifdef MAPNIK_DEBUG //mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: "); #endif Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); try { projection proj(m_.srs()); // map projection double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic()); #ifdef MAPNIK_DEBUG std::clog << "scale denominator = " << scale_denom << "\n"; #endif std::vector<layer>::const_iterator itr = m_.layers().begin(); std::vector<layer>::const_iterator end = m_.layers().end(); while (itr != end) { if (itr->isVisible(scale_denom)) { apply_to_layer(*itr, p, proj, scale_denom); } ++itr; } } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } p.end_map_processing(m_); } private: void apply_to_layer(layer const& lay, Processor & p, projection const& proj0,double scale_denom) { #ifdef MAPNIK_DEBUG //wall_clock_progress_timer timer(clog, "end layer rendering: "); #endif p.start_layer_processing(lay); boost::shared_ptr<datasource> ds=lay.datasource(); if (ds) { box2d<double> ext = m_.get_buffered_extent(); projection proj1(lay.srs()); proj_transform prj_trans(proj0,proj1); box2d<double> layer_ext = lay.envelope(); double lx0 = layer_ext.minx(); double ly0 = layer_ext.miny(); double lz0 = 0.0; double lx1 = layer_ext.maxx(); double ly1 = layer_ext.maxy(); double lz1 = 0.0; // back project layers extent into main map projection prj_trans.backward(lx0,ly0,lz0); prj_trans.backward(lx1,ly1,lz1); // if no intersection then nothing to do for layer if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() ) { return; } // clip query bbox lx0 = std::max(ext.minx(),lx0); ly0 = std::max(ext.miny(),ly0); lx1 = std::min(ext.maxx(),lx1); ly1 = std::min(ext.maxy(),ly1); prj_trans.forward(lx0,ly0,lz0); prj_trans.forward(lx1,ly1,lz1); box2d<double> bbox(lx0,ly0,lx1,ly1); query::resolution_type res(m_.getWidth()/bbox.width(),m_.getHeight()/bbox.height()); query q(bbox,res,scale_denom); //BBOX query std::vector<std::string> const& style_names = lay.styles(); std::vector<std::string>::const_iterator stylesIter = style_names.begin(); std::vector<std::string>::const_iterator stylesEnd = style_names.end(); for (;stylesIter != stylesEnd; ++stylesIter) { std::set<std::string> names; attribute_collector collector(names); std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; bool active_rules=false; boost::optional<feature_type_style const&> style=m_.find_style(*stylesIter); if (!style) continue; const std::vector<rule_type>& rules=(*style).get_rules(); std::vector<rule_type>::const_iterator ruleIter=rules.begin(); std::vector<rule_type>::const_iterator ruleEnd=rules.end(); for (;ruleIter!=ruleEnd;++ruleIter) { if (ruleIter->active(scale_denom)) { active_rules=true; // collect unique attribute names collector(*ruleIter); if (ruleIter->has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } else { if_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } } } std::set<std::string>::const_iterator namesIter=names.begin(); std::set<std::string>::const_iterator namesEnd =names.end(); // push all property names for (;namesIter!=namesEnd;++namesIter) { q.add_property_name(*namesIter); } if (active_rules) { featureset_ptr fs=ds->features(q); if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; std::vector<rule_type*>::const_iterator itr=if_rules.begin(); std::vector<rule_type*>::const_iterator end=if_rules.end(); for (;itr != end;++itr) { expression_ptr const& expr=(*itr)->get_filter(); value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr); if (result.to_bool()) { do_else=false; const rule_type::symbolizers& symbols = (*itr)->get_symbolizers(); rule_type::symbolizers::const_iterator symIter=symbols.begin(); rule_type::symbolizers::const_iterator symEnd =symbols.end(); for (;symIter != symEnd;++symIter) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),*symIter); } } } if (do_else) { //else filter std::vector<rule_type*>::const_iterator itr= else_rules.begin(); std::vector<rule_type*>::const_iterator end= else_rules.end(); for (;itr != end;++itr) { const rule_type::symbolizers& symbols = (*itr)->get_symbolizers(); rule_type::symbolizers::const_iterator symIter= symbols.begin(); rule_type::symbolizers::const_iterator symEnd = symbols.end(); for (;symIter!=symEnd;++symIter) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),*symIter); } } } } } } } } p.end_layer_processing(lay); } Map const& m_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <commit_msg>+ calculate resolution using map's current extent (see ticket #502 for discussion, thanks springmeyer and mar_rud!)<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/utils.hpp> #include <mapnik/projection.hpp> #include <mapnik/scale_denominator.hpp> #ifdef MAPNIK_DEBUG //#include <mapnik/wall_clock_timer.hpp> #endif //stl #include <vector> namespace mapnik { template <typename Processor> class feature_style_processor { struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output, Feature const& f, proj_transform const& prj_trans) : output_(output), f_(f), prj_trans_(prj_trans) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_,prj_trans_); } Processor & output_; Feature const& f_; proj_transform const& prj_trans_; }; public: feature_style_processor(Map const& m) : m_(m) {} void apply() { #ifdef MAPNIK_DEBUG //mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: "); #endif Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); try { projection proj(m_.srs()); // map projection double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic()); #ifdef MAPNIK_DEBUG std::clog << "scale denominator = " << scale_denom << "\n"; #endif std::vector<layer>::const_iterator itr = m_.layers().begin(); std::vector<layer>::const_iterator end = m_.layers().end(); while (itr != end) { if (itr->isVisible(scale_denom)) { apply_to_layer(*itr, p, proj, scale_denom); } ++itr; } } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } p.end_map_processing(m_); } private: void apply_to_layer(layer const& lay, Processor & p, projection const& proj0,double scale_denom) { #ifdef MAPNIK_DEBUG //wall_clock_progress_timer timer(clog, "end layer rendering: "); #endif p.start_layer_processing(lay); boost::shared_ptr<datasource> ds=lay.datasource(); if (ds) { box2d<double> ext = m_.get_buffered_extent(); projection proj1(lay.srs()); proj_transform prj_trans(proj0,proj1); box2d<double> layer_ext = lay.envelope(); double lx0 = layer_ext.minx(); double ly0 = layer_ext.miny(); double lz0 = 0.0; double lx1 = layer_ext.maxx(); double ly1 = layer_ext.maxy(); double lz1 = 0.0; // back project layers extent into main map projection prj_trans.backward(lx0,ly0,lz0); prj_trans.backward(lx1,ly1,lz1); // if no intersection then nothing to do for layer if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() ) { return; } // clip query bbox lx0 = std::max(ext.minx(),lx0); ly0 = std::max(ext.miny(),ly0); lx1 = std::min(ext.maxx(),lx1); ly1 = std::min(ext.maxy(),ly1); prj_trans.forward(lx0,ly0,lz0); prj_trans.forward(lx1,ly1,lz1); box2d<double> bbox(lx0,ly0,lx1,ly1); query::resolution_type res(m_.getWidth()/m_.getCurrentExtent().width(),m_.getHeight()/m_.getCurrentExtent().height()); query q(bbox,res,scale_denom); //BBOX query std::vector<std::string> const& style_names = lay.styles(); std::vector<std::string>::const_iterator stylesIter = style_names.begin(); std::vector<std::string>::const_iterator stylesEnd = style_names.end(); for (;stylesIter != stylesEnd; ++stylesIter) { std::set<std::string> names; attribute_collector collector(names); std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; bool active_rules=false; boost::optional<feature_type_style const&> style=m_.find_style(*stylesIter); if (!style) continue; const std::vector<rule_type>& rules=(*style).get_rules(); std::vector<rule_type>::const_iterator ruleIter=rules.begin(); std::vector<rule_type>::const_iterator ruleEnd=rules.end(); for (;ruleIter!=ruleEnd;++ruleIter) { if (ruleIter->active(scale_denom)) { active_rules=true; // collect unique attribute names collector(*ruleIter); if (ruleIter->has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } else { if_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } } } std::set<std::string>::const_iterator namesIter=names.begin(); std::set<std::string>::const_iterator namesEnd =names.end(); // push all property names for (;namesIter!=namesEnd;++namesIter) { q.add_property_name(*namesIter); } if (active_rules) { featureset_ptr fs=ds->features(q); if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; std::vector<rule_type*>::const_iterator itr=if_rules.begin(); std::vector<rule_type*>::const_iterator end=if_rules.end(); for (;itr != end;++itr) { expression_ptr const& expr=(*itr)->get_filter(); value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr); if (result.to_bool()) { do_else=false; const rule_type::symbolizers& symbols = (*itr)->get_symbolizers(); rule_type::symbolizers::const_iterator symIter=symbols.begin(); rule_type::symbolizers::const_iterator symEnd =symbols.end(); for (;symIter != symEnd;++symIter) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),*symIter); } } } if (do_else) { //else filter std::vector<rule_type*>::const_iterator itr= else_rules.begin(); std::vector<rule_type*>::const_iterator end= else_rules.end(); for (;itr != end;++itr) { const rule_type::symbolizers& symbols = (*itr)->get_symbolizers(); rule_type::symbolizers::const_iterator symIter= symbols.begin(); rule_type::symbolizers::const_iterator symEnd = symbols.end(); for (;symIter!=symEnd;++symIter) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),*symIter); } } } } } } } } p.end_layer_processing(lay); } Map const& m_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <|endoftext|>
<commit_before>/** * Package: eVias Core unitary tests * * Copyright (c) 2010 - 2011 Grégory Saive * * For more informations about the licensing of this product, please refer * to the LICENCE file in the root application directory. * */ #include "../core/string_utils.hpp" #include "../core/unit_test_suite.hpp" #include "../application/console.hpp" // unitary test classes include #include "configFiles/objectParse.hpp" #include "configFiles/objectWrite.hpp" #include "configFiles/invalidRead.hpp" #include "jsonObjects/simpleParse.hpp" #include "jsonObjects/objectParse.hpp" #include "jsonObjects/objectLoad.hpp" #include "sqlObjects/dataChecks.hpp" #include "sqlObjects/insertStmt.hpp" #include "sqlObjects/removeStmt.hpp" #include "sqlObjects/updateStmt.hpp" #include "sqlObjects/paramsParse.hpp" #include "qtViews/mainWnd.hpp" #include "qtViews/enhancedView.hpp" #include "databaseObjects/dbConnection.hpp" #include "databaseObjects/dbInsert.hpp" #include "databaseObjects/dbDelete.hpp" #include "databaseObjects/dbUpdate.hpp" #include "databaseObjects/dbFetchAll.hpp" #include "networkObjects/packetObject.hpp" #include <vector> #include <string> int main (int argc, char* args[]) { // XXX handle call arguments // - should allow specifying test lists for execution // - should allow configuration of tests using namespace std; using evias::core::test::unitTestSuite; using evias::core::test::testResult; using evias::application::consoleParser; using evias::core::in_vector; string project = "eVias C++ library unitary test suite"; string usage = " \ ./suite_execution.exe [--skip (config|json|sqlobjects|views|dbobjects|network)] \ [--only (config|json|sqlobjects|views|dbobjects|network) \ "; consoleParser* suiteCallArgs = new consoleParser(project, usage, argc, args); suiteCallArgs->canEmptyCall(true) ->addAllowedArg("--skip") ->addAllowedArg("--only") ->parseAll(); map<string,string> callArgs = suiteCallArgs->readData(); // suite execution call configuration bool hasOnly = (callArgs.find("--only") != callArgs.end()); bool hasSkip = (callArgs.find("--skip") != callArgs.end()); bool testConfigFiles = false; bool testJson = false; bool testSqlObjects = false; bool testViews = false; bool testDbObjects = false; bool testNetwork = false; map<string,int> validKeys; validKeys.insert(make_pair("config", 1)); validKeys.insert(make_pair("json", 2)); validKeys.insert(make_pair("sqlobjects", 3)); validKeys.insert(make_pair("views", 4)); validKeys.insert(make_pair("dbobjects", 5)); validKeys.insert(make_pair("network", 6)); if (hasOnly && callArgs["--only"].size() > 0 && (validKeys.find(callArgs["--only"]) != validKeys.end()) ) { string onlyVal = callArgs["--only"]; if (onlyVal == "config") testConfigFiles = true; else if (onlyVal == "json") testJson = true; else if (onlyVal == "sqlobjects") testSqlObjects = true; else if (onlyVal == "views") testViews = true; else if (onlyVal == "dbobjects") testDbObjects = true; else if (onlyVal == "network") testNetwork = true; } else if (hasSkip && callArgs["--skip"].size() > 0) { // skip may have to split arguments with "," for several skipped modules string skipKeys = callArgs["--skip"]; vector<string> keysToSkip; if (skipKeys.find(",") != string::npos) { // has multiple keys // (append last comma for in_vector() bug keysToSkip = evias::core::split(skipKeys.append(","), ','); } else keysToSkip.push_back(skipKeys); // for skip option, by default everything is tested testConfigFiles = testJson = testSqlObjects = testViews = testDbObjects = testNetwork = true; // foreach key found, "do not test" if (in_vector("config", keysToSkip)) testConfigFiles = false; if (in_vector("json", keysToSkip)) testJson = false; if (in_vector("sqlobjects", keysToSkip)) testSqlObjects = false; if (in_vector("views", keysToSkip)) testViews = false; if (in_vector("dbobjects", keysToSkip)) testDbObjects = false; if (in_vector("network", keysToSkip)) testNetwork = false; } else { // no relevant arg, test everything testConfigFiles = testJson = testSqlObjects = testViews = testDbObjects = testNetwork = true; } // start unitary test suite configuration vector<string> params; unitTestSuite testSuite; // // initialize each unitary test service // evias::core::test::configFiles::objectParse* configFiles_objectParse = new evias::core::test::configFiles::objectParse(); params.push_back ("/home/greg/srv/home.work/cpp/eviasLib/evias/tests/bin/config/configFiles/objectParse.ini"); configFiles_objectParse->setOptions(params); configFiles_objectParse->setLabel("INI parsing"); params.clear(); evias::core::test::configFiles::objectWrite* configFiles_objectWrite = new evias::core::test::configFiles::objectWrite(); params.push_back ("/home/greg/srv/home.work/cpp/eviasLib/evias/tests/bin/config/configFiles/objectWrite.ini"); configFiles_objectWrite->setOptions(params); configFiles_objectWrite->setLabel("INI writing"); params.clear(); evias::core::test::configFiles::invalidRead* configFiles_invalidRead = new evias::core::test::configFiles::invalidRead(); params.push_back ("/home/greg/srv/home.work/cpp/eviasLib/evias/tests/bin/config/configFiles/invalidRead.ini"); configFiles_invalidRead->setOptions(params); configFiles_invalidRead->setLabel("INI invalid reading"); params.clear(); evias::core::test::jsonObjects::simpleParse* jsonObjects_simpleParse = new evias::core::test::jsonObjects::simpleParse(); jsonObjects_simpleParse->setLabel("JSON classes simpleParse"); evias::core::test::jsonObjects::objectParse* jsonObjects_objectParse = new evias::core::test::jsonObjects::objectParse(); jsonObjects_objectParse->setLabel("JSON classes objectParse"); evias::core::test::jsonObjects::objectLoad* jsonObjects_objectLoad = new evias::core::test::jsonObjects::objectLoad(); jsonObjects_objectLoad->setLabel("JSON classes objectLoad"); evias::core::test::sqlObjects::dataChecks* sqlObjects_dataChecks = new evias::core::test::sqlObjects::dataChecks(); sqlObjects_dataChecks->setLabel("SQL classes query data checks"); evias::core::test::sqlObjects::insertStmt* sqlObjects_insertStmt = new evias::core::test::sqlObjects::insertStmt(); sqlObjects_insertStmt->setLabel("SQL classes insertStmt"); evias::core::test::sqlObjects::removeStmt* sqlObjects_removeStmt = new evias::core::test::sqlObjects::removeStmt(); sqlObjects_removeStmt->setLabel("SQL classes removeStmt"); evias::core::test::sqlObjects::updateStmt* sqlObjects_updateStmt = new evias::core::test::sqlObjects::updateStmt(); sqlObjects_updateStmt->setLabel("SQL classes updateStmt"); evias::core::test::sqlObjects::paramsParse* sqlObjects_paramsParse = new evias::core::test::sqlObjects::paramsParse(); sqlObjects_paramsParse->setLabel("SQL classes parameters parse (conditions)"); evias::core::test::qtViews::mainWnd* qtViews_mainWnd = new evias::core::test::qtViews::mainWnd(); qtViews_mainWnd->setLabel("Qt classes mainWnd"); qtViews_mainWnd->setCall(argc,args); evias::core::test::qtViews::enhancedView* qtViews_enhancedView = new evias::core::test::qtViews::enhancedView(); qtViews_enhancedView->setLabel("Qt classes enhancedView"); qtViews_enhancedView->setCall(argc,args); params.clear(); params.push_back("evias"); params.push_back("developing"); params.push_back(""); params.push_back("web.evias.loc"); evias::core::test::databaseObjects::dbConnection* databaseObjects_dbConnection = new evias::core::test::databaseObjects::dbConnection(); databaseObjects_dbConnection->setOptions(params); databaseObjects_dbConnection->setLabel("Database objects dbConnection"); evias::core::test::databaseObjects::dbInsert* databaseObjects_dbInsert = new evias::core::test::databaseObjects::dbInsert(); databaseObjects_dbInsert->setOptions(params); databaseObjects_dbInsert->setLabel("Database objects dbInsert"); evias::core::test::databaseObjects::dbDelete* databaseObjects_dbDelete = new evias::core::test::databaseObjects::dbDelete(); databaseObjects_dbDelete->setOptions(params); databaseObjects_dbDelete->setLabel("Database objects dbDelete"); evias::core::test::databaseObjects::dbUpdate* databaseObjects_dbUpdate = new evias::core::test::databaseObjects::dbUpdate(); databaseObjects_dbUpdate->setOptions(params); databaseObjects_dbUpdate->setLabel("Database objects dbUpdate"); evias::core::test::databaseObjects::dbFetchAll* databaseObjects_dbFetchAll = new evias::core::test::databaseObjects::dbFetchAll(); databaseObjects_dbFetchAll->setOptions(params); databaseObjects_dbFetchAll->setLabel("Database objects dbFetchAll"); evias::core::test::networkObjects::packetObject* networkObjects_packetObject = new evias::core::test::networkObjects::packetObject(); networkObjects_packetObject->setLabel("Network objects packetObject"); /** * configure test suite * map a test object to a testResult. * result code will be checked, result message * will only in case message is not "no_message_check". **/ if (testConfigFiles) { testSuite.addTest(configFiles_objectParse, testResult(1, "no_message_check")); testSuite.addTest(configFiles_objectWrite, testResult(1, "no_message_check")); testSuite.addTest(configFiles_invalidRead, testResult(1, "no_message_check")); } if (testJson) { testSuite.addTest(jsonObjects_simpleParse, testResult(1, "no_message_check")); testSuite.addTest(jsonObjects_objectParse, testResult(1, "no_message_check")); testSuite.addTest(jsonObjects_objectLoad, testResult(1, "no_message_check")); } if (testSqlObjects) { testSuite.addTest(sqlObjects_dataChecks, testResult(1, "no_message_check")); testSuite.addTest(sqlObjects_insertStmt, testResult(1, "no_message_check")); testSuite.addTest(sqlObjects_removeStmt, testResult(1, "no_message_check")); testSuite.addTest(sqlObjects_updateStmt, testResult(1, "no_message_check")); testSuite.addTest(sqlObjects_paramsParse, testResult(1, "no_message_check")); } if (testViews) { testSuite.addTest(qtViews_mainWnd, testResult(1, "no_message_check")); testSuite.addTest(qtViews_enhancedView, testResult(1, "no_message_check")); } if (testDbObjects) { testSuite.addTest(databaseObjects_dbConnection, testResult(1, "no_message_check")); testSuite.addTest(databaseObjects_dbInsert, testResult(1, "no_message_check")); testSuite.addTest(databaseObjects_dbDelete, testResult(1, "no_message_check")); testSuite.addTest(databaseObjects_dbUpdate, testResult(1, "no_message_check")); testSuite.addTest(databaseObjects_dbFetchAll, testResult(1, "no_message_check")); } if (testNetwork) { testSuite.addTest(networkObjects_packetObject, testResult(1, "no_message_check")); } testSuite.setQuietMode(false); testSuite.setOutputFile("/home/greg/srv/home.work/cpp/eviasLib/evias/tests/bin/logs/suite_execution_results.log"); return (int) testSuite.execute(); } <commit_msg>suite_execution.cpp contains main() implementation. As of an easy understanding of the unitary test suite application runpoint is very important, this file should only be handling the console call arguments and configure a suite object to do whatever it is able to do.<commit_after>/** * Package: eVias Core unitary tests * * Copyright (c) 2010 - 2011 Grégory Saive * * For more informations about the licensing of this product, please refer * to the LICENCE file in the root application directory. * */ #include "../core/string_utils.hpp" #include "../application/console.hpp" #include "library_test_suite.hpp" // unitary test classes include #include <vector> #include <string> int main (int argc, char* args[]) { using namespace std; using evias::core::test::eviasTestSuite; using evias::core::test::testResult; using evias::application::consoleParser; using evias::core::in_vector; string project = "eVias C++ library unitary test suite"; string usage = " \ ./suite_execution.exe [--skip config,json,sqlobjects,views,dbobjects,network] \ [--only config,json,sqlobjects,views,dbobjects,network] \ "; consoleParser* suiteCallArgs = new consoleParser(project, usage, argc, args); suiteCallArgs->canEmptyCall(true) ->addAllowedArg("--skip") ->addAllowedArg("--only") ->parseAll(); map<string,string> callArgs = suiteCallArgs->readData(); // suite execution call configuration // basically we test everything. bool testConfigFiles = true; bool testJson = true; bool testSqlObjects = true; bool testViews = true; bool testDbObjects = true; bool testNetwork = true; bool hasOnly = (callArgs.find("--only") != callArgs.end()); bool hasSkip = (callArgs.find("--skip") != callArgs.end()); // callArg[KEY] access facility string usingOption = "default"; if (hasOnly && callArgs["--only"].size() > 0) { usingOption = "--only"; } else if (hasSkip && callArgs["--skip"].size() > 0) { usingOption = "--skip"; } // process call arguments if (usingOption == "--only" || usingOption == "--skip") { // we have a workable option (size > 0) vector<string> optionKeys; string optionData = callArgs[usingOption]; evias::core::trim(optionData, " "); if (optionData.find(",") != string::npos) optionKeys = evias::core::split(optionData.append(","), ','); // multi key ',' separated else optionKeys.push_back(optionData); // single key // if we are in "skip mode" => we test everything except present key(s) // if we are in "only mode" => we test nothing but present key(s) bool initTest = true; // everything if (usingOption == "--only") { initTest = false; } testConfigFiles = testJson = testSqlObjects = testViews = testDbObjects = testNetwork = (initTest); // present in option key(s) means having to change the data if (in_vector("config", optionKeys)) testConfigFiles = ! initTest; if (in_vector("json", optionKeys)) testJson = ! initTest; if (in_vector("sqlobjects", optionKeys)) testSqlObjects = ! initTest; if (in_vector("views", optionKeys)) testViews = ! initTest; if (in_vector("dbobjects", optionKeys)) testDbObjects = ! initTest; if (in_vector("network", optionKeys)) testNetwork = ! initTest; } // configure the test suite eviasTestSuite* librarySuite = new eviasTestSuite(argc, args); librarySuite->setTestConfig(testConfigFiles) ->setTestJSON(testJson) ->setTestSQL(testSqlObjects) ->setTestViews(testViews) ->setTestDatabase(testDbObjects) ->setTestNetwork(testNetwork); // execute tests int returnCode = librarySuite->execute(); delete librarySuite; return returnCode; } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "maintenancejobrunner.h" #include <vespa/vespalib/util/lambdatask.h> #include <vespa/fastos/thread.h> #include <vespa/log/log.h> LOG_SETUP(".proton.server.maintenancejobrunner"); using vespalib::Executor; using vespalib::makeLambdaTask; namespace proton { void MaintenanceJobRunner::run() { addExecutorTask(); } void MaintenanceJobRunner::stop() { Guard guard(_lock); _stopped = true; } void MaintenanceJobRunner::addExecutorTask() { Guard guard(_lock); if (!_stopped && !_job->isBlocked() && !_queued) { _queued = true; _executor.execute(makeLambdaTask([this]() { runJobInExecutor(); })); } } void MaintenanceJobRunner::runJobInExecutor() { { Guard guard(_lock); _queued = false; if (_stopped) { return; } _running = true; } bool finished = _job->run(); if (LOG_WOULD_LOG(debug)) { FastOS_ThreadId threadId = FastOS_Thread::GetCurrentThreadId(); LOG(debug, "runJobInExecutor(): job='%s', task='%p', threadId=%" PRIu64 "", _job->getName().c_str(), this, (uint64_t)threadId); } if (!finished) { addExecutorTask(); } { Guard guard(_lock); _running = false; } } MaintenanceJobRunner::MaintenanceJobRunner(Executor &executor, IMaintenanceJob::UP job) : _executor(executor), _job(std::move(job)), _stopped(false), _queued(false), _running(false), _lock() { _job->registerRunner(this); } bool MaintenanceJobRunner::isRunning() const { Guard guard(_lock); return _running || _queued; } } // namespace proton <commit_msg>Call onStop on the job<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "maintenancejobrunner.h" #include <vespa/vespalib/util/lambdatask.h> #include <vespa/fastos/thread.h> #include <vespa/log/log.h> LOG_SETUP(".proton.server.maintenancejobrunner"); using vespalib::Executor; using vespalib::makeLambdaTask; namespace proton { void MaintenanceJobRunner::run() { addExecutorTask(); } void MaintenanceJobRunner::stop() { { Guard guard(_lock); _stopped = true; } _job->onStop(); } void MaintenanceJobRunner::addExecutorTask() { Guard guard(_lock); if (!_stopped && !_job->isBlocked() && !_queued) { _queued = true; _executor.execute(makeLambdaTask([this]() { runJobInExecutor(); })); } } void MaintenanceJobRunner::runJobInExecutor() { { Guard guard(_lock); _queued = false; if (_stopped) { return; } _running = true; } bool finished = _job->run(); if (LOG_WOULD_LOG(debug)) { FastOS_ThreadId threadId = FastOS_Thread::GetCurrentThreadId(); LOG(debug, "runJobInExecutor(): job='%s', task='%p', threadId=%" PRIu64 "", _job->getName().c_str(), this, (uint64_t)threadId); } if (!finished) { addExecutorTask(); } { Guard guard(_lock); _running = false; } } MaintenanceJobRunner::MaintenanceJobRunner(Executor &executor, IMaintenanceJob::UP job) : _executor(executor), _job(std::move(job)), _stopped(false), _queued(false), _running(false), _lock() { _job->registerRunner(this); } bool MaintenanceJobRunner::isRunning() const { Guard guard(_lock); return _running || _queued; } } // namespace proton <|endoftext|>
<commit_before>/* * Server.cpp * * Created on: 2009-09-13 * Author: chudy */ #include "network/Server.h" #include "common.h" #include "network/events.h" Server::Server(int p_port) : m_permitedConnection(NULL), m_raceServer(this) { m_slots.connect(m_gameServer.sig_client_connected(), this, &Server::slotClientConnected); m_slots.connect(m_gameServer.sig_client_disconnected(), this, &Server::slotClientDisconnected); m_slots.connect(m_gameServer.sig_event_received(), this, &Server::slotEventArrived); m_gameServer.start(CL_StringHelp::int_to_local8(p_port)); } Server::~Server() { m_gameServer.stop(); } void Server::update(int p_timeElapsed) { // m_gameServer.process_events(); } void Server::slotClientConnected(CL_NetGameConnection *p_netGameConnection) { CL_MutexSection lockSection(&m_lockMutex); cl_log_event("network", "Player %1 is connected", (unsigned) p_netGameConnection); Player *player = new Player(); m_connections[p_netGameConnection] = player; // emit the signal m_signalPlayerConnected.invoke(p_netGameConnection, player); } void Server::slotClientDisconnected(CL_NetGameConnection *p_netGameConnection) { CL_MutexSection lockSection(&m_lockMutex); cl_log_event("network", "Player %1 disconnects", m_connections[p_netGameConnection]->getName().empty() ? CL_StringHelp::uint_to_local8((unsigned) p_netGameConnection) : m_connections[p_netGameConnection]->getName()); std::map<CL_NetGameConnection*, Player*>::iterator itor = m_connections.find(p_netGameConnection); if (itor != m_connections.end()) { Player* player = itor->second; // emit the signal m_signalPlayerDisconnected.invoke(p_netGameConnection, player); // cleanup delete player; m_connections.erase(itor); } } void Server::slotEventArrived(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { cl_log_event("event", "Event %1 arrived", p_event.to_string()); try { const CL_String eventName = p_event.get_name(); const std::vector<CL_TempString> parts = CL_StringHelp::split_text(eventName, ":"); bool unhandled = false; if (parts[0] == EVENT_PREFIX_GENERAL) { if (eventName == EVENT_HI) { handleHiEvent(p_connection, p_event); } else if (eventName == EVENT_GRANT_PERMISSIONS) { handleGrantEvent(p_connection, p_event); } else if (eventName == EVENT_INIT_RACE) { handleInitRaceEvent(p_connection, p_event); } else { unhandled = true; } } else if (parts[0] == EVENT_PREFIX_RACE) { CL_MutexSection lockSection(&m_lockMutex); m_raceServer.handleEvent(p_connection, p_event); } else { unhandled = true; } if (unhandled) { cl_log_event("event", "Event %1 remains unhandled", p_event.to_string()); } } catch (CL_Exception e) { cl_log_event("exception", e.message); } } void Server::handleHiEvent(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { const CL_String playerName = p_event.get_argument(0); if (playerName.empty()) { cl_log_event("error", "Protocol error while handling %1 event", p_event.to_string()); return; } CL_MutexSection lockSection(&m_lockMutex); // check availability bool nameAvailable = true; std::pair<CL_NetGameConnection*, Player*> pair; foreach (pair, m_connections) { if (pair.second->getName() == playerName) { nameAvailable = false; } } if (!nameAvailable) { // refuse of nick set send(p_connection, CL_NetGameEvent(EVENT_PLAYER_NICK_IN_USE)); cl_log_event("event", "Name '%1' already in use for player '%2'", playerName, (unsigned) p_connection); } else { // resend player's connection event m_connections[p_connection]->setName(playerName); sendToAll(CL_NetGameEvent(EVENT_PLAYER_CONNECTED, playerName), p_connection); cl_log_event("event", "Player %1 is now known as '%2'", (unsigned) p_connection, playerName); // and send him the list of other players std::pair<CL_NetGameConnection*, Player*> pair; foreach(pair, m_connections) { if (pair.first == p_connection) { continue; } CL_NetGameEvent replyEvent(EVENT_PLAYER_CONNECTED, pair.second->getName()); send(p_connection, replyEvent); } // if race is initialized, then send him the init event if (m_raceServer.isInitialized()) { CL_NetGameEvent raceInitEvent(EVENT_INIT_RACE, m_raceServer.getLevelName()); send(p_connection, raceInitEvent); } } } void Server::send(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { p_connection->send_event(p_event); } void Server::sendToAll(const CL_NetGameEvent &p_event, const CL_NetGameConnection* p_ignore) { CL_MutexSection lockSection(&m_lockMutex); std::pair<CL_NetGameConnection*, Player*> pair; foreach(pair, m_connections) { if (pair.first != p_ignore) { pair.first->send_event(p_event); } } } CL_NetGameConnection* Server::getConnectionForPlayer(const Player* player) { CL_MutexSection lockSection(&m_lockMutex); std::pair<CL_NetGameConnection*, Player*> pair; foreach (pair, m_connections) { if (pair.second == player) { return pair.first; } } return NULL; } void Server::handleInitRaceEvent(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { if (!isPermitted(p_connection)) { const CL_String &playerName = m_connections[p_connection]->getName(); cl_log_event("perm", "Player %1 is not permitted to init the race", playerName); } const CL_String levelName = (CL_String) p_event.get_argument(0); // if race is initialized, then destroy it now if (m_raceServer.isInitialized()) { m_raceServer.destroy(); } cl_log_event("event", "Initializing the race on level %1", levelName); // initialize the level m_raceServer.initialize(levelName); // send init race event to other players sendToAll(p_event, p_connection); } void Server::handleGrantEvent(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { const CL_String &playerName = m_connections[p_connection]->getName(); const CL_String password = p_event.get_argument(0); if (password == "123") { // FIXME: store the password as server configuration m_permitedConnection = p_connection; cl_log_event("perm", "Player %1 is the root", playerName); } else { cl_log_event("perm", "Wrong root password for player %1", playerName); } } <commit_msg>* First connection grants the privilages to init race<commit_after>/* * Server.cpp * * Created on: 2009-09-13 * Author: chudy */ #include "network/Server.h" #include "common.h" #include "network/events.h" Server::Server(int p_port) : m_permitedConnection(NULL), m_raceServer(this) { m_slots.connect(m_gameServer.sig_client_connected(), this, &Server::slotClientConnected); m_slots.connect(m_gameServer.sig_client_disconnected(), this, &Server::slotClientDisconnected); m_slots.connect(m_gameServer.sig_event_received(), this, &Server::slotEventArrived); m_gameServer.start(CL_StringHelp::int_to_local8(p_port)); } Server::~Server() { m_gameServer.stop(); } void Server::update(int p_timeElapsed) { // m_gameServer.process_events(); } void Server::slotClientConnected(CL_NetGameConnection *p_netGameConnection) { CL_MutexSection lockSection(&m_lockMutex); cl_log_event("network", "Player %1 is connected", (unsigned) p_netGameConnection); Player *player = new Player(); m_connections[p_netGameConnection] = player; // if this is first player, then it grants the permission if (m_connections.size() == 1) { m_permitedConnection = p_netGameConnection; } // emit the signal m_signalPlayerConnected.invoke(p_netGameConnection, player); } void Server::slotClientDisconnected(CL_NetGameConnection *p_netGameConnection) { CL_MutexSection lockSection(&m_lockMutex); cl_log_event("network", "Player %1 disconnects", m_connections[p_netGameConnection]->getName().empty() ? CL_StringHelp::uint_to_local8((unsigned) p_netGameConnection) : m_connections[p_netGameConnection]->getName()); std::map<CL_NetGameConnection*, Player*>::iterator itor = m_connections.find(p_netGameConnection); if (itor != m_connections.end()) { Player* player = itor->second; // emit the signal m_signalPlayerDisconnected.invoke(p_netGameConnection, player); // cleanup delete player; m_connections.erase(itor); } } void Server::slotEventArrived(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { cl_log_event("event", "Event %1 arrived", p_event.to_string()); try { const CL_String eventName = p_event.get_name(); const std::vector<CL_TempString> parts = CL_StringHelp::split_text(eventName, ":"); bool unhandled = false; if (parts[0] == EVENT_PREFIX_GENERAL) { if (eventName == EVENT_HI) { handleHiEvent(p_connection, p_event); } else if (eventName == EVENT_GRANT_PERMISSIONS) { handleGrantEvent(p_connection, p_event); } else if (eventName == EVENT_INIT_RACE) { handleInitRaceEvent(p_connection, p_event); } else { unhandled = true; } } else if (parts[0] == EVENT_PREFIX_RACE) { CL_MutexSection lockSection(&m_lockMutex); m_raceServer.handleEvent(p_connection, p_event); } else { unhandled = true; } if (unhandled) { cl_log_event("event", "Event %1 remains unhandled", p_event.to_string()); } } catch (CL_Exception e) { cl_log_event("exception", e.message); } } void Server::handleHiEvent(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { const CL_String playerName = p_event.get_argument(0); if (playerName.empty()) { cl_log_event("error", "Protocol error while handling %1 event", p_event.to_string()); return; } CL_MutexSection lockSection(&m_lockMutex); // check availability bool nameAvailable = true; std::pair<CL_NetGameConnection*, Player*> pair; foreach (pair, m_connections) { if (pair.second->getName() == playerName) { nameAvailable = false; } } if (!nameAvailable) { // refuse of nick set send(p_connection, CL_NetGameEvent(EVENT_PLAYER_NICK_IN_USE)); cl_log_event("event", "Name '%1' already in use for player '%2'", playerName, (unsigned) p_connection); } else { // resend player's connection event m_connections[p_connection]->setName(playerName); sendToAll(CL_NetGameEvent(EVENT_PLAYER_CONNECTED, playerName), p_connection); cl_log_event("event", "Player %1 is now known as '%2'", (unsigned) p_connection, playerName); // and send him the list of other players std::pair<CL_NetGameConnection*, Player*> pair; foreach(pair, m_connections) { if (pair.first == p_connection) { continue; } CL_NetGameEvent replyEvent(EVENT_PLAYER_CONNECTED, pair.second->getName()); send(p_connection, replyEvent); } // if race is initialized, then send him the init event if (m_raceServer.isInitialized()) { CL_NetGameEvent raceInitEvent(EVENT_INIT_RACE, m_raceServer.getLevelName()); send(p_connection, raceInitEvent); } } } void Server::send(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { p_connection->send_event(p_event); } void Server::sendToAll(const CL_NetGameEvent &p_event, const CL_NetGameConnection* p_ignore) { CL_MutexSection lockSection(&m_lockMutex); std::pair<CL_NetGameConnection*, Player*> pair; foreach(pair, m_connections) { if (pair.first != p_ignore) { pair.first->send_event(p_event); } } } CL_NetGameConnection* Server::getConnectionForPlayer(const Player* player) { CL_MutexSection lockSection(&m_lockMutex); std::pair<CL_NetGameConnection*, Player*> pair; foreach (pair, m_connections) { if (pair.second == player) { return pair.first; } } return NULL; } void Server::handleInitRaceEvent(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { if (!isPermitted(p_connection)) { const CL_String &playerName = m_connections[p_connection]->getName(); cl_log_event("perm", "Player %1 is not permitted to init the race", playerName); } const CL_String levelName = (CL_String) p_event.get_argument(0); // if race is initialized, then destroy it now if (m_raceServer.isInitialized()) { m_raceServer.destroy(); } cl_log_event("event", "Initializing the race on level %1", levelName); // initialize the level m_raceServer.initialize(levelName); // send init race event to other players sendToAll(p_event, p_connection); } void Server::handleGrantEvent(CL_NetGameConnection *p_connection, const CL_NetGameEvent &p_event) { const CL_String &playerName = m_connections[p_connection]->getName(); const CL_String password = p_event.get_argument(0); if (password == "123") { // FIXME: store the password as server configuration m_permitedConnection = p_connection; cl_log_event("perm", "Player %1 is the root", playerName); } else { cl_log_event("perm", "Wrong root password for player %1", playerName); } } <|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #include <rectojump/core/game.hpp> #include <rectojump/core/game_window.hpp> #include <rectojump/core/main_menu.hpp> #include <rectojump/core/state.hpp> #include <rectojump/global/error_inserter.hpp> #include <rectojump/game/debug_info.inl> int main() { // generate errors rj::error_inserter{}; // game rj::game_window gw; rj::game g{gw}; rj::main_menu m{g}; rj::state_handler sh{gw, g, m}; gw.start(); return 0; } <commit_msg>main adaption<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #include <rectojump/core/game.hpp> #include <rectojump/core/game_window.hpp> #include <rectojump/core/main_menu.hpp> #include <rectojump/core/state.hpp> #include <rectojump/game/debug_info.inl> #include <rectojump/global/error_inserter.hpp> #include <rectojump/shared/data_manager.hpp> int main() { // generate errors rj::error_inserter{}; // data rj::data_manager dm{rj::data_path, true}; // game rj::game_window gw; rj::game g{gw}; rj::main_menu m{g}; rj::state_handler sh{gw, g, m, dm}; gw.start(); return 0; } <|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_UI_CONNECTED_BUTTONS_HPP #define RJ_UI_CONNECTED_BUTTONS_HPP #include "button.hpp" #include <rectojump/global/common.hpp> #include <mlk/signals_slots/slot.h> namespace rj { namespace ui { template<typename T> using btn_ptr = mlk::sptr<T>; using base_btn_ptr = btn_ptr<button>; struct button_event {base_btn_ptr button; mlk::slot<> event;}; class connected_buttons : public sf::Drawable { std::map<int, button_event> m_buttons; int m_current_pressed_index{0}; int m_current_add_index{0}; bool m_pressed{false}; public: mlk::slot<base_btn_ptr&> on_press; mlk::slot<base_btn_ptr&> on_active_button; mlk::slot<base_btn_ptr&> on_inactive_button; connected_buttons() = default; void update(dur duration) { for(auto& a : m_buttons) { // update all buttons a.second.button->update(duration); // get current pressed button if(!a.second.button->is_pressed() && !a.second.button->is_hover()) on_inactive_button(a.second.button); if(a.second.button->is_pressed()) { m_current_pressed_index = a.first; if(!m_pressed) { a.second.event(); on_press(m_buttons[m_current_pressed_index].button); m_pressed = true; } } } // call the custom user settings if(m_current_pressed_index != -1) { on_active_button(m_buttons[m_current_pressed_index].button); if(!m_buttons[m_current_pressed_index].button->is_pressed()) m_pressed = false; } } template<typename Button_Type, typename... Args> btn_ptr<Button_Type> add_button(Args&&... args) { auto ptr(std::make_shared<Button_Type>(std::forward<Args>(args)...)); m_buttons.emplace(m_current_add_index, button_event{ptr, {}}); ++m_current_add_index; return ptr; } template<typename Button_Type, typename Func, typename... Args> btn_ptr<Button_Type> add_button_event(Func&& f, Args&&... args) { auto ptr(std::make_shared<Button_Type>(std::forward<Args>(args)...)); m_buttons.emplace(m_current_add_index, button_event{ptr, {f}}); ++m_current_add_index; return ptr; } void inactivate() noexcept {m_current_pressed_index = -1;} void set_active_button(int index) noexcept {m_current_pressed_index = index; on_press(m_buttons[m_current_pressed_index].button);} const base_btn_ptr& get_active_btn() const noexcept {return m_buttons.at(m_current_pressed_index).button;} auto get_buttons() -> const decltype(m_buttons)& {return m_buttons;} private: void draw(sf::RenderTarget& target, sf::RenderStates states) const override { for(auto& a : m_buttons) target.draw(*a.second.button, states); } }; } } #endif // RJ_UI_CONNECTED_BUTTONS_HPP <commit_msg>ui > connected_buttons: adapted to ui::button<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_UI_CONNECTED_BUTTONS_HPP #define RJ_UI_CONNECTED_BUTTONS_HPP #include "button.hpp" #include <rectojump/global/common.hpp> #include <mlk/signals_slots/slot.h> namespace rj { namespace ui { template<typename T> using btn_ptr = mlk::sptr<T>; using base_btn_ptr = btn_ptr<button>; struct button_event {base_btn_ptr button; mlk::slot<> event;}; class connected_buttons : public sf::Drawable { std::map<int, button_event> m_buttons; int m_current_pressed_index{0}; int m_current_add_index{0}; bool m_pressed{false}; public: mlk::slot<base_btn_ptr&> on_press; mlk::slot<base_btn_ptr&> on_active_button; mlk::slot<base_btn_ptr&> on_inactive_button; connected_buttons() = default; void update(dur duration) { for(auto& a : m_buttons) { // update all buttons a.second.button->update(duration); // get current pressed button if(!a.second.button->pressed() && !a.second.button->hover()) on_inactive_button(a.second.button); if(a.second.button->pressed()) { m_current_pressed_index = a.first; if(!m_pressed) { a.second.event(); on_press(m_buttons[m_current_pressed_index].button); m_pressed = true; } } } // call the custom user settings if(m_current_pressed_index != -1) { on_active_button(m_buttons[m_current_pressed_index].button); if(!m_buttons[m_current_pressed_index].button->pressed()) m_pressed = false; } } template<typename Button_Type, typename... Args> btn_ptr<Button_Type> add_button(Args&&... args) { auto ptr(std::make_shared<Button_Type>(std::forward<Args>(args)...)); m_buttons.emplace(m_current_add_index, button_event{ptr, {}}); ++m_current_add_index; return ptr; } template<typename Button_Type, typename Func, typename... Args> btn_ptr<Button_Type> add_button_event(Func&& f, Args&&... args) { auto ptr(std::make_shared<Button_Type>(std::forward<Args>(args)...)); m_buttons.emplace(m_current_add_index, button_event{ptr, {f}}); ++m_current_add_index; return ptr; } void inactivate() noexcept {m_current_pressed_index = -1;} void set_active_button(int index) noexcept {m_current_pressed_index = index; on_press(m_buttons[m_current_pressed_index].button);} const base_btn_ptr& get_active_btn() const noexcept {return m_buttons.at(m_current_pressed_index).button;} auto get_buttons() -> const decltype(m_buttons)& {return m_buttons;} private: void draw(sf::RenderTarget& target, sf::RenderStates states) const override { for(auto& a : m_buttons) target.draw(*a.second.button, states); } }; } } #endif // RJ_UI_CONNECTED_BUTTONS_HPP <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drawfont.hxx,v $ * * $Revision: 1.38 $ * * last change: $Author: hr $ $Date: 2007-09-27 08:55: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 _DRAWFONT_HXX #define _DRAWFONT_HXX #include <tools/solar.h> #include <tools/string.hxx> #include <errhdl.hxx> class SwTxtFrm; class OutputDevice; class ViewShell; class SwScriptInfo; class Point; class SwWrongList; class Size; class SwFont; class Font; class SwUnderlineFont; /************************************************************************* * class SwDrawTextInfo * * encapsulates information for drawing text *************************************************************************/ class SwDrawTextInfo { const SwTxtFrm* pFrm; OutputDevice* pOut; ViewShell* pSh; const SwScriptInfo* pScriptInfo; const Point* pPos; const XubString* pText; const SwWrongList* pWrong; const SwWrongList* pSmartTags; // SMARTTAGS const Size* pSize; SwFont *pFnt; SwUnderlineFont* pUnderFnt; xub_StrLen* pHyphPos; long nLeft; long nRight; long nKanaDiff; xub_StrLen nIdx; xub_StrLen nLen; xub_StrLen nOfst; USHORT nWidth; USHORT nAscent; USHORT nCompress; long nSperren; long nSpace; long nKern; xub_StrLen nNumberOfBlanks; BYTE nCursorBidiLevel; BOOL bBullet : 1; BOOL bUpper : 1; // Fuer Kapitaelchen: Grossbuchstaben-Flag BOOL bDrawSpace : 1; // Fuer Kapitaelchen: Unter/Durchstreichung BOOL bGreyWave : 1; // Graue Wellenlinie beim extended TextInput BOOL bSpaceStop : 1; // For underlining we need to know, if a portion // is right in front of a hole portion or a // fix margin portion. BOOL bSnapToGrid : 1; // Does paragraph snap to grid? BOOL bIgnoreFrmRTL : 1; // Paint text as if text has LTR direction, used for // line numbering BOOL bPosMatchesBounds :1; // GetCrsrOfst should not return the next // position if screen position is inside second // half of bound rect, used for Accessibility SwDrawTextInfo(); // nicht zulaessig public: #ifndef PRODUCT BOOL bPos : 1; // These flags should control, that the appropriate BOOL bWrong : 1; // Set-function has been called before calling BOOL bSize : 1; // the Get-function of a member BOOL bFnt : 1; BOOL bHyph : 1; BOOL bLeft : 1; BOOL bRight : 1; BOOL bKana : 1; BOOL bOfst : 1; BOOL bAscent: 1; BOOL bSperr : 1; BOOL bSpace : 1; BOOL bNumberOfBlanks : 1; BOOL bUppr : 1; BOOL bDrawSp: 1; #endif SwDrawTextInfo( ViewShell *pS, OutputDevice &rO, const SwScriptInfo* pSI, const XubString &rSt, xub_StrLen nI, xub_StrLen nL, USHORT nW = 0, BOOL bB = FALSE ) { pFrm = NULL; pSh = pS; pOut = &rO; pScriptInfo = pSI; pText = &rSt; nIdx = nI; nLen = nL; nKern = 0; nCompress = 0; nWidth = nW; nNumberOfBlanks = 0; nCursorBidiLevel = 0; bBullet = bB; pUnderFnt = 0; bGreyWave = FALSE; bSpaceStop = FALSE; bSnapToGrid = FALSE; bIgnoreFrmRTL = FALSE; bPosMatchesBounds = FALSE; // These values are initialized but, they have to be // set explicitly via their Set-function before they may // be accessed by their Get-function: pPos = 0; pWrong = 0; pSmartTags = 0; pSize = 0; pFnt = 0; pHyphPos = 0; nLeft = 0; nRight = 0; nKanaDiff = 0; nOfst = 0; nAscent = 0; nSperren = 0; nSpace = 0; bUpper = FALSE; bDrawSpace = FALSE; #ifndef PRODUCT // these flags control, whether the matching member variables have // been set by using the Set-function before they may be accessed // by their Get-function: bPos = bWrong = bSize = bFnt = bAscent = bSpace = bNumberOfBlanks = bUppr = bDrawSp = bLeft = bRight = bKana = bOfst = bHyph = bSperr = FALSE; #endif } const SwTxtFrm* GetFrm() const { return pFrm; } void SetFrm( const SwTxtFrm* pNewFrm ) { pFrm = pNewFrm; } ViewShell *GetShell() const { return pSh; } OutputDevice& GetOut() const { return *pOut; } OutputDevice *GetpOut() const { return pOut; } const SwScriptInfo* GetScriptInfo() const { return pScriptInfo; } const Point &GetPos() const { ASSERT( bPos, "DrawTextInfo: Undefined Position" ); return *pPos; } xub_StrLen *GetHyphPos() const { ASSERT( bHyph, "DrawTextInfo: Undefined Hyph Position" ); return pHyphPos; } const XubString &GetText() const { return *pText; } const SwWrongList* GetWrong() const { ASSERT( bWrong, "DrawTextInfo: Undefined WrongList" ); return pWrong; } const SwWrongList* GetSmartTags() const { return pSmartTags; } const Size &GetSize() const { ASSERT( bSize, "DrawTextInfo: Undefined Size" ); return *pSize; } SwFont* GetFont() const { ASSERT( bFnt, "DrawTextInfo: Undefined Font" ); return pFnt; } SwUnderlineFont* GetUnderFnt() const { return pUnderFnt; } xub_StrLen GetIdx() const { return nIdx; } xub_StrLen GetLen() const { return nLen; } xub_StrLen GetOfst() const { ASSERT( bOfst, "DrawTextInfo: Undefined Offset" ); return nOfst; } xub_StrLen GetEnd() const { return nIdx + nLen; } long GetLeft() const { ASSERT( bLeft, "DrawTextInfo: Undefined left range" ); return nLeft; } long GetRight() const { ASSERT( bRight, "DrawTextInfo: Undefined right range" ); return nRight; } long GetKanaDiff() const { ASSERT( bKana, "DrawTextInfo: Undefined kana difference" ); return nKanaDiff; } USHORT GetWidth() const { return nWidth; } USHORT GetAscent() const { ASSERT( bAscent, "DrawTextInfo: Undefined Ascent" ); return nAscent; } USHORT GetKanaComp() const { return nCompress; } long GetSperren() const { ASSERT( bSperr, "DrawTextInfo: Undefined >Sperren<" ); return nSperren; } long GetKern() const { return nKern; } long GetSpace() const { ASSERT( bSpace, "DrawTextInfo: Undefined Spacing" ); return nSpace; } xub_StrLen GetNumberOfBlanks() const { ASSERT( bNumberOfBlanks, "DrawTextInfo::Undefined NumberOfBlanks" ); return nNumberOfBlanks; } BYTE GetCursorBidiLevel() const { return nCursorBidiLevel; } BOOL GetBullet() const { return bBullet; } BOOL GetUpper() const { ASSERT( bUppr, "DrawTextInfo: Undefined Upperflag" ); return bUpper; } BOOL GetDrawSpace() const { ASSERT( bDrawSp, "DrawTextInfo: Undefined DrawSpaceflag" ); return bDrawSpace; } BOOL GetGreyWave() const { return bGreyWave; } BOOL IsSpaceStop() const { return bSpaceStop; } BOOL SnapToGrid() const { return bSnapToGrid; } BOOL IsIgnoreFrmRTL() const { return bIgnoreFrmRTL; } BOOL IsPosMatchesBounds() const { return bPosMatchesBounds; } void SetOut( OutputDevice &rNew ) { pOut = &rNew; } void SetPos( const Point &rNew ) { pPos = &rNew; #ifndef PRODUCT bPos = TRUE; #endif } void SetHyphPos( xub_StrLen *pNew ) { pHyphPos = pNew; #ifndef PRODUCT bHyph = TRUE; #endif } void SetText( const XubString &rNew ) { pText = &rNew; } void SetWrong( const SwWrongList* pNew ) { pWrong = pNew; #ifndef PRODUCT bWrong = TRUE; #endif } void SetSmartTags( const SwWrongList* pNew ) { pSmartTags = pNew; } void SetSize( const Size &rNew ) { pSize = &rNew; #ifndef PRODUCT bSize = TRUE; #endif } void SetFont( SwFont* pNew ) { pFnt = pNew; #ifndef PRODUCT bFnt = TRUE; #endif } void SetIdx( xub_StrLen nNew ) { nIdx = nNew; } void SetLen( xub_StrLen nNew ) { nLen = nNew; } void SetOfst( xub_StrLen nNew ) { nOfst = nNew; #ifndef PRODUCT bOfst = TRUE; #endif } void SetLeft( long nNew ) { nLeft = nNew; #ifndef PRODUCT bLeft = TRUE; #endif } void SetRight( long nNew ) { nRight = nNew; #ifndef PRODUCT bRight = TRUE; #endif } void SetKanaDiff( long nNew ) { nKanaDiff = nNew; #ifndef PRODUCT bKana = TRUE; #endif } void SetWidth( USHORT nNew ) { nWidth = nNew; } void SetAscent( USHORT nNew ) { nAscent = nNew; #ifndef PRODUCT bAscent = TRUE; #endif } void SetKern( long nNew ) { nKern = nNew; } void SetSpace( long nNew ) { if( nNew < 0 ) { nSperren = -nNew; nSpace = 0; } else { nSpace = nNew; nSperren = 0; } #ifndef PRODUCT bSpace = TRUE; bSperr = TRUE; #endif } void SetNumberOfBlanks( xub_StrLen nNew ) { #ifndef PRODUCT bNumberOfBlanks = TRUE; #endif nNumberOfBlanks = nNew; } void SetCursorBidiLevel( BYTE nNew ) { nCursorBidiLevel = nNew; } void SetKanaComp( short nNew ) { nCompress = nNew; } void SetBullet( BOOL bNew ) { bBullet = bNew; } void SetUnderFnt( SwUnderlineFont* pULFnt ) { pUnderFnt = pULFnt; } void SetUpper( BOOL bNew ) { bUpper = bNew; #ifndef PRODUCT bUppr = TRUE; #endif } void SetDrawSpace( BOOL bNew ) { bDrawSpace = bNew; #ifndef PRODUCT bDrawSp = TRUE; #endif } void SetGreyWave( BOOL bNew ) { bGreyWave = bNew; } void SetSpaceStop( BOOL bNew ) { bSpaceStop = bNew; } void SetSnapToGrid( BOOL bNew ) { bSnapToGrid = bNew; } void SetIgnoreFrmRTL( BOOL bNew ) { bIgnoreFrmRTL = bNew; } void SetPosMatchesBounds( BOOL bNew ) { bPosMatchesBounds = bNew; } void Shift( USHORT nDir ); // sets a new color at the output device if necessary // if a font is passed as argument, the change if made to the font // otherwise the font at the output device is changed // returns if the font has been changed sal_Bool ApplyAutoColor( Font* pFnt = 0 ); }; #endif <commit_msg>INTEGRATION: CWS gcframework_DEV300 (1.37.364); FILE MERGED 2008/01/08 10:04:49 tl 1.37.364.2: RESYNC: (1.37-1.38); FILE MERGED 2007/11/26 09:14:31 tl 1.37.364.1: #i83776# get SwXTextMarkup::commitTextMarkup working<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drawfont.hxx,v $ * * $Revision: 1.39 $ * * last change: $Author: obo $ $Date: 2008-02-26 09:45:41 $ * * 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 _DRAWFONT_HXX #define _DRAWFONT_HXX #include <tools/solar.h> #include <tools/string.hxx> #include <errhdl.hxx> class SwTxtFrm; class OutputDevice; class ViewShell; class SwScriptInfo; class Point; class SwWrongList; class Size; class SwFont; class Font; class SwUnderlineFont; /************************************************************************* * class SwDrawTextInfo * * encapsulates information for drawing text *************************************************************************/ class SwDrawTextInfo { const SwTxtFrm* pFrm; OutputDevice* pOut; ViewShell* pSh; const SwScriptInfo* pScriptInfo; const Point* pPos; const XubString* pText; const SwWrongList* pWrong; const SwWrongList* pGrammarCheck; const SwWrongList* pSmartTags; // SMARTTAGS const Size* pSize; SwFont *pFnt; SwUnderlineFont* pUnderFnt; xub_StrLen* pHyphPos; long nLeft; long nRight; long nKanaDiff; xub_StrLen nIdx; xub_StrLen nLen; xub_StrLen nOfst; USHORT nWidth; USHORT nAscent; USHORT nCompress; long nSperren; long nSpace; long nKern; xub_StrLen nNumberOfBlanks; BYTE nCursorBidiLevel; BOOL bBullet : 1; BOOL bUpper : 1; // Fuer Kapitaelchen: Grossbuchstaben-Flag BOOL bDrawSpace : 1; // Fuer Kapitaelchen: Unter/Durchstreichung BOOL bGreyWave : 1; // Graue Wellenlinie beim extended TextInput BOOL bSpaceStop : 1; // For underlining we need to know, if a portion // is right in front of a hole portion or a // fix margin portion. BOOL bSnapToGrid : 1; // Does paragraph snap to grid? BOOL bIgnoreFrmRTL : 1; // Paint text as if text has LTR direction, used for // line numbering BOOL bPosMatchesBounds :1; // GetCrsrOfst should not return the next // position if screen position is inside second // half of bound rect, used for Accessibility SwDrawTextInfo(); // nicht zulaessig public: #ifndef PRODUCT BOOL bPos : 1; // These flags should control, that the appropriate BOOL bWrong : 1; // Set-function has been called before calling BOOL bGrammarCheck : 1; // the Get-function of a member BOOL bSize : 1; BOOL bFnt : 1; BOOL bHyph : 1; BOOL bLeft : 1; BOOL bRight : 1; BOOL bKana : 1; BOOL bOfst : 1; BOOL bAscent: 1; BOOL bSperr : 1; BOOL bSpace : 1; BOOL bNumberOfBlanks : 1; BOOL bUppr : 1; BOOL bDrawSp: 1; #endif SwDrawTextInfo( ViewShell *pS, OutputDevice &rO, const SwScriptInfo* pSI, const XubString &rSt, xub_StrLen nI, xub_StrLen nL, USHORT nW = 0, BOOL bB = FALSE ) { pFrm = NULL; pSh = pS; pOut = &rO; pScriptInfo = pSI; pText = &rSt; nIdx = nI; nLen = nL; nKern = 0; nCompress = 0; nWidth = nW; nNumberOfBlanks = 0; nCursorBidiLevel = 0; bBullet = bB; pUnderFnt = 0; bGreyWave = FALSE; bSpaceStop = FALSE; bSnapToGrid = FALSE; bIgnoreFrmRTL = FALSE; bPosMatchesBounds = FALSE; // These values are initialized but, they have to be // set explicitly via their Set-function before they may // be accessed by their Get-function: pPos = 0; pWrong = 0; pGrammarCheck = 0; pSmartTags = 0; pSize = 0; pFnt = 0; pHyphPos = 0; nLeft = 0; nRight = 0; nKanaDiff = 0; nOfst = 0; nAscent = 0; nSperren = 0; nSpace = 0; bUpper = FALSE; bDrawSpace = FALSE; #ifndef PRODUCT // these flags control, whether the matching member variables have // been set by using the Set-function before they may be accessed // by their Get-function: bPos = bWrong = bGrammarCheck = bSize = bFnt = bAscent = bSpace = bNumberOfBlanks = bUppr = bDrawSp = bLeft = bRight = bKana = bOfst = bHyph = bSperr = FALSE; #endif } const SwTxtFrm* GetFrm() const { return pFrm; } void SetFrm( const SwTxtFrm* pNewFrm ) { pFrm = pNewFrm; } ViewShell *GetShell() const { return pSh; } OutputDevice& GetOut() const { return *pOut; } OutputDevice *GetpOut() const { return pOut; } const SwScriptInfo* GetScriptInfo() const { return pScriptInfo; } const Point &GetPos() const { ASSERT( bPos, "DrawTextInfo: Undefined Position" ); return *pPos; } xub_StrLen *GetHyphPos() const { ASSERT( bHyph, "DrawTextInfo: Undefined Hyph Position" ); return pHyphPos; } const XubString &GetText() const { return *pText; } const SwWrongList* GetWrong() const { ASSERT( bWrong, "DrawTextInfo: Undefined WrongList" ); return pWrong; } const SwWrongList* GetGrammarCheck() const { ASSERT( bGrammarCheck, "DrawTextInfo: Undefined GrammarCheck List" ); return pGrammarCheck; } const SwWrongList* GetSmartTags() const { return pSmartTags; } const Size &GetSize() const { ASSERT( bSize, "DrawTextInfo: Undefined Size" ); return *pSize; } SwFont* GetFont() const { ASSERT( bFnt, "DrawTextInfo: Undefined Font" ); return pFnt; } SwUnderlineFont* GetUnderFnt() const { return pUnderFnt; } xub_StrLen GetIdx() const { return nIdx; } xub_StrLen GetLen() const { return nLen; } xub_StrLen GetOfst() const { ASSERT( bOfst, "DrawTextInfo: Undefined Offset" ); return nOfst; } xub_StrLen GetEnd() const { return nIdx + nLen; } long GetLeft() const { ASSERT( bLeft, "DrawTextInfo: Undefined left range" ); return nLeft; } long GetRight() const { ASSERT( bRight, "DrawTextInfo: Undefined right range" ); return nRight; } long GetKanaDiff() const { ASSERT( bKana, "DrawTextInfo: Undefined kana difference" ); return nKanaDiff; } USHORT GetWidth() const { return nWidth; } USHORT GetAscent() const { ASSERT( bAscent, "DrawTextInfo: Undefined Ascent" ); return nAscent; } USHORT GetKanaComp() const { return nCompress; } long GetSperren() const { ASSERT( bSperr, "DrawTextInfo: Undefined >Sperren<" ); return nSperren; } long GetKern() const { return nKern; } long GetSpace() const { ASSERT( bSpace, "DrawTextInfo: Undefined Spacing" ); return nSpace; } xub_StrLen GetNumberOfBlanks() const { ASSERT( bNumberOfBlanks, "DrawTextInfo::Undefined NumberOfBlanks" ); return nNumberOfBlanks; } BYTE GetCursorBidiLevel() const { return nCursorBidiLevel; } BOOL GetBullet() const { return bBullet; } BOOL GetUpper() const { ASSERT( bUppr, "DrawTextInfo: Undefined Upperflag" ); return bUpper; } BOOL GetDrawSpace() const { ASSERT( bDrawSp, "DrawTextInfo: Undefined DrawSpaceflag" ); return bDrawSpace; } BOOL GetGreyWave() const { return bGreyWave; } BOOL IsSpaceStop() const { return bSpaceStop; } BOOL SnapToGrid() const { return bSnapToGrid; } BOOL IsIgnoreFrmRTL() const { return bIgnoreFrmRTL; } BOOL IsPosMatchesBounds() const { return bPosMatchesBounds; } void SetOut( OutputDevice &rNew ) { pOut = &rNew; } void SetPos( const Point &rNew ) { pPos = &rNew; #ifndef PRODUCT bPos = TRUE; #endif } void SetHyphPos( xub_StrLen *pNew ) { pHyphPos = pNew; #ifndef PRODUCT bHyph = TRUE; #endif } void SetText( const XubString &rNew ) { pText = &rNew; } void SetWrong( const SwWrongList* pNew ) { pWrong = pNew; #ifndef PRODUCT bWrong = TRUE; #endif } void SetGrammarCheck( const SwWrongList* pNew ) { pGrammarCheck = pNew; #ifndef PRODUCT bGrammarCheck = TRUE; #endif } void SetSmartTags( const SwWrongList* pNew ) { pSmartTags = pNew; } void SetSize( const Size &rNew ) { pSize = &rNew; #ifndef PRODUCT bSize = TRUE; #endif } void SetFont( SwFont* pNew ) { pFnt = pNew; #ifndef PRODUCT bFnt = TRUE; #endif } void SetIdx( xub_StrLen nNew ) { nIdx = nNew; } void SetLen( xub_StrLen nNew ) { nLen = nNew; } void SetOfst( xub_StrLen nNew ) { nOfst = nNew; #ifndef PRODUCT bOfst = TRUE; #endif } void SetLeft( long nNew ) { nLeft = nNew; #ifndef PRODUCT bLeft = TRUE; #endif } void SetRight( long nNew ) { nRight = nNew; #ifndef PRODUCT bRight = TRUE; #endif } void SetKanaDiff( long nNew ) { nKanaDiff = nNew; #ifndef PRODUCT bKana = TRUE; #endif } void SetWidth( USHORT nNew ) { nWidth = nNew; } void SetAscent( USHORT nNew ) { nAscent = nNew; #ifndef PRODUCT bAscent = TRUE; #endif } void SetKern( long nNew ) { nKern = nNew; } void SetSpace( long nNew ) { if( nNew < 0 ) { nSperren = -nNew; nSpace = 0; } else { nSpace = nNew; nSperren = 0; } #ifndef PRODUCT bSpace = TRUE; bSperr = TRUE; #endif } void SetNumberOfBlanks( xub_StrLen nNew ) { #ifndef PRODUCT bNumberOfBlanks = TRUE; #endif nNumberOfBlanks = nNew; } void SetCursorBidiLevel( BYTE nNew ) { nCursorBidiLevel = nNew; } void SetKanaComp( short nNew ) { nCompress = nNew; } void SetBullet( BOOL bNew ) { bBullet = bNew; } void SetUnderFnt( SwUnderlineFont* pULFnt ) { pUnderFnt = pULFnt; } void SetUpper( BOOL bNew ) { bUpper = bNew; #ifndef PRODUCT bUppr = TRUE; #endif } void SetDrawSpace( BOOL bNew ) { bDrawSpace = bNew; #ifndef PRODUCT bDrawSp = TRUE; #endif } void SetGreyWave( BOOL bNew ) { bGreyWave = bNew; } void SetSpaceStop( BOOL bNew ) { bSpaceStop = bNew; } void SetSnapToGrid( BOOL bNew ) { bSnapToGrid = bNew; } void SetIgnoreFrmRTL( BOOL bNew ) { bIgnoreFrmRTL = bNew; } void SetPosMatchesBounds( BOOL bNew ) { bPosMatchesBounds = bNew; } void Shift( USHORT nDir ); // sets a new color at the output device if necessary // if a font is passed as argument, the change if made to the font // otherwise the font at the output device is changed // returns if the font has been changed sal_Bool ApplyAutoColor( Font* pFnt = 0 ); }; #endif <|endoftext|>
<commit_before>// Copyright (c) 2018-2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_CONTRIB_ICU_INTERNAL_HPP #define TAO_PEGTL_CONTRIB_ICU_INTERNAL_HPP #include <unicode/uchar.h> #include "../analyze_traits.hpp" #include "../../config.hpp" #include "../../type_list.hpp" #include "../../internal/enable_control.hpp" namespace TAO_PEGTL_NAMESPACE { namespace internal { namespace icu { template< typename Peek, UProperty P, bool V = true > struct binary_property { using rule_t = binary_property; using subs_t = empty_list; template< typename ParseInput > [[nodiscard]] static bool match( ParseInput& in ) noexcept( noexcept( Peek::peek( in ) ) ) { if( const auto r = Peek::peek( in ) ) { if( u_hasBinaryProperty( r.data, P ) == V ) { in.bump( r.size ); return true; } } return false; } }; template< typename Peek, UProperty P, int V > struct property_value { using rule_t = property_value; using subs_t = empty_list; template< typename ParseInput > [[nodiscard]] static bool match( ParseInput& in ) noexcept( noexcept( Peek::peek( in ) ) ) { if( const auto r = Peek::peek( in ) ) { if( u_getIntPropertyValue( r.data, P ) == V ) { in.bump( r.size ); return true; } } return false; } }; } // namespace icu template< typename Peek, UProperty P, bool V > inline constexpr bool enable_control< icu::binary_property< Peek, P, V > > = false; template< typename Peek, UProperty P, int V > inline constexpr bool enable_control< icu::property_value< Peek, P, V > > = false; } // namespace internal template< typename Name, typename Peek, UProperty P, bool V > struct analyze_traits< Name, internal::icu::binary_property< Peek, P, V > > : analyze_any_traits<> {}; template< typename Name, typename Peek, UProperty P, int V > struct analyze_traits< Name, internal::icu::property_value< Peek, P, V > > : analyze_any_traits<> {}; } // namespace TAO_PEGTL_NAMESPACE #endif <commit_msg>clang-format<commit_after>// Copyright (c) 2018-2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_CONTRIB_ICU_INTERNAL_HPP #define TAO_PEGTL_CONTRIB_ICU_INTERNAL_HPP #include <unicode/uchar.h> #include "../analyze_traits.hpp" #include "../../config.hpp" #include "../../type_list.hpp" #include "../../internal/enable_control.hpp" namespace TAO_PEGTL_NAMESPACE { namespace internal { namespace icu { template< typename Peek, UProperty P, bool V = true > struct binary_property { using rule_t = binary_property; using subs_t = empty_list; template< typename ParseInput > [[nodiscard]] static bool match( ParseInput& in ) noexcept( noexcept( Peek::peek( in ) ) ) { if( const auto r = Peek::peek( in ) ) { if( u_hasBinaryProperty( r.data, P ) == V ) { in.bump( r.size ); return true; } } return false; } }; template< typename Peek, UProperty P, int V > struct property_value { using rule_t = property_value; using subs_t = empty_list; template< typename ParseInput > [[nodiscard]] static bool match( ParseInput& in ) noexcept( noexcept( Peek::peek( in ) ) ) { if( const auto r = Peek::peek( in ) ) { if( u_getIntPropertyValue( r.data, P ) == V ) { in.bump( r.size ); return true; } } return false; } }; } // namespace icu template< typename Peek, UProperty P, bool V > inline constexpr bool enable_control< icu::binary_property< Peek, P, V > > = false; template< typename Peek, UProperty P, int V > inline constexpr bool enable_control< icu::property_value< Peek, P, V > > = false; } // namespace internal template< typename Name, typename Peek, UProperty P, bool V > struct analyze_traits< Name, internal::icu::binary_property< Peek, P, V > > : analyze_any_traits<> {}; template< typename Name, typename Peek, UProperty P, int V > struct analyze_traits< Name, internal::icu::property_value< Peek, P, V > > : analyze_any_traits<> {}; } // namespace TAO_PEGTL_NAMESPACE #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: devicehelper.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2006-12-13 14:47:31 $ * * 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_canvas.hxx" #include <canvas/debug.hxx> #include <canvas/canvastools.hxx> #include <canvas/base/linepolypolygonbase.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <vcl/canvastools.hxx> #include <basegfx/tools/canvastools.hxx> #include "devicehelper.hxx" #include "spritecanvas.hxx" #include "spritecanvashelper.hxx" #include "canvasbitmap.hxx" using namespace ::com::sun::star; namespace vclcanvas { DeviceHelper::DeviceHelper() : mpSpriteCanvas(NULL), mpBackBuffer() { } void DeviceHelper::init( Window& rOutputWindow, SpriteCanvas& rSpriteCanvas ) { rSpriteCanvas.setWindow( uno::Reference<awt::XWindow2>( VCLUnoHelper::GetInterface(&rOutputWindow), uno::UNO_QUERY_THROW) ); mpOutputWindow = &rOutputWindow; mpSpriteCanvas = &rSpriteCanvas; // setup back buffer mpBackBuffer.reset( new BackBuffer( rOutputWindow ) ); mpBackBuffer->setSize( rOutputWindow.GetOutputSizePixel() ); } geometry::RealSize2D DeviceHelper::getPhysicalResolution() { if( !mpOutputWindow ) return ::canvas::tools::createInfiniteSize2D(); // we're disposed // Map a one-by-one millimeter box to pixel const MapMode aOldMapMode( mpOutputWindow->GetMapMode() ); mpOutputWindow->SetMapMode( MapMode(MAP_MM) ); const Size aPixelSize( mpOutputWindow->LogicToPixel(Size(1,1)) ); mpOutputWindow->SetMapMode( aOldMapMode ); return ::vcl::unotools::size2DFromSize( aPixelSize ); } geometry::RealSize2D DeviceHelper::getPhysicalSize() { if( !mpOutputWindow ) return ::canvas::tools::createInfiniteSize2D(); // we're disposed // Map the pixel dimensions of the output window to millimeter const MapMode aOldMapMode( mpOutputWindow->GetMapMode() ); mpOutputWindow->SetMapMode( MapMode(MAP_MM) ); const Size aLogSize( mpOutputWindow->PixelToLogic(mpOutputWindow->GetOutputSizePixel()) ); mpOutputWindow->SetMapMode( aOldMapMode ); return ::vcl::unotools::size2DFromSize( aLogSize ); } uno::Reference< rendering::XLinePolyPolygon2D > DeviceHelper::createCompatibleLinePolyPolygon( const uno::Reference< rendering::XGraphicDevice >& , const uno::Sequence< uno::Sequence< geometry::RealPoint2D > >& points ) { if( !mpOutputWindow ) return uno::Reference< rendering::XLinePolyPolygon2D >(); // we're disposed return uno::Reference< rendering::XLinePolyPolygon2D >( new ::canvas::LinePolyPolygonBase( ::basegfx::unotools::polyPolygonFromPoint2DSequenceSequence( points ) ) ); } uno::Reference< rendering::XBezierPolyPolygon2D > DeviceHelper::createCompatibleBezierPolyPolygon( const uno::Reference< rendering::XGraphicDevice >& , const uno::Sequence< uno::Sequence< geometry::RealBezierSegment2D > >& points ) { if( !mpOutputWindow ) return uno::Reference< rendering::XBezierPolyPolygon2D >(); // we're disposed return uno::Reference< rendering::XBezierPolyPolygon2D >( new ::canvas::LinePolyPolygonBase( ::basegfx::unotools::polyPolygonFromBezier2DSequenceSequence( points ) ) ); } uno::Reference< rendering::XBitmap > DeviceHelper::createCompatibleBitmap( const uno::Reference< rendering::XGraphicDevice >& , const geometry::IntegerSize2D& size ) { if( !mpSpriteCanvas ) return uno::Reference< rendering::XBitmap >(); // we're disposed return uno::Reference< rendering::XBitmap >( new CanvasBitmap( ::vcl::unotools::sizeFromIntegerSize2D(size), false, mpSpriteCanvas ) ); } uno::Reference< rendering::XVolatileBitmap > DeviceHelper::createVolatileBitmap( const uno::Reference< rendering::XGraphicDevice >& , const geometry::IntegerSize2D& ) { return uno::Reference< rendering::XVolatileBitmap >(); } uno::Reference< rendering::XBitmap > DeviceHelper::createCompatibleAlphaBitmap( const uno::Reference< rendering::XGraphicDevice >& , const geometry::IntegerSize2D& size ) { if( !mpSpriteCanvas ) return uno::Reference< rendering::XBitmap >(); // we're disposed return uno::Reference< rendering::XBitmap >( new CanvasBitmap( ::vcl::unotools::sizeFromIntegerSize2D(size), true, mpSpriteCanvas ) ); } uno::Reference< rendering::XVolatileBitmap > DeviceHelper::createVolatileAlphaBitmap( const uno::Reference< rendering::XGraphicDevice >& , const geometry::IntegerSize2D& ) { return uno::Reference< rendering::XVolatileBitmap >(); } sal_Bool DeviceHelper::hasFullScreenMode() { // TODO(F3): offer fullscreen mode the XCanvas way return false; } sal_Bool DeviceHelper::enterFullScreenMode( sal_Bool bEnter ) { (void)bEnter; // TODO(F3): offer fullscreen mode the XCanvas way return false; } ::sal_Int32 DeviceHelper::createBuffers( ::sal_Int32 nBuffers ) { (void)nBuffers; // TODO(F3): implement XBufferStrategy interface. For now, we // _always_ will have exactly one backbuffer return 1; } void DeviceHelper::destroyBuffers() { // TODO(F3): implement XBufferStrategy interface. For now, we // _always_ will have exactly one backbuffer } ::sal_Bool DeviceHelper::showBuffer( ::sal_Bool bUpdateAll ) { // forward to sprite canvas helper if( !mpSpriteCanvas ) return false; return mpSpriteCanvas->updateScreen( bUpdateAll ); } ::sal_Bool DeviceHelper::switchBuffer( ::sal_Bool bUpdateAll ) { // no difference for VCL canvas return showBuffer( bUpdateAll ); } void DeviceHelper::disposing() { // release all references mpSpriteCanvas = NULL; mpBackBuffer.reset(); } uno::Any DeviceHelper::getDeviceHandle() const { if( !mpOutputWindow ) return uno::Any(); return uno::makeAny( reinterpret_cast< sal_Int64 >(mpOutputWindow) ); } uno::Any DeviceHelper::getSurfaceHandle() const { if( !mpBackBuffer ) return uno::Any(); return uno::makeAny( reinterpret_cast< sal_Int64 >(&mpBackBuffer->getOutDev()) ); } void DeviceHelper::notifySizeUpdate( const awt::Rectangle& rBounds ) { if( mpBackBuffer ) mpBackBuffer->setSize( ::Size(rBounds.Width, rBounds.Height) ); } void DeviceHelper::dumpScreenContent() const { static sal_uInt32 nFilePostfixCount(0); if( mpOutputWindow ) { String aFilename( String::CreateFromAscii("dbg_frontbuffer") ); aFilename += String::CreateFromInt32(nFilePostfixCount); aFilename += String::CreateFromAscii(".bmp"); SvFileStream aStream( aFilename, STREAM_STD_READWRITE ); const ::Point aEmptyPoint; bool bOldMap( mpOutputWindow->IsMapModeEnabled() ); mpOutputWindow->EnableMapMode( FALSE ); aStream << mpOutputWindow->GetBitmap(aEmptyPoint, mpOutputWindow->GetOutputSizePixel()); mpOutputWindow->EnableMapMode( bOldMap ); if( mpBackBuffer ) { String aFilename2( String::CreateFromAscii("dbg_backbuffer") ); aFilename2 += String::CreateFromInt32(nFilePostfixCount); aFilename2 += String::CreateFromAscii(".bmp"); SvFileStream aStream2( aFilename2, STREAM_STD_READWRITE ); mpBackBuffer->getOutDev().EnableMapMode( FALSE ); aStream2 << mpBackBuffer->getOutDev().GetBitmap(aEmptyPoint, mpBackBuffer->getOutDev().GetOutputSizePixel()); } ++nFilePostfixCount; } } } <commit_msg>INTEGRATION: CWS changefileheader (1.5.80); FILE MERGED 2008/03/28 16:35:16 rt 1.5.80.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: devicehelper.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_canvas.hxx" #include <canvas/debug.hxx> #include <canvas/canvastools.hxx> #include <canvas/base/linepolypolygonbase.hxx> #include <toolkit/helper/vclunohelper.hxx> #include <vcl/canvastools.hxx> #include <basegfx/tools/canvastools.hxx> #include "devicehelper.hxx" #include "spritecanvas.hxx" #include "spritecanvashelper.hxx" #include "canvasbitmap.hxx" using namespace ::com::sun::star; namespace vclcanvas { DeviceHelper::DeviceHelper() : mpSpriteCanvas(NULL), mpBackBuffer() { } void DeviceHelper::init( Window& rOutputWindow, SpriteCanvas& rSpriteCanvas ) { rSpriteCanvas.setWindow( uno::Reference<awt::XWindow2>( VCLUnoHelper::GetInterface(&rOutputWindow), uno::UNO_QUERY_THROW) ); mpOutputWindow = &rOutputWindow; mpSpriteCanvas = &rSpriteCanvas; // setup back buffer mpBackBuffer.reset( new BackBuffer( rOutputWindow ) ); mpBackBuffer->setSize( rOutputWindow.GetOutputSizePixel() ); } geometry::RealSize2D DeviceHelper::getPhysicalResolution() { if( !mpOutputWindow ) return ::canvas::tools::createInfiniteSize2D(); // we're disposed // Map a one-by-one millimeter box to pixel const MapMode aOldMapMode( mpOutputWindow->GetMapMode() ); mpOutputWindow->SetMapMode( MapMode(MAP_MM) ); const Size aPixelSize( mpOutputWindow->LogicToPixel(Size(1,1)) ); mpOutputWindow->SetMapMode( aOldMapMode ); return ::vcl::unotools::size2DFromSize( aPixelSize ); } geometry::RealSize2D DeviceHelper::getPhysicalSize() { if( !mpOutputWindow ) return ::canvas::tools::createInfiniteSize2D(); // we're disposed // Map the pixel dimensions of the output window to millimeter const MapMode aOldMapMode( mpOutputWindow->GetMapMode() ); mpOutputWindow->SetMapMode( MapMode(MAP_MM) ); const Size aLogSize( mpOutputWindow->PixelToLogic(mpOutputWindow->GetOutputSizePixel()) ); mpOutputWindow->SetMapMode( aOldMapMode ); return ::vcl::unotools::size2DFromSize( aLogSize ); } uno::Reference< rendering::XLinePolyPolygon2D > DeviceHelper::createCompatibleLinePolyPolygon( const uno::Reference< rendering::XGraphicDevice >& , const uno::Sequence< uno::Sequence< geometry::RealPoint2D > >& points ) { if( !mpOutputWindow ) return uno::Reference< rendering::XLinePolyPolygon2D >(); // we're disposed return uno::Reference< rendering::XLinePolyPolygon2D >( new ::canvas::LinePolyPolygonBase( ::basegfx::unotools::polyPolygonFromPoint2DSequenceSequence( points ) ) ); } uno::Reference< rendering::XBezierPolyPolygon2D > DeviceHelper::createCompatibleBezierPolyPolygon( const uno::Reference< rendering::XGraphicDevice >& , const uno::Sequence< uno::Sequence< geometry::RealBezierSegment2D > >& points ) { if( !mpOutputWindow ) return uno::Reference< rendering::XBezierPolyPolygon2D >(); // we're disposed return uno::Reference< rendering::XBezierPolyPolygon2D >( new ::canvas::LinePolyPolygonBase( ::basegfx::unotools::polyPolygonFromBezier2DSequenceSequence( points ) ) ); } uno::Reference< rendering::XBitmap > DeviceHelper::createCompatibleBitmap( const uno::Reference< rendering::XGraphicDevice >& , const geometry::IntegerSize2D& size ) { if( !mpSpriteCanvas ) return uno::Reference< rendering::XBitmap >(); // we're disposed return uno::Reference< rendering::XBitmap >( new CanvasBitmap( ::vcl::unotools::sizeFromIntegerSize2D(size), false, mpSpriteCanvas ) ); } uno::Reference< rendering::XVolatileBitmap > DeviceHelper::createVolatileBitmap( const uno::Reference< rendering::XGraphicDevice >& , const geometry::IntegerSize2D& ) { return uno::Reference< rendering::XVolatileBitmap >(); } uno::Reference< rendering::XBitmap > DeviceHelper::createCompatibleAlphaBitmap( const uno::Reference< rendering::XGraphicDevice >& , const geometry::IntegerSize2D& size ) { if( !mpSpriteCanvas ) return uno::Reference< rendering::XBitmap >(); // we're disposed return uno::Reference< rendering::XBitmap >( new CanvasBitmap( ::vcl::unotools::sizeFromIntegerSize2D(size), true, mpSpriteCanvas ) ); } uno::Reference< rendering::XVolatileBitmap > DeviceHelper::createVolatileAlphaBitmap( const uno::Reference< rendering::XGraphicDevice >& , const geometry::IntegerSize2D& ) { return uno::Reference< rendering::XVolatileBitmap >(); } sal_Bool DeviceHelper::hasFullScreenMode() { // TODO(F3): offer fullscreen mode the XCanvas way return false; } sal_Bool DeviceHelper::enterFullScreenMode( sal_Bool bEnter ) { (void)bEnter; // TODO(F3): offer fullscreen mode the XCanvas way return false; } ::sal_Int32 DeviceHelper::createBuffers( ::sal_Int32 nBuffers ) { (void)nBuffers; // TODO(F3): implement XBufferStrategy interface. For now, we // _always_ will have exactly one backbuffer return 1; } void DeviceHelper::destroyBuffers() { // TODO(F3): implement XBufferStrategy interface. For now, we // _always_ will have exactly one backbuffer } ::sal_Bool DeviceHelper::showBuffer( ::sal_Bool bUpdateAll ) { // forward to sprite canvas helper if( !mpSpriteCanvas ) return false; return mpSpriteCanvas->updateScreen( bUpdateAll ); } ::sal_Bool DeviceHelper::switchBuffer( ::sal_Bool bUpdateAll ) { // no difference for VCL canvas return showBuffer( bUpdateAll ); } void DeviceHelper::disposing() { // release all references mpSpriteCanvas = NULL; mpBackBuffer.reset(); } uno::Any DeviceHelper::getDeviceHandle() const { if( !mpOutputWindow ) return uno::Any(); return uno::makeAny( reinterpret_cast< sal_Int64 >(mpOutputWindow) ); } uno::Any DeviceHelper::getSurfaceHandle() const { if( !mpBackBuffer ) return uno::Any(); return uno::makeAny( reinterpret_cast< sal_Int64 >(&mpBackBuffer->getOutDev()) ); } void DeviceHelper::notifySizeUpdate( const awt::Rectangle& rBounds ) { if( mpBackBuffer ) mpBackBuffer->setSize( ::Size(rBounds.Width, rBounds.Height) ); } void DeviceHelper::dumpScreenContent() const { static sal_uInt32 nFilePostfixCount(0); if( mpOutputWindow ) { String aFilename( String::CreateFromAscii("dbg_frontbuffer") ); aFilename += String::CreateFromInt32(nFilePostfixCount); aFilename += String::CreateFromAscii(".bmp"); SvFileStream aStream( aFilename, STREAM_STD_READWRITE ); const ::Point aEmptyPoint; bool bOldMap( mpOutputWindow->IsMapModeEnabled() ); mpOutputWindow->EnableMapMode( FALSE ); aStream << mpOutputWindow->GetBitmap(aEmptyPoint, mpOutputWindow->GetOutputSizePixel()); mpOutputWindow->EnableMapMode( bOldMap ); if( mpBackBuffer ) { String aFilename2( String::CreateFromAscii("dbg_backbuffer") ); aFilename2 += String::CreateFromInt32(nFilePostfixCount); aFilename2 += String::CreateFromAscii(".bmp"); SvFileStream aStream2( aFilename2, STREAM_STD_READWRITE ); mpBackBuffer->getOutDev().EnableMapMode( FALSE ); aStream2 << mpBackBuffer->getOutDev().GetBitmap(aEmptyPoint, mpBackBuffer->getOutDev().GetOutputSizePixel()); } ++nFilePostfixCount; } } } <|endoftext|>
<commit_before>#include <cv_bridge/cv_bridge.h> #include <igvc_msgs/map.h> #include <pcl/point_cloud.h> #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> #include <ros/publisher.h> #include <ros/ros.h> #include <sensor_msgs/Image.h> #include <stdlib.h> #include <math.h> #include <Eigen/Core> #include <opencv2/core/eigen.hpp> #include <opencv2/opencv.hpp> #include <nav_msgs/Odometry.h> #include "tf/transform_datatypes.h" igvc_msgs::map msgBoi; // >> message to be sent cv_bridge::CvImage img_bridge; sensor_msgs::Image imageBoi; // >> image in the message ros::Publisher map_pub; ros::Publisher debug_pub; ros::Subscriber odom_sub; ros::Publisher debug_pcl_pub; cv::Mat *published_map; // matrix will be publishing std::map<std::string, tf::StampedTransform> transforms; tf::TransformListener *tf_listener; std::string topics; Eigen::Map<Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic>> *eigenRep; double resolution; double orientation; int start_x; // start x location int start_y; // start y location int length_y; int width_x; bool debug; double cur_x; double cur_y; std::tuple<double, double> rotate(double x, double y) { double newX = x * cos(orientation) + y * -1 * sin(orientation); double newY = x * sin(orientation) + y * cos(orientation); return (std::make_tuple(newX, newY)); } void odom_callback(const nav_msgs::Odometry::ConstPtr &msg) { cur_x = msg->pose.pose.position.x; cur_y = msg->pose.pose.position.y; tf::Quaternion quat; tf::quaternionMsgToTF(msg->pose.pose.orientation, quat); double roll, pitch, yaw; tf::Matrix3x3(quat).getRPY(roll, pitch, yaw); ROS_INFO_STREAM("orientation " << yaw); orientation = yaw; } void frame_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic) { // transform pointcloud into the occupancy grid, no filtering right now bool offMap = false; int count = 0; // make transformed clouds pcl::PointCloud<pcl::PointXYZ>::Ptr transformed = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>()); ros::Time time = ros::Time::now(); if(transforms.find(topic) == transforms.end()) { if(tf_listener->waitForTransform("/base_footprint", msg->header.frame_id, ros::Time(0), ros::Duration(3.0))) { ROS_INFO_STREAM("\n\ngetting transform for " << topic << "\n\n"); tf::StampedTransform transform; tf_listener->lookupTransform("/base_footprint", msg->header.frame_id, ros::Time(0), transform); transforms.insert(std::pair<std::string, tf::StampedTransform>(topic, transform)); } else { ROS_ERROR_STREAM("\n\nfailed to find transform using empty transform\n\n"); tf::StampedTransform transform; transform.setOrigin(tf::Vector3(0.0, 0.0, 0.0)); tf::Quaternion q; q.setRPY(0, 0, 0); transform.setRotation(q); transform.child_frame_id_ = "/base_footprint"; transform.frame_id_ = "/lidar"; transform.stamp_ = ros::Time::now(); transforms.insert(std::pair<std::string, tf::StampedTransform>(topic, transform)); } } pcl_ros::transformPointCloud(*msg, *transformed, transforms.at(topic)); pcl::PointCloud<pcl::PointXYZ>::const_iterator point; for (point = transformed->begin(); point < transformed->points.end(); point++) { //ROS_INFO_STREAM("points starts at " << point->x << "," << point->y); double x_loc, y_loc; std::tie(x_loc, y_loc) = rotate(point->x, point->y); //ROS_INFO_STREAM("rotated " << x_loc << "," << y_loc); int point_x = static_cast<int>(std::round(x_loc / resolution + cur_x / resolution + start_x)); int point_y = static_cast<int>(std::round(y_loc / resolution + cur_y / resolution + start_y)); //ROS_INFO_STREAM("point = " << point_x << "," << point_y); if (point_x >= 0 && point_y >= 0 && point_x < length_y && start_y < width_x) { //ROS_INFO_STREAM("putting point at " << point_x << "," << point_y); published_map->at<uchar>(point_x, point_y) = (uchar)255; count++; } else if (!offMap) { ROS_WARN_STREAM("Some points out of range, won't be put on map."); offMap = true; } } published_map->at<uchar>(start_x + cur_x / resolution, start_y + cur_y / resolution) = (uchar)100; // make image message from img bridge img_bridge = cv_bridge::CvImage(msgBoi.header, sensor_msgs::image_encodings::MONO8, *published_map); img_bridge.toImageMsg(imageBoi); // from cv_bridge to sensor_msgs::Image time = ros::Time::now(); // so times are exact same imageBoi.header.stamp = time; // set fields of map message msgBoi.header.stamp = time; msgBoi.image = imageBoi; msgBoi.length = length_y; msgBoi.width = width_x; msgBoi.resolution = resolution; msgBoi.orientation = orientation; map_pub.publish(msgBoi); if (debug) { debug_pub.publish(imageBoi); ROS_INFO_STREAM("\nThe robot is located at " << cur_x << "," << cur_y << "," << orientation); pcl::PointCloud<pcl::PointXYZRGB>::Ptr fromOcuGrid= pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>()); for(int i = 0; i < width_x; i++){ // init frame so edges are easily visible for(int j = 0; j < length_y; j++){ if(published_map->at<uchar>(i, j) == (uchar)255) { pcl::PointXYZRGB p(255, published_map->at<uchar>(i, j), published_map->at<uchar>(i, j)); p.x = (i - start_x) * resolution; p.y = (j - start_y) * resolution; fromOcuGrid->points.push_back(p); } } } fromOcuGrid->header.frame_id = "/odom"; fromOcuGrid->header.stamp = msg->header.stamp; debug_pcl_pub.publish(fromOcuGrid); } } int main(int argc, char **argv) { ros::init(argc, argv, "new_mapper"); ros::NodeHandle nh; ros::NodeHandle pNh("~"); std::list<ros::Subscriber> subs; tf_listener = new tf::TransformListener(); double cont_start_x; double cont_start_y; if(!pNh.hasParam("topics") && !pNh.hasParam("occupancy_grid_length") && !pNh.hasParam("occupancy_grid_length") && !pNh.hasParam("occupancy_grid_resolution") && !pNh.hasParam("start_X") & !pNh.hasParam("start_Y") && !pNh.hasParam("debug")) { ROS_ERROR_STREAM("missing parameters exiting"); return 0; } // assumes all params inputted in meters pNh.getParam("topics", topics); pNh.getParam("occupancy_grid_length", length_y); pNh.getParam("occupancy_grid_width", width_x); pNh.getParam("occupancy_grid_resolution", resolution); pNh.getParam("start_X", cont_start_x); pNh.getParam("start_Y", cont_start_y); pNh.getParam("orientation", orientation); pNh.getParam("debug", debug); // convert from meters to grid length_y = (int)std::round(length_y / resolution); width_x = (int)std::round(width_x / resolution); start_x = (int)std::round(cont_start_x / resolution); start_y = (int)std::round(cont_start_y / resolution); ROS_INFO_STREAM("cv::Mat length: " << length_y << " width: " << width_x << " resolution: " << resolution); // set up tokens and get list of subscribers std::istringstream iss(topics); std::vector<std::string> tokens{ std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>() }; odom_sub = nh.subscribe("/odometry/filtered", 1, odom_callback); for (std::string topic : tokens) { ROS_INFO_STREAM("Mapper subscribing to " << topic); subs.push_back(nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>(topic, 1, boost::bind(frame_callback, _1, topic))); } published_map = new cv::Mat(length_y, width_x, CV_8UC1); eigenRep = new Eigen::Map<Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic>>( (unsigned char *)published_map, width_x, length_y); map_pub = nh.advertise<igvc_msgs::map>("/map", 1); if (debug) { debug_pub = nh.advertise<sensor_msgs::Image>("/map_debug", 1); debug_pcl_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("/map_debug_pcl", 1); /*for(int i = 0; i < width_x; i++){ // init frame so edges are easily visible for(int j = 0; j < length_y; j++){ if(i == 0 || i == width_x - 1 || j == 0 || j == length_y - 1) { published_map->at<uchar>(i, j) = (uchar)255; } } }*/ } ros::spin(); } <commit_msg>fixed issues with mapper not publishing current location<commit_after>#include <cv_bridge/cv_bridge.h> #include <igvc_msgs/map.h> #include <pcl/point_cloud.h> #include <pcl_ros/point_cloud.h> #include <pcl_ros/transforms.h> #include <ros/publisher.h> #include <ros/ros.h> #include <sensor_msgs/Image.h> #include <stdlib.h> #include <math.h> #include <Eigen/Core> #include <opencv2/core/eigen.hpp> #include <opencv2/opencv.hpp> #include <nav_msgs/Odometry.h> #include "tf/transform_datatypes.h" igvc_msgs::map msgBoi; // >> message to be sent cv_bridge::CvImage img_bridge; sensor_msgs::Image imageBoi; // >> image in the message ros::Publisher map_pub; ros::Publisher debug_pub; ros::Subscriber odom_sub; ros::Publisher debug_pcl_pub; cv::Mat *published_map; // matrix will be publishing std::map<std::string, tf::StampedTransform> transforms; tf::TransformListener *tf_listener; std::string topics; Eigen::Map<Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic>> *eigenRep; double resolution; double orientation; int start_x; // start x location int start_y; // start y location int length_y; int width_x; bool debug; double cur_x; double cur_y; bool update = true; std::tuple<double, double> rotate(double x, double y) { double newX = x * cos(orientation) + y * -1 * sin(orientation); double newY = x * sin(orientation) + y * cos(orientation); return (std::make_tuple(newX, newY)); } void odom_callback(const nav_msgs::Odometry::ConstPtr &msg) { if(update) { cur_x = msg->pose.pose.position.x; cur_y = msg->pose.pose.position.y; tf::Quaternion quat; tf::quaternionMsgToTF(msg->pose.pose.orientation, quat); double roll, pitch, yaw; tf::Matrix3x3(quat).getRPY(roll, pitch, yaw); orientation = yaw; update = false; } } void frame_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic) { // transform pointcloud into the occupancy grid, no filtering right now bool offMap = false; int count = 0; // make transformed clouds pcl::PointCloud<pcl::PointXYZ>::Ptr transformed = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>()); ros::Time time = ros::Time::now(); if(transforms.find(topic) == transforms.end()) { if(tf_listener->waitForTransform("/base_footprint", msg->header.frame_id, ros::Time(0), ros::Duration(3.0))) { ROS_INFO_STREAM("\n\ngetting transform for " << topic << "\n\n"); tf::StampedTransform transform; tf_listener->lookupTransform("/base_footprint", msg->header.frame_id, ros::Time(0), transform); transforms.insert(std::pair<std::string, tf::StampedTransform>(topic, transform)); } else { ROS_ERROR_STREAM("\n\nfailed to find transform using empty transform\n\n"); tf::StampedTransform transform; transform.setOrigin(tf::Vector3(0.0, 0.0, 0.0)); tf::Quaternion q; q.setRPY(0, 0, 0); transform.setRotation(q); transform.child_frame_id_ = "/base_footprint"; transform.frame_id_ = "/lidar"; transform.stamp_ = ros::Time::now(); transforms.insert(std::pair<std::string, tf::StampedTransform>(topic, transform)); } } pcl_ros::transformPointCloud(*msg, *transformed, transforms.at(topic)); pcl::PointCloud<pcl::PointXYZ>::const_iterator point; for (point = transformed->begin(); point < transformed->points.end(); point++) { //ROS_INFO_STREAM("points starts at " << point->x << "," << point->y); double x_loc, y_loc; std::tie(x_loc, y_loc) = rotate(point->x, point->y); //ROS_INFO_STREAM("rotated " << x_loc << "," << y_loc); int point_x = static_cast<int>(std::round(x_loc / resolution + cur_x / resolution + start_x)); int point_y = static_cast<int>(std::round(y_loc / resolution + cur_y / resolution + start_y)); //ROS_INFO_STREAM("point = " << point_x << "," << point_y); if (point_x >= 0 && point_y >= 0 && point_x < length_y && start_y < width_x) { //ROS_INFO_STREAM("putting point at " << point_x << "," << point_y); published_map->at<uchar>(point_x, point_y) = (uchar)255; count++; } else if (!offMap) { ROS_WARN_STREAM("Some points out of range, won't be put on map."); offMap = true; } } published_map->at<uchar>(start_x + cur_x / resolution, start_y + cur_y / resolution) = (uchar)100; // make image message from img bridge img_bridge = cv_bridge::CvImage(msgBoi.header, sensor_msgs::image_encodings::MONO8, *published_map); img_bridge.toImageMsg(imageBoi); // from cv_bridge to sensor_msgs::Image time = ros::Time::now(); // so times are exact same imageBoi.header.stamp = time; // set fields of map message msgBoi.header.stamp = time; msgBoi.image = imageBoi; msgBoi.length = length_y; msgBoi.width = width_x; msgBoi.resolution = resolution; msgBoi.orientation = orientation; ROS_INFO_STREAM("robot location " << cur_x / resolution << ", " << cur_y / resolution); msgBoi.x = std::round(cur_x / resolution); msgBoi.y = std::round(cur_y / resolution); map_pub.publish(msgBoi); if (debug) { debug_pub.publish(imageBoi); //ROS_INFO_STREAM("\nThe robot is located at " << cur_x << "," << cur_y << "," << orientation); pcl::PointCloud<pcl::PointXYZRGB>::Ptr fromOcuGrid= pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>()); for(int i = 0; i < width_x; i++){ // init frame so edges are easily visible for(int j = 0; j < length_y; j++){ if(published_map->at<uchar>(i, j) == (uchar)255) { pcl::PointXYZRGB p(255, published_map->at<uchar>(i, j), published_map->at<uchar>(i, j)); p.x = (i - start_x) * resolution; p.y = (j - start_y) * resolution; fromOcuGrid->points.push_back(p); } } } fromOcuGrid->header.frame_id = "/odom"; fromOcuGrid->header.stamp = msg->header.stamp; debug_pcl_pub.publish(fromOcuGrid); } update = true; } int main(int argc, char **argv) { ros::init(argc, argv, "new_mapper"); ros::NodeHandle nh; ros::NodeHandle pNh("~"); std::list<ros::Subscriber> subs; tf_listener = new tf::TransformListener(); double cont_start_x; double cont_start_y; if(!pNh.hasParam("topics") && !pNh.hasParam("occupancy_grid_length") && !pNh.hasParam("occupancy_grid_length") && !pNh.hasParam("occupancy_grid_resolution") && !pNh.hasParam("start_X") & !pNh.hasParam("start_Y") && !pNh.hasParam("debug")) { ROS_ERROR_STREAM("missing parameters exiting"); return 0; } // assumes all params inputted in meters pNh.getParam("topics", topics); pNh.getParam("occupancy_grid_length", length_y); pNh.getParam("occupancy_grid_width", width_x); pNh.getParam("occupancy_grid_resolution", resolution); pNh.getParam("start_X", cont_start_x); pNh.getParam("start_Y", cont_start_y); pNh.getParam("orientation", orientation); pNh.getParam("debug", debug); // convert from meters to grid length_y = (int)std::round(length_y / resolution); width_x = (int)std::round(width_x / resolution); start_x = (int)std::round(cont_start_x / resolution); start_y = (int)std::round(cont_start_y / resolution); ROS_INFO_STREAM("cv::Mat length: " << length_y << " width: " << width_x << " resolution: " << resolution); // set up tokens and get list of subscribers std::istringstream iss(topics); std::vector<std::string> tokens{ std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>() }; odom_sub = nh.subscribe("/odometry/filtered", 1, odom_callback); for (std::string topic : tokens) { ROS_INFO_STREAM("Mapper subscribing to " << topic); subs.push_back(nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>(topic, 1, boost::bind(frame_callback, _1, topic))); } published_map = new cv::Mat(length_y, width_x, CV_8UC1); eigenRep = new Eigen::Map<Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic>>( (unsigned char *)published_map, width_x, length_y); map_pub = nh.advertise<igvc_msgs::map>("/map", 1); if (debug) { debug_pub = nh.advertise<sensor_msgs::Image>("/map_debug", 1); debug_pcl_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>("/map_debug_pcl", 1); /*for(int i = 0; i < width_x; i++){ // init frame so edges are easily visible for(int j = 0; j < length_y; j++){ if(i == 0 || i == width_x - 1 || j == 0 || j == length_y - 1) { published_map->at<uchar>(i, j) = (uchar)255; } } }*/ } ros::spin(); } <|endoftext|>
<commit_before> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2017 Igor Mironchik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CFGFILE__TAG_SCALAR_VECTOR_HPP__INCLUDED #define CFGFILE__TAG_SCALAR_VECTOR_HPP__INCLUDED //cfgfile include. #include "tag.hpp" #include "constraint.hpp" #include "format.hpp" #include "string_format.hpp" #include "types.hpp" #include "exceptions.hpp" #include "parser_info.hpp" #if defined( CFGFILE_string_t_BUILD ) && defined( CFGFILE_XML_SUPPORT ) // Qt include. #include <QDomDocument> #include <QDomElement> #include <QDomText> #endif // C++ include. #include <vector> namespace cfgfile { // // tag_scalar_vector_t // //! Tag with multiple scalar values. template< class T > class tag_scalar_vector_t : public tag_t { public: typedef std::vector< T > values_vector_t; explicit tag_scalar_vector_t( const string_t & name, bool is_mandatory = false ) : tag_t( name, is_mandatory ) , m_constraint( nullptr ) { } tag_scalar_vector_t( tag_t & owner, const string_t & name, bool is_mandatory = false ) : tag_t( owner, name, is_mandatory ) , m_constraint( nullptr ) { } ~tag_scalar_vector_t() { } //! \return Amount of the values. typename values_vector_t::size_type size() const { return m_values.size(); } //! \return Value with the given index. const T & at( typename values_vector_t::size_type index ) const { return m_values.at( index ); } //! \return All values. const values_vector_t & values() const { return m_values; } /*! Set value. Repeatly adds value to the end of vector. */ void set_value( const T & v ) { if( m_constraint ) { if( !m_constraint->check( v ) ) throw exception_t< Trait >( string_t( Trait::from_ascii( "Invalid value: \"" ) ) + string_t( format_t< T >::to_string( v ) ) + Trait::from_ascii( "\". Value must match to the constraint in tag \"" ) + name() + Trait::from_ascii( "\"." ) ); } m_values.push_back( v ); set_defined(); } //! Set values. void set_values( const values_vector_t & v ) { m_values = v; set_defined(); } /*! Query optional values. If isDefined() is true then \a receiver will be initialized with values of the tag, otherwise nothing with \a receiver will happen. */ void query_opt_values( values_vector_t & receiver ) { if( is_defined() ) receiver = m_values; } //! Set constraint for the tag's value. void set_constraint( constraint_t< T > * c ) { m_constraint = c; } //! Print tag to the output. string_t print( int indent = 0 ) const override { string_t result; if( is_defined() ) { result.append( string_t( indent, const_t< Trait >::c_tab ) ); result.push_back( const_t< Trait >::c_begin_tag ); result.append( name() ); for( const T & v : m_values ) { result.push_back( const_t< Trait >::c_space ); string_t value = format_t< T >::to_string( v ); value = to_cfgfile_format( value ); result.append( value ); } if( !children().empty() ) { result.push_back( const_t< Trait >::c_carriage_return ); for( const tag_t * tag : children() ) result.append( tag->print( indent + 1 ) ); result.append( string_t( indent, const_t< Trait >::c_tab ) ); } result.push_back( const_t< Trait >::c_end_tag ); result.push_back( const_t< Trait >::c_carriage_return ); } return result; } #if defined( CFGFILE_QT_SUPPORT ) && defined( CFGFILE_XML_SUPPORT ) //! Print tag to the output. void print( QDomDocument & doc, QDomElement * parent = 0 ) const override { if( is_defined() ) { QDomElement this_element = doc.createElement( name() ); if( !parent ) doc.appendChild( this_element ); else parent->appendChild( this_element ); typename values_vector_t::size_type i = 1; for( const T & v : m_values ) { string_t value = format_t< T >::to_string( v ); value = to_cfgfile_format( value ); QString tmp = value; if( tmp.startsWith( const_t< Trait >::c_quotes ) && tmp.endsWith( const_t< Trait >::c_quotes ) ) tmp = tmp.mid( 1, tmp.length() - 2 ); this_element.setAttribute( QString( "a" ) + QString::number( i ), tmp ); ++i; } if( !children().empty() ) { for( const tag_t * tag : children() ) tag->print( doc, &this_element ); } } } #endif //! Called when tag parsing finished. void on_finish( const parser_info_t< Trait > & info ) override { for( const tag_t * tag : children() ) { if( tag->is_mandatory() && !tag->is_defined() ) throw exception_t< Trait >( string_t( Trait::from_ascii( "Undefined child mandatory tag: \"" ) ) + tag->name() + Trait::from_ascii( "\". Where parent is: \"" ) + name() + Trait::from_ascii( "\". In file \"" ) + info.file_name() + Trait::from_ascii( "\" on line " ) + Trait::to_string( info.line_number() ) + Trait::from_ascii( "." ) ); } } //! Called when string found. void on_string( const parser_info_t< Trait > & info, const string_t & str ) override { if( is_any_child_defined() ) throw exception_t< Trait >( string_t( Trait::from_ascii( "Value \"" ) ) + str + Trait::from_ascii( "\" for tag \"" ) + name() + Trait::from_ascii( "\" must be defined before any child tag. In file \"" ) + info.file_name() + Trait::from_ascii( "\" on line " ) + Trait::to_string( info.line_number() ) + Trait::from_ascii( "." ) ); const T value = format_t< T >::from_string( info, str ); if( m_constraint ) { if( !m_constraint->check( value ) ) throw exception_t< Trait >( string_t( Trait::from_ascii( "Invalid value: \"" ) ) + str + Trait::from_ascii( "\". Value must match to the constraint in tag \"" ) + name() + Trait::from_ascii( "\". In file \"" ) + info.file_name() + Trait::from_ascii( "\" on line " ) + Trait::to_string( info.line_number() ) + Trait::from_ascii( "." ) ); } m_values.push_back( value ); set_defined(); } private: //! Value of the tag. values_vector_t m_values; //! Constraint. constraint_t< T > * m_constraint; }; // class tag_scalar_vector_t } /* namespace cfgfile */ #endif // CFGFILE__TAG_SCALAR_VECTOR_HPP__INCLUDED <commit_msg>Converted tag_scalar.hpp<commit_after> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2017 Igor Mironchik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CFGFILE__TAG_SCALAR_VECTOR_HPP__INCLUDED #define CFGFILE__TAG_SCALAR_VECTOR_HPP__INCLUDED //cfgfile include. #include "tag.hpp" #include "constraint.hpp" #include "format.hpp" #include "string_format.hpp" #include "types.hpp" #include "exceptions.hpp" #include "parser_info.hpp" #if defined( CFGFILE_QT_SUPPORT ) && defined( CFGFILE_XML_SUPPORT ) // Qt include. #include <QDomDocument> #include <QDomElement> #include <QDomText> #endif // C++ include. #include <vector> namespace cfgfile { // // tag_scalar_vector_t // //! Tag with multiple scalar values. template< class T, class Trait > class tag_scalar_vector_t : public tag_t< Trait > { public: typedef std::vector< T > values_vector_t; explicit tag_scalar_vector_t( const Trait::string_t & name, bool is_mandatory = false ) : tag_t< Trait >( name, is_mandatory ) , m_constraint( nullptr ) { } tag_scalar_vector_t( tag_t< Trait > & owner, const Trait::string_t & name, bool is_mandatory = false ) : tag_t< Trait >( owner, name, is_mandatory ) , m_constraint( nullptr ) { } ~tag_scalar_vector_t() { } //! \return Amount of the values. typename values_vector_t::size_type size() const { return m_values.size(); } //! \return Value with the given index. const T & at( typename values_vector_t::size_type index ) const { return m_values.at( index ); } //! \return All values. const values_vector_t & values() const { return m_values; } /*! Set value. Repeatly adds value to the end of vector. */ void set_value( const T & v ) { if( m_constraint ) { if( !m_constraint->check( v ) ) throw exception_t< Trait >( Trait::from_ascii( "Invalid value: \"" ) + Trait::string_t( format_t< T >::to_string( v ) ) + Trait::from_ascii( "\". Value must match to the constraint in tag \"" ) + name() + Trait::from_ascii( "\"." ) ); } m_values.push_back( v ); set_defined(); } //! Set values. void set_values( const values_vector_t & v ) { m_values = v; set_defined(); } /*! Query optional values. If isDefined() is true then \a receiver will be initialized with values of the tag, otherwise nothing with \a receiver will happen. */ void query_opt_values( values_vector_t & receiver ) { if( is_defined() ) receiver = m_values; } //! Set constraint for the tag's value. void set_constraint( constraint_t< T > * c ) { m_constraint = c; } //! Print tag to the output. Trait::string_t print( int indent = 0 ) const override { Trait::string_t result; if( is_defined() ) { result.append( Trait::string_t( indent, const_t< Trait >::c_tab ) ); result.push_back( const_t< Trait >::c_begin_tag ); result.append( name() ); for( const T & v : m_values ) { result.push_back( const_t< Trait >::c_space ); Trait::string_t value = format_t< T >::to_string( v ); value = to_cfgfile_format( value ); result.append( value ); } if( !children().empty() ) { result.push_back( const_t< Trait >::c_carriage_return ); for( const tag_t< Trait > * tag : children() ) result.append( tag->print( indent + 1 ) ); result.append( Trait::string_t( indent, const_t< Trait >::c_tab ) ); } result.push_back( const_t< Trait >::c_end_tag ); result.push_back( const_t< Trait >::c_carriage_return ); } return result; } #if defined( CFGFILE_QT_SUPPORT ) && defined( CFGFILE_XML_SUPPORT ) //! Print tag to the output. void print( QDomDocument & doc, QDomElement * parent = 0 ) const override { if( is_defined() ) { QDomElement this_element = doc.createElement( name() ); if( !parent ) doc.appendChild( this_element ); else parent->appendChild( this_element ); typename values_vector_t::size_type i = 1; for( const T & v : m_values ) { Trait::string_t value = format_t< T >::to_string( v ); value = to_cfgfile_format( value ); QString tmp = value; if( tmp.startsWith( const_t< Trait >::c_quotes ) && tmp.endsWith( const_t< Trait >::c_quotes ) ) tmp = tmp.mid( 1, tmp.length() - 2 ); this_element.setAttribute( QString( "a" ) + QString::number( i ), tmp ); ++i; } if( !children().empty() ) { for( const tag_t< Trait > * tag : children() ) tag->print( doc, &this_element ); } } } #endif //! Called when tag parsing finished. void on_finish( const parser_info_t< Trait > & info ) override { for( const tag_t< Trait > * tag : children() ) { if( tag->is_mandatory() && !tag->is_defined() ) throw exception_t< Trait >( Trait::from_ascii( "Undefined child mandatory tag: \"" ) + tag->name() + Trait::from_ascii( "\". Where parent is: \"" ) + name() + Trait::from_ascii( "\". In file \"" ) + info.file_name() + Trait::from_ascii( "\" on line " ) + Trait::to_string( info.line_number() ) + Trait::from_ascii( "." ) ); } } //! Called when string found. void on_string( const parser_info_t< Trait > & info, const Trait::string_t & str ) override { if( is_any_child_defined() ) throw exception_t< Trait >( Trait::from_ascii( "Value \"" ) + str + Trait::from_ascii( "\" for tag \"" ) + name() + Trait::from_ascii( "\" must be defined before any child tag. In file \"" ) + info.file_name() + Trait::from_ascii( "\" on line " ) + Trait::to_string( info.line_number() ) + Trait::from_ascii( "." ) ); const T value = format_t< T, Trait >::from_string( info, str ); if( m_constraint ) { if( !m_constraint->check( value ) ) throw exception_t< Trait >( Trait::from_ascii( "Invalid value: \"" ) + str + Trait::from_ascii( "\". Value must match to the constraint in tag \"" ) + name() + Trait::from_ascii( "\". In file \"" ) + info.file_name() + Trait::from_ascii( "\" on line " ) + Trait::to_string( info.line_number() ) + Trait::from_ascii( "." ) ); } m_values.push_back( value ); set_defined(); } private: //! Value of the tag. values_vector_t m_values; //! Constraint. constraint_t< T > * m_constraint; }; // class tag_scalar_vector_t } /* namespace cfgfile */ #endif // CFGFILE__TAG_SCALAR_VECTOR_HPP__INCLUDED <|endoftext|>
<commit_before>/* cperf_type_lookup_test.cpp -*- C++ -*- Rémi Attab ([email protected]), 12 Apr 2014 FreeBSD-style copyright and disclaimer apply Used to tests the complexity of type lookups within the compiler. In other words, if we have thousands of reflected types in our project, what's the overhead of looking up one of those types. gcc 4.7 seems to have a complexity of O(1) as was expected. */ #include "reflect.h" #include <boost/test/unit_test.hpp> using namespace reflect; #define reflectThing1Impl(name) \ struct name {}; \ reflectClassDecl(name) #define reflectThing1() \ reflectThing1Impl(reflectUniqueName(Thing)) #define reflectThing10() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() #define reflectThing100() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() #define reflectThing1000() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() reflectThing1000() struct Target {}; reflectClass(Target) {} int main(int, char**) { (void) type<Target>(); (void) type<Thing_100>(); } <commit_msg>cperf: type lookup will run without crashing.<commit_after>/* cperf_type_lookup_test.cpp -*- C++ -*- Rémi Attab ([email protected]), 12 Apr 2014 FreeBSD-style copyright and disclaimer apply Used to tests the complexity of type lookups within the compiler. In other words, if we have thousands of reflected types in our project, what's the overhead of looking up one of those types. gcc 4.7 seems to have a complexity of O(1) as was expected. */ #include "reflect.h" #include <boost/test/unit_test.hpp> using namespace reflect; /******************************************************************************/ /* REFLECT THING */ /******************************************************************************/ #define reflectThing1Impl(name) \ struct name {}; \ reflectClassDecl(name) #define reflectThing1() \ reflectThing1Impl(reflectUniqueName(Thing)) #define reflectThing10() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() \ reflectThing1() #define reflectThing100() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() \ reflectThing10() #define reflectThing1000() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() \ reflectThing100() /******************************************************************************/ /* MAIN */ /******************************************************************************/ reflectThing1000() struct Target {}; reflectClass(Target) {} int main(int, char**) { (void) type<Target>(); } <|endoftext|>
<commit_before>//---------------------------- dof_renumbering.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2000, 2001 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- dof_renumbering.cc --------------------------- /* Author: Wolfgang Bangerth, University of Heidelberg, 2001 */ #include <base/logstream.h> #include <base/function_lib.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_iterator.h> #include <dofs/dof_accessor.h> #include <grid/grid_generator.h> #include <dofs/dof_handler.h> #include <fe/fe_q.h> #include <fe/fe_dgq.h> #include <fe/fe_system.h> #include <numerics/dof_renumbering.h> #include <fstream> template <int dim> void print_dofs (const DoFHandler<dim> &dof) { std::vector<unsigned int> v (dof.get_fe().dofs_per_cell); for (typename DoFHandler<dim>::active_cell_iterator cell=dof.begin_active(); cell != dof.end(); ++cell) { deallog << "Cell " << cell << " -- "; cell->get_dof_indices (v); for (unsigned int i=0; i<v.size(); ++i) deallog << v[i] << ' '; deallog << std::endl; } } template <int dim> void check () { Functions::CosineFunction<dim> cosine; Triangulation<dim> tr; if (dim==2) GridGenerator::hyper_ball(tr, Point<dim>(), 1); else GridGenerator::hyper_cube(tr, -1,1); tr.refine_global (1); tr.begin_active()->set_refine_flag (); tr.execute_coarsening_and_refinement (); if (dim==1) tr.refine_global(2); FESystem<dim> element (FE_Q<dim>(2), 2, FE_DGQ<dim>(1), 1); DoFHandler<dim> dof(tr); dof.distribute_dofs(element); print_dofs (dof); DoFRenumbering::Cuthill_McKee (dof); print_dofs (dof); DoFRenumbering::Cuthill_McKee (dof, true); print_dofs (dof); DoFRenumbering::Cuthill_McKee (dof, true, true); print_dofs (dof); std::vector<unsigned int> order(element.n_components()); for (unsigned int i=0; i<order.size(); ++i) order[i] = order.size()-i-1; DoFRenumbering::component_wise (dof, order); print_dofs (dof); std::vector<bool> selected_dofs (dof.n_dofs(), false); for (unsigned int i=0; i<dof.n_dofs(); ++i) if (i%2==0) selected_dofs[i] = true; DoFRenumbering::sort_selected_dofs_back (dof, selected_dofs); print_dofs (dof); } int main () { std::ofstream logfile ("dof_renumbering.output"); logfile.precision (2); logfile.setf(std::ios::fixed); deallog.attach(logfile); deallog.depth_console (0); deallog.push ("1d"); check<1> (); deallog.pop (); deallog.push ("2d"); check<2> (); deallog.pop (); deallog.push ("3d"); check<3> (); deallog.pop (); } <commit_msg>tests for multilevel numbering added<commit_after>//---------------------------- dof_renumbering.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2000, 2001 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- dof_renumbering.cc --------------------------- /* Author: Wolfgang Bangerth, University of Heidelberg, 2001 */ #include <base/logstream.h> #include <base/function_lib.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_iterator.h> #include <grid/grid_generator.h> #include <dofs/dof_accessor.h> #include <dofs/dof_handler.h> #include <multigrid/mg_dof_accessor.h> #include <multigrid/mg_dof_handler.h> #include <fe/fe_q.h> #include <fe/fe_dgq.h> #include <fe/fe_system.h> #include <numerics/dof_renumbering.h> #include <fstream> template <int dim> void print_dofs (const DoFHandler<dim> &dof) { std::vector<unsigned int> v (dof.get_fe().dofs_per_cell); for (typename DoFHandler<dim>::active_cell_iterator cell=dof.begin_active(); cell != dof.end(); ++cell) { deallog << "Cell " << cell << " -- "; cell->get_dof_indices (v); for (unsigned int i=0; i<v.size(); ++i) deallog << v[i] << ' '; deallog << std::endl; } } template <int dim> void print_dofs (const MGDoFHandler<dim> &dof, unsigned int level) { std::vector<unsigned int> v (dof.get_fe().dofs_per_cell); for (typename MGDoFHandler<dim>::cell_iterator cell=dof.begin(level); cell != dof.end(level); ++cell) { deallog << "Cell " << cell << " -- "; cell->get_mg_dof_indices (v); for (unsigned int i=0; i<v.size(); ++i) deallog << v[i] << ' '; deallog << std::endl; } } template <int dim> void check () { Functions::CosineFunction<dim> cosine; Triangulation<dim> tr; if (dim==2) GridGenerator::hyper_ball(tr, Point<dim>(), 1); else GridGenerator::hyper_cube(tr, -1,1); tr.refine_global (1); tr.begin_active()->set_refine_flag (); tr.execute_coarsening_and_refinement (); if (dim==1) tr.refine_global(2); FESystem<dim> element (FE_Q<dim>(2), 2, FE_DGQ<dim>(1), 1); MGDoFHandler<dim> mgdof(tr); DoFHandler<dim>& dof = mgdof; dof.distribute_dofs(element); // Prepare a reordering of // components for later use std::vector<unsigned int> order(element.n_components()); for (unsigned int i=0; i<order.size(); ++i) order[i] = order.size()-i-1; // Check global ordering print_dofs (dof); DoFRenumbering::Cuthill_McKee (dof); print_dofs (dof); DoFRenumbering::Cuthill_McKee (dof, true); print_dofs (dof); DoFRenumbering::Cuthill_McKee (dof, true, true); print_dofs (dof); DoFRenumbering::component_wise (dof, order); print_dofs (dof); std::vector<bool> selected_dofs (dof.n_dofs(), false); for (unsigned int i=0; i<dof.n_dofs(); ++i) if (i%2==0) selected_dofs[i] = true; DoFRenumbering::sort_selected_dofs_back (dof, selected_dofs); print_dofs (dof); // Check level ordering for (unsigned int level=0;level<tr.n_levels();++level) { print_dofs (mgdof, level); // Reinsert after fixing // DoFRenumbering::Cuthill_McKee (mgdof, level); // print_dofs (mgdof, level); // DoFRenumbering::Cuthill_McKee (mgdof, level, true); // print_dofs (mgdof, level); DoFRenumbering::component_wise (mgdof, order); print_dofs (mgdof, level); } } int main () { std::ofstream logfile ("dof_renumbering.output"); logfile.precision (2); logfile.setf(std::ios::fixed); deallog.attach(logfile); deallog.depth_console (0); deallog.push ("1d"); check<1> (); deallog.pop (); deallog.push ("2d"); check<2> (); deallog.pop (); deallog.push ("3d"); check<3> (); deallog.pop (); } <|endoftext|>
<commit_before>//===-- SIShrinkInstructions.cpp - Shrink Instructions --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // /// The pass tries to use the 32-bit encoding for instructions when possible. //===----------------------------------------------------------------------===// // #include "AMDGPU.h" #include "AMDGPUSubtarget.h" #include "SIInstrInfo.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/Constants.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Function.h" #include "llvm/Support/Debug.h" #include "llvm/Target/TargetMachine.h" #define DEBUG_TYPE "si-shrink-instructions" STATISTIC(NumInstructionsShrunk, "Number of 64-bit instruction reduced to 32-bit."); STATISTIC(NumLiteralConstantsFolded, "Number of literal constants folded into 32-bit instructions."); namespace llvm { void initializeSIShrinkInstructionsPass(PassRegistry&); } using namespace llvm; namespace { class SIShrinkInstructions : public MachineFunctionPass { public: static char ID; public: SIShrinkInstructions() : MachineFunctionPass(ID) { } bool runOnMachineFunction(MachineFunction &MF) override; const char *getPassName() const override { return "SI Shrink Instructions"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } }; } // End anonymous namespace. INITIALIZE_PASS_BEGIN(SIShrinkInstructions, DEBUG_TYPE, "SI Lower il Copies", false, false) INITIALIZE_PASS_END(SIShrinkInstructions, DEBUG_TYPE, "SI Lower il Copies", false, false) char SIShrinkInstructions::ID = 0; FunctionPass *llvm::createSIShrinkInstructionsPass() { return new SIShrinkInstructions(); } static bool isVGPR(const MachineOperand *MO, const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI) { if (!MO->isReg()) return false; if (TargetRegisterInfo::isVirtualRegister(MO->getReg())) return TRI.hasVGPRs(MRI.getRegClass(MO->getReg())); return TRI.hasVGPRs(TRI.getPhysRegClass(MO->getReg())); } static bool canShrink(MachineInstr &MI, const SIInstrInfo *TII, const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI) { const MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2); // Can't shrink instruction with three operands. if (Src2) return false; const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); const MachineOperand *Src1Mod = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers); if (Src1 && (!isVGPR(Src1, TRI, MRI) || (Src1Mod && Src1Mod->getImm() != 0))) return false; // We don't need to check src0, all input types are legal, so just make // sure src0 isn't using any modifiers. const MachineOperand *Src0Mod = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers); if (Src0Mod && Src0Mod->getImm() != 0) return false; // Check output modifiers const MachineOperand *Omod = TII->getNamedOperand(MI, AMDGPU::OpName::omod); if (Omod && Omod->getImm() != 0) return false; const MachineOperand *Clamp = TII->getNamedOperand(MI, AMDGPU::OpName::clamp); return !Clamp || Clamp->getImm() == 0; } /// \brief This function checks \p MI for operands defined by a move immediate /// instruction and then folds the literal constant into the instruction if it /// can. This function assumes that \p MI is a VOP1, VOP2, or VOPC instruction /// and will only fold literal constants if we are still in SSA. static void foldImmediates(MachineInstr &MI, const SIInstrInfo *TII, MachineRegisterInfo &MRI, bool TryToCommute = true) { if (!MRI.isSSA()) return; assert(TII->isVOP1(MI.getOpcode()) || TII->isVOP2(MI.getOpcode()) || TII->isVOPC(MI.getOpcode())); const SIRegisterInfo &TRI = TII->getRegisterInfo(); MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0); // Only one literal constant is allowed per instruction, so if src0 is a // literal constant then we can't do any folding. if (Src0->isImm() && TII->isLiteralConstant(*Src0)) return; // Literal constants and SGPRs can only be used in Src0, so if Src0 is an // SGPR, we cannot commute the instruction, so we can't fold any literal // constants. if (Src0->isReg() && !isVGPR(Src0, TRI, MRI)) return; // Try to fold Src0 if (Src0->isReg()) { unsigned Reg = Src0->getReg(); MachineInstr *Def = MRI.getUniqueVRegDef(Reg); if (Def && Def->isMoveImmediate()) { MachineOperand &MovSrc = Def->getOperand(1); bool ConstantFolded = false; if (MovSrc.isImm() && isUInt<32>(MovSrc.getImm())) { Src0->ChangeToImmediate(MovSrc.getImm()); ConstantFolded = true; } else if (MovSrc.isFPImm()) { const ConstantFP *CFP = MovSrc.getFPImm(); if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) { Src0->ChangeToFPImmediate(CFP); ConstantFolded = true; } } if (ConstantFolded) { if (MRI.use_empty(Reg)) Def->eraseFromParent(); ++NumLiteralConstantsFolded; return; } } } // We have failed to fold src0, so commute the instruction and try again. if (TryToCommute && MI.isCommutable() && TII->commuteInstruction(&MI)) foldImmediates(MI, TII, MRI, false); } bool SIShrinkInstructions::runOnMachineFunction(MachineFunction &MF) { MachineRegisterInfo &MRI = MF.getRegInfo(); const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(MF.getSubtarget().getInstrInfo()); const SIRegisterInfo &TRI = TII->getRegisterInfo(); std::vector<unsigned> I1Defs; for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE; ++BI) { MachineBasicBlock &MBB = *BI; MachineBasicBlock::iterator I, Next; for (I = MBB.begin(); I != MBB.end(); I = Next) { Next = std::next(I); MachineInstr &MI = *I; if (!TII->hasVALU32BitEncoding(MI.getOpcode())) continue; if (!canShrink(MI, TII, TRI, MRI)) { // Try commuting the instruction and see if that enables us to shrink // it. if (!MI.isCommutable() || !TII->commuteInstruction(&MI) || !canShrink(MI, TII, TRI, MRI)) continue; } int Op32 = AMDGPU::getVOPe32(MI.getOpcode()); // Op32 could be -1 here if we started with an instruction that had a // a 32-bit encoding and then commuted it to an instruction that did not. if (Op32 == -1) continue; if (TII->isVOPC(Op32)) { unsigned DstReg = MI.getOperand(0).getReg(); if (TargetRegisterInfo::isVirtualRegister(DstReg)) { // VOPC instructions can only write to the VCC register. We can't // force them to use VCC here, because the register allocator has // trouble with sequences like this, which cause the allocator to run // out of registers if vreg0 and vreg1 belong to the VCCReg register // class: // vreg0 = VOPC; // vreg1 = VOPC; // S_AND_B64 vreg0, vreg1 // // So, instead of forcing the instruction to write to VCC, we provide // a hint to the register allocator to use VCC and then we we will run // this pass again after RA and shrink it if it outputs to VCC. MRI.setRegAllocationHint(MI.getOperand(0).getReg(), 0, AMDGPU::VCC); continue; } if (DstReg != AMDGPU::VCC) continue; } // We can shrink this instruction DEBUG(dbgs() << "Shrinking "; MI.dump(); dbgs() << '\n';); MachineInstrBuilder Inst32 = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(Op32)); // dst Inst32.addOperand(MI.getOperand(0)); Inst32.addOperand(*TII->getNamedOperand(MI, AMDGPU::OpName::src0)); const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); if (Src1) Inst32.addOperand(*Src1); ++NumInstructionsShrunk; MI.eraseFromParent(); foldImmediates(*Inst32, TII, MRI); DEBUG(dbgs() << "e32 MI = " << *Inst32 << '\n'); } } return false; } <commit_msg>R600/SI: Simplify code with hasModifiersSet<commit_after>//===-- SIShrinkInstructions.cpp - Shrink Instructions --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // /// The pass tries to use the 32-bit encoding for instructions when possible. //===----------------------------------------------------------------------===// // #include "AMDGPU.h" #include "AMDGPUSubtarget.h" #include "SIInstrInfo.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/Constants.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Function.h" #include "llvm/Support/Debug.h" #include "llvm/Target/TargetMachine.h" #define DEBUG_TYPE "si-shrink-instructions" STATISTIC(NumInstructionsShrunk, "Number of 64-bit instruction reduced to 32-bit."); STATISTIC(NumLiteralConstantsFolded, "Number of literal constants folded into 32-bit instructions."); namespace llvm { void initializeSIShrinkInstructionsPass(PassRegistry&); } using namespace llvm; namespace { class SIShrinkInstructions : public MachineFunctionPass { public: static char ID; public: SIShrinkInstructions() : MachineFunctionPass(ID) { } bool runOnMachineFunction(MachineFunction &MF) override; const char *getPassName() const override { return "SI Shrink Instructions"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } }; } // End anonymous namespace. INITIALIZE_PASS_BEGIN(SIShrinkInstructions, DEBUG_TYPE, "SI Lower il Copies", false, false) INITIALIZE_PASS_END(SIShrinkInstructions, DEBUG_TYPE, "SI Lower il Copies", false, false) char SIShrinkInstructions::ID = 0; FunctionPass *llvm::createSIShrinkInstructionsPass() { return new SIShrinkInstructions(); } static bool isVGPR(const MachineOperand *MO, const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI) { if (!MO->isReg()) return false; if (TargetRegisterInfo::isVirtualRegister(MO->getReg())) return TRI.hasVGPRs(MRI.getRegClass(MO->getReg())); return TRI.hasVGPRs(TRI.getPhysRegClass(MO->getReg())); } static bool canShrink(MachineInstr &MI, const SIInstrInfo *TII, const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI) { const MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2); // Can't shrink instruction with three operands. if (Src2) return false; const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); const MachineOperand *Src1Mod = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers); if (Src1 && (!isVGPR(Src1, TRI, MRI) || (Src1Mod && Src1Mod->getImm() != 0))) return false; // We don't need to check src0, all input types are legal, so just make sure // src0 isn't using any modifiers. if (TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers)) return false; // Check output modifiers if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod)) return false; if (TII->hasModifiersSet(MI, AMDGPU::OpName::clamp)) return false; return true; } /// \brief This function checks \p MI for operands defined by a move immediate /// instruction and then folds the literal constant into the instruction if it /// can. This function assumes that \p MI is a VOP1, VOP2, or VOPC instruction /// and will only fold literal constants if we are still in SSA. static void foldImmediates(MachineInstr &MI, const SIInstrInfo *TII, MachineRegisterInfo &MRI, bool TryToCommute = true) { if (!MRI.isSSA()) return; assert(TII->isVOP1(MI.getOpcode()) || TII->isVOP2(MI.getOpcode()) || TII->isVOPC(MI.getOpcode())); const SIRegisterInfo &TRI = TII->getRegisterInfo(); MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0); // Only one literal constant is allowed per instruction, so if src0 is a // literal constant then we can't do any folding. if (Src0->isImm() && TII->isLiteralConstant(*Src0)) return; // Literal constants and SGPRs can only be used in Src0, so if Src0 is an // SGPR, we cannot commute the instruction, so we can't fold any literal // constants. if (Src0->isReg() && !isVGPR(Src0, TRI, MRI)) return; // Try to fold Src0 if (Src0->isReg()) { unsigned Reg = Src0->getReg(); MachineInstr *Def = MRI.getUniqueVRegDef(Reg); if (Def && Def->isMoveImmediate()) { MachineOperand &MovSrc = Def->getOperand(1); bool ConstantFolded = false; if (MovSrc.isImm() && isUInt<32>(MovSrc.getImm())) { Src0->ChangeToImmediate(MovSrc.getImm()); ConstantFolded = true; } else if (MovSrc.isFPImm()) { const ConstantFP *CFP = MovSrc.getFPImm(); if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) { Src0->ChangeToFPImmediate(CFP); ConstantFolded = true; } } if (ConstantFolded) { if (MRI.use_empty(Reg)) Def->eraseFromParent(); ++NumLiteralConstantsFolded; return; } } } // We have failed to fold src0, so commute the instruction and try again. if (TryToCommute && MI.isCommutable() && TII->commuteInstruction(&MI)) foldImmediates(MI, TII, MRI, false); } bool SIShrinkInstructions::runOnMachineFunction(MachineFunction &MF) { MachineRegisterInfo &MRI = MF.getRegInfo(); const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(MF.getSubtarget().getInstrInfo()); const SIRegisterInfo &TRI = TII->getRegisterInfo(); std::vector<unsigned> I1Defs; for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE; ++BI) { MachineBasicBlock &MBB = *BI; MachineBasicBlock::iterator I, Next; for (I = MBB.begin(); I != MBB.end(); I = Next) { Next = std::next(I); MachineInstr &MI = *I; if (!TII->hasVALU32BitEncoding(MI.getOpcode())) continue; if (!canShrink(MI, TII, TRI, MRI)) { // Try commuting the instruction and see if that enables us to shrink // it. if (!MI.isCommutable() || !TII->commuteInstruction(&MI) || !canShrink(MI, TII, TRI, MRI)) continue; } int Op32 = AMDGPU::getVOPe32(MI.getOpcode()); // Op32 could be -1 here if we started with an instruction that had a // a 32-bit encoding and then commuted it to an instruction that did not. if (Op32 == -1) continue; if (TII->isVOPC(Op32)) { unsigned DstReg = MI.getOperand(0).getReg(); if (TargetRegisterInfo::isVirtualRegister(DstReg)) { // VOPC instructions can only write to the VCC register. We can't // force them to use VCC here, because the register allocator has // trouble with sequences like this, which cause the allocator to run // out of registers if vreg0 and vreg1 belong to the VCCReg register // class: // vreg0 = VOPC; // vreg1 = VOPC; // S_AND_B64 vreg0, vreg1 // // So, instead of forcing the instruction to write to VCC, we provide // a hint to the register allocator to use VCC and then we we will run // this pass again after RA and shrink it if it outputs to VCC. MRI.setRegAllocationHint(MI.getOperand(0).getReg(), 0, AMDGPU::VCC); continue; } if (DstReg != AMDGPU::VCC) continue; } // We can shrink this instruction DEBUG(dbgs() << "Shrinking "; MI.dump(); dbgs() << '\n';); MachineInstrBuilder Inst32 = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(Op32)); // dst Inst32.addOperand(MI.getOperand(0)); Inst32.addOperand(*TII->getNamedOperand(MI, AMDGPU::OpName::src0)); const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); if (Src1) Inst32.addOperand(*Src1); ++NumInstructionsShrunk; MI.eraseFromParent(); foldImmediates(*Inst32, TII, MRI); DEBUG(dbgs() << "e32 MI = " << *Inst32 << '\n'); } } return false; } <|endoftext|>
<commit_before> #include <SFML/Config.hpp> #include <SFML/Graphics.hpp> #include <sfeMovie/Movie.hpp> #include <iostream> #include <algorithm> /* * Here is a little use sample for sfeMovie. * It'll open and display the movie specified by MOVIE_FILE above. * * This sample implements basic controls as follow: * - Escape key to exit * - Space key to play/pause the movie playback * - S key to stop and go back to the beginning of the movie * - F key to toggle between windowed and fullscreen mode * - A key to select the next audio stream * - V key to select the next video stream */ void my_pause() { #ifdef SFML_SYSTEM_WINDOWS system("PAUSE"); #endif } std::string StatusToString(sfe::Status status) { switch (status) { case sfe::Stopped: return "Stopped"; case sfe::Paused: return "Paused"; case sfe::Playing: return "Playing"; default: return "unknown status"; } } std::string mediaTypeToString(sfe::MediaType type) { switch (type) { case sfe::Audio: return "audio"; case sfe::Subtitle: return "subtitle"; case sfe::Video: return "video"; case sfe::Unknown: return "unknown"; default: return "(null)"; } } void drawControls(sf::RenderWindow& window, const sfe::Movie& movie) { const int kHorizontalMargin = 10; const int kVerticalMargin = 10; const int kTimelineBackgroundHeight = 20; const int kTimelineInnerMargin = 4; sf::RectangleShape background(sf::Vector2f(window.getSize().x - 2 * kHorizontalMargin, kTimelineBackgroundHeight)); background.setPosition(kHorizontalMargin, window.getSize().y - kTimelineBackgroundHeight - kVerticalMargin); background.setFillColor(sf::Color(0, 0, 0, 255/2)); sf::RectangleShape border(sf::Vector2f(background.getSize().x - 2 * kTimelineInnerMargin, background.getSize().y - 2 * kTimelineInnerMargin)); border.setPosition(background.getPosition().x + kTimelineInnerMargin, background.getPosition().y + kTimelineInnerMargin); border.setFillColor(sf::Color::Transparent); border.setOutlineColor(sf::Color::White); border.setOutlineThickness(1.0); float fprogress = movie.getPlayingOffset().asSeconds() / movie.getDuration().asSeconds(); sf::RectangleShape progress(sf::Vector2f(1, border.getSize().y - 2 * border.getOutlineThickness())); progress.setPosition(border.getPosition().x + border.getOutlineThickness() + fprogress * (border.getSize().x - 2 * border.getOutlineThickness()), border.getPosition().y + border.getOutlineThickness()); progress.setFillColor(sf::Color::White); window.draw(background); window.draw(border); window.draw(progress); } void printMovieInfo(const sfe::Movie& movie) { std::cout << "Status: " << StatusToString(movie.getStatus()) << std::endl; std::cout << "Position: " << movie.getPlayingOffset().asSeconds() << "s" << std::endl; std::cout << "Duration: " << movie.getDuration().asSeconds() << "s" << std::endl; std::cout << "Size: " << movie.getSize().x << "x" << movie.getSize().y << std::endl; std::cout << "Framerate: " << movie.getFramerate() << " FPS (average)" << std::endl; std::cout << "Volume: " << movie.getVolume() << std::endl; std::cout << "Sample rate: " << movie.getSampleRate() << std::endl; std::cout << "Channel count: " << movie.getChannelCount() << std::endl; const sfe::Streams& videoStreams = movie.getStreams(sfe::Video); const sfe::Streams& audioStreams = movie.getStreams(sfe::Audio); std::cout << videoStreams.size() + audioStreams.size() << " streams found in the media" << std::endl; for (sfe::Streams::const_iterator it = videoStreams.begin(); it != videoStreams.end(); ++it) { std::cout << " #" << it->identifier << " : " << mediaTypeToString(it->type) << std::endl; } for (sfe::Streams::const_iterator it = audioStreams.begin(); it != audioStreams.end(); ++it) { std::cout << " #" << it->identifier << " : " << mediaTypeToString(it->type); if (!it->language.empty()) std::cout << " (language: " << it->language << ")"; std::cout << std::endl; } } int main(int argc, const char *argv[]) { if (argc < 2) { std::cout << "Usage: " << std::string(argv[0]) << " movie_path" << std::endl; my_pause(); return 1; } std::string mediaFile = std::string(argv[1]); std::cout << "Going to open movie file \"" << mediaFile << "\"" << std::endl; sfe::Movie movie; if (!movie.openFromFile(mediaFile)) { my_pause(); return 1; } bool fullscreen = false; sf::VideoMode desktopMode = sf::VideoMode::getDesktopMode(); int width = std::min((int)desktopMode.width, movie.getSize().x); int height = std::min((int)desktopMode.height, movie.getSize().y); // Create window sf::RenderWindow window(sf::VideoMode(width, height), "sfeMovie Player", sf::Style::Close | sf::Style::Resize); movie.fit(0, 0, width, height); printMovieInfo(movie); // Allow stream selection const sfe::Streams& audioStreams = movie.getStreams(sfe::Audio); const sfe::Streams& videoStreams = movie.getStreams(sfe::Video); const sfe::Streams& subtitleStreams = movie.getStreams(sfe::Subtitle); int selectedVideoStreamId = 0; int selectedAudioStreamId = 0; int selectedSubtitleStreamId = 0; // Scale movie to the window drawing area and enable VSync window.setFramerateLimit(60); window.setVerticalSyncEnabled(true); movie.play(); while (window.isOpen()) { sf::Event ev; while (window.pollEvent(ev)) { // Window closure if (ev.type == sf::Event::Closed || (ev.type == sf::Event::KeyPressed && ev.key.code == sf::Keyboard::Escape)) { window.close(); } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Space) { if (movie.getStatus() == sfe::Playing) { movie.pause(); } else { movie.play(); } } else if (ev.key.code == sf::Keyboard::P) { movie.stop(); } else if (ev.key.code == sf::Keyboard::F) { fullscreen = !fullscreen; if (fullscreen) window.create(desktopMode, "sfeMovie Player", sf::Style::Fullscreen); else window.create(sf::VideoMode(width, height), "sfeMovie Player", sf::Style::Close | sf::Style::Resize); movie.fit(0, 0, window.getSize().x, window.getSize().y); } else if (ev.key.code == sf::Keyboard::P) { printMovieInfo(movie); } else if (ev.key.code == sf::Keyboard::V) { if (videoStreams.size() > 1) { selectedVideoStreamId++; selectedVideoStreamId %= videoStreams.size(); movie.selectStream(videoStreams[selectedVideoStreamId]); std::cout << "Selected video stream #" << videoStreams[selectedVideoStreamId].identifier << std::endl; } } else if (ev.key.code == sf::Keyboard::A) { if (audioStreams.size() > 1) { selectedAudioStreamId++; selectedAudioStreamId %= audioStreams.size(); movie.selectStream(audioStreams[selectedAudioStreamId]); std::cout << "Selected audio stream #" << audioStreams[selectedAudioStreamId].identifier << std::endl; } } else if (ev.key.code == sf::Keyboard::S) { if (subtitleStreams.size() > 1) { selectedSubtitleStreamId++; selectedSubtitleStreamId %= subtitleStreams.size(); movie.selectStream(subtitleStreams[selectedSubtitleStreamId]); std::cout << "Selected subtitle stream #" << subtitleStreams[selectedSubtitleStreamId].identifier << std::endl; } } } else if (ev.type == sf::Event::MouseWheelMoved) { float volume = movie.getVolume() + 10 * ev.mouseWheel.delta; volume = std::min(volume, 100.f); volume = std::max(volume, 0.f); movie.setVolume(volume); } else if (ev.type == sf::Event::Resized) { movie.fit(0, 0, window.getSize().x, window.getSize().y); window.setView(sf::View(sf::FloatRect(0, 0, window.getSize().x, window.getSize().y))); } } movie.update(); // Render movie window.clear(); window.draw(movie); drawControls(window, movie); window.display(); } return 0; } <commit_msg>#7 DIsplay correct info about the available subtitle streams<commit_after> #include <SFML/Config.hpp> #include <SFML/Graphics.hpp> #include <sfeMovie/Movie.hpp> #include <iostream> #include <algorithm> /* * Here is a little use sample for sfeMovie. * It'll open and display the movie specified by MOVIE_FILE above. * * This sample implements basic controls as follow: * - Escape key to exit * - Space key to play/pause the movie playback * - S key to stop and go back to the beginning of the movie * - F key to toggle between windowed and fullscreen mode * - A key to select the next audio stream * - V key to select the next video stream */ void my_pause() { #ifdef SFML_SYSTEM_WINDOWS system("PAUSE"); #endif } std::string StatusToString(sfe::Status status) { switch (status) { case sfe::Stopped: return "Stopped"; case sfe::Paused: return "Paused"; case sfe::Playing: return "Playing"; default: return "unknown status"; } } std::string mediaTypeToString(sfe::MediaType type) { switch (type) { case sfe::Audio: return "audio"; case sfe::Subtitle: return "subtitle"; case sfe::Video: return "video"; case sfe::Unknown: return "unknown"; default: return "(null)"; } } void drawControls(sf::RenderWindow& window, const sfe::Movie& movie) { const int kHorizontalMargin = 10; const int kVerticalMargin = 10; const int kTimelineBackgroundHeight = 20; const int kTimelineInnerMargin = 4; sf::RectangleShape background(sf::Vector2f(window.getSize().x - 2 * kHorizontalMargin, kTimelineBackgroundHeight)); background.setPosition(kHorizontalMargin, window.getSize().y - kTimelineBackgroundHeight - kVerticalMargin); background.setFillColor(sf::Color(0, 0, 0, 255/2)); sf::RectangleShape border(sf::Vector2f(background.getSize().x - 2 * kTimelineInnerMargin, background.getSize().y - 2 * kTimelineInnerMargin)); border.setPosition(background.getPosition().x + kTimelineInnerMargin, background.getPosition().y + kTimelineInnerMargin); border.setFillColor(sf::Color::Transparent); border.setOutlineColor(sf::Color::White); border.setOutlineThickness(1.0); float fprogress = movie.getPlayingOffset().asSeconds() / movie.getDuration().asSeconds(); sf::RectangleShape progress(sf::Vector2f(1, border.getSize().y - 2 * border.getOutlineThickness())); progress.setPosition(border.getPosition().x + border.getOutlineThickness() + fprogress * (border.getSize().x - 2 * border.getOutlineThickness()), border.getPosition().y + border.getOutlineThickness()); progress.setFillColor(sf::Color::White); window.draw(background); window.draw(border); window.draw(progress); } void printMovieInfo(const sfe::Movie& movie) { std::cout << "Status: " << StatusToString(movie.getStatus()) << std::endl; std::cout << "Position: " << movie.getPlayingOffset().asSeconds() << "s" << std::endl; std::cout << "Duration: " << movie.getDuration().asSeconds() << "s" << std::endl; std::cout << "Size: " << movie.getSize().x << "x" << movie.getSize().y << std::endl; std::cout << "Framerate: " << movie.getFramerate() << " FPS (average)" << std::endl; std::cout << "Volume: " << movie.getVolume() << std::endl; std::cout << "Sample rate: " << movie.getSampleRate() << std::endl; std::cout << "Channel count: " << movie.getChannelCount() << std::endl; const sfe::Streams& videoStreams = movie.getStreams(sfe::Video); const sfe::Streams& audioStreams = movie.getStreams(sfe::Audio); const sfe::Streams& subtitleStreams = movie.getStreams(sfe::Subtitle); std::cout << videoStreams.size() + audioStreams.size() + subtitleStreams.size() << " streams found in the media" << std::endl; for (sfe::Streams::const_iterator it = videoStreams.begin(); it != videoStreams.end(); ++it) { std::cout << " #" << it->identifier << " : " << mediaTypeToString(it->type) << std::endl; } for (sfe::Streams::const_iterator it = audioStreams.begin(); it != audioStreams.end(); ++it) { std::cout << " #" << it->identifier << " : " << mediaTypeToString(it->type); if (!it->language.empty()) std::cout << " (language: " << it->language << ")"; std::cout << std::endl; } for (sfe::Streams::const_iterator it = subtitleStreams.begin(); it != subtitleStreams.end(); ++it) { std::cout << " #" << it->identifier << " : " << mediaTypeToString(it->type); if (!it->language.empty()) std::cout << " (language: " << it->language << ")"; std::cout << std::endl; } } int main(int argc, const char *argv[]) { if (argc < 2) { std::cout << "Usage: " << std::string(argv[0]) << " movie_path" << std::endl; my_pause(); return 1; } std::string mediaFile = std::string(argv[1]); std::cout << "Going to open movie file \"" << mediaFile << "\"" << std::endl; sfe::Movie movie; if (!movie.openFromFile(mediaFile)) { my_pause(); return 1; } bool fullscreen = false; sf::VideoMode desktopMode = sf::VideoMode::getDesktopMode(); int width = std::min((int)desktopMode.width, movie.getSize().x); int height = std::min((int)desktopMode.height, movie.getSize().y); // Create window sf::RenderWindow window(sf::VideoMode(width, height), "sfeMovie Player", sf::Style::Close | sf::Style::Resize); movie.fit(0, 0, width, height); printMovieInfo(movie); // Allow stream selection const sfe::Streams& audioStreams = movie.getStreams(sfe::Audio); const sfe::Streams& videoStreams = movie.getStreams(sfe::Video); const sfe::Streams& subtitleStreams = movie.getStreams(sfe::Subtitle); int selectedVideoStreamId = 0; int selectedAudioStreamId = 0; int selectedSubtitleStreamId = 0; // Scale movie to the window drawing area and enable VSync window.setFramerateLimit(60); window.setVerticalSyncEnabled(true); movie.play(); while (window.isOpen()) { sf::Event ev; while (window.pollEvent(ev)) { // Window closure if (ev.type == sf::Event::Closed || (ev.type == sf::Event::KeyPressed && ev.key.code == sf::Keyboard::Escape)) { window.close(); } if (ev.type == sf::Event::KeyPressed) { if (ev.key.code == sf::Keyboard::Space) { if (movie.getStatus() == sfe::Playing) { movie.pause(); } else { movie.play(); } } else if (ev.key.code == sf::Keyboard::P) { movie.stop(); } else if (ev.key.code == sf::Keyboard::F) { fullscreen = !fullscreen; if (fullscreen) window.create(desktopMode, "sfeMovie Player", sf::Style::Fullscreen); else window.create(sf::VideoMode(width, height), "sfeMovie Player", sf::Style::Close | sf::Style::Resize); movie.fit(0, 0, window.getSize().x, window.getSize().y); } else if (ev.key.code == sf::Keyboard::I) { printMovieInfo(movie); } else if (ev.key.code == sf::Keyboard::V) { if (videoStreams.size() > 1) { selectedVideoStreamId++; selectedVideoStreamId %= videoStreams.size(); movie.selectStream(videoStreams[selectedVideoStreamId]); std::cout << "Selected video stream #" << videoStreams[selectedVideoStreamId].identifier << std::endl; } } else if (ev.key.code == sf::Keyboard::A) { if (audioStreams.size() > 1) { selectedAudioStreamId++; selectedAudioStreamId %= audioStreams.size(); movie.selectStream(audioStreams[selectedAudioStreamId]); std::cout << "Selected audio stream #" << audioStreams[selectedAudioStreamId].identifier << std::endl; } } else if (ev.key.code == sf::Keyboard::S) { if (subtitleStreams.size() > 0) { selectedSubtitleStreamId++; selectedSubtitleStreamId %= subtitleStreams.size() + 1; if (selectedSubtitleStreamId == subtitleStreams.size()) { movie.selectStream(sfe::StreamDescriptor::NoSelection(sfe::Subtitle)); std::cout << "Unselected subtitle stream" << std::endl; } else { movie.selectStream(subtitleStreams[selectedSubtitleStreamId]); std::cout << "Selected subtitle stream #" << subtitleStreams[selectedSubtitleStreamId].identifier << std::endl; } } } } else if (ev.type == sf::Event::MouseWheelMoved) { float volume = movie.getVolume() + 10 * ev.mouseWheel.delta; volume = std::min(volume, 100.f); volume = std::max(volume, 0.f); movie.setVolume(volume); } else if (ev.type == sf::Event::Resized) { movie.fit(0, 0, window.getSize().x, window.getSize().y); window.setView(sf::View(sf::FloatRect(0, 0, window.getSize().x, window.getSize().y))); } } movie.update(); // Render movie window.clear(); window.draw(movie); drawControls(window, movie); window.display(); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/path_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/resource_bundle.h" #include "chrome/plugin/npobject_util.h" #include "googleurl/src/url_util.h" #include "webkit/glue/webkit_glue.h" namespace webkit_glue { bool GetExeDirectory(std::wstring *path) { return PathService::Get(base::DIR_EXE, path); } bool GetApplicationDirectory(std::wstring *path) { return PathService::Get(chrome::DIR_APP, path); } bool IsPluginRunningInRendererProcess() { return !IsPluginProcess(); } std::wstring GetWebKitLocale() { // The browser process should have passed the locale to the renderer via the // --lang command line flag. CommandLine parsed_command_line; const std::wstring& lang = parsed_command_line.GetSwitchValue(switches::kLang); DCHECK(!lang.empty()); return lang; } std::wstring GetLocalizedString(int message_id) { return ResourceBundle::GetSharedInstance().GetLocalizedString(message_id); } } // namespace webkit_glue <commit_msg>Allow lang to be blank in the renderer and plugin if running in single process mode. Review URL: http://codereview.chromium.org/5602<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/path_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/resource_bundle.h" #include "chrome/plugin/npobject_util.h" #include "googleurl/src/url_util.h" #include "webkit/glue/webkit_glue.h" namespace webkit_glue { bool GetExeDirectory(std::wstring *path) { return PathService::Get(base::DIR_EXE, path); } bool GetApplicationDirectory(std::wstring *path) { return PathService::Get(chrome::DIR_APP, path); } bool IsPluginRunningInRendererProcess() { return !IsPluginProcess(); } std::wstring GetWebKitLocale() { // The browser process should have passed the locale to the renderer via the // --lang command line flag. In single process mode, this will return the // wrong value. TODO(tc): Fix this for single process mode. CommandLine parsed_command_line; const std::wstring& lang = parsed_command_line.GetSwitchValue(switches::kLang); DCHECK(!lang.empty() || (!parsed_command_line.HasSwitch(switches::kRendererProcess) && !parsed_command_line.HasSwitch(switches::kPluginProcess))); return lang; } std::wstring GetLocalizedString(int message_id) { return ResourceBundle::GetSharedInstance().GetLocalizedString(message_id); } } // namespace webkit_glue <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/ipc_message.h" #include "base/logging.h" #include "build/build_config.h" namespace IPC { //------------------------------------------------------------------------------ Message::~Message() { } Message::Message() : Pickle(sizeof(Header)) { header()->routing = header()->type = header()->flags = 0; #if defined(OS_POSIX) header()->num_fds = 0; #endif InitLoggingVariables(); } Message::Message(int32 routing_id, uint16 type, PriorityValue priority) : Pickle(sizeof(Header)) { header()->routing = routing_id; header()->type = type; header()->flags = priority; #if defined(OS_POSIX) header()->num_fds = 0; #endif InitLoggingVariables(); } Message::Message(const char* data, int data_len) : Pickle(data, data_len) { InitLoggingVariables(); } Message::Message(const Message& other) : Pickle(other) { InitLoggingVariables(); descriptor_set_.TakeFrom(&other.descriptor_set_); } void Message::InitLoggingVariables() { #ifdef IPC_MESSAGE_LOG_ENABLED received_time_ = 0; dont_log_ = false; log_data_ = NULL; #endif } Message& Message::operator=(const Message& other) { *static_cast<Pickle*>(this) = other; return *this; } #ifdef IPC_MESSAGE_LOG_ENABLED void Message::set_sent_time(int64 time) { DCHECK((header()->flags & HAS_SENT_TIME_BIT) == 0); header()->flags |= HAS_SENT_TIME_BIT; WriteInt64(time); } int64 Message::sent_time() const { if ((header()->flags & HAS_SENT_TIME_BIT) == 0) return 0; const char* data = end_of_payload(); data -= sizeof(int64); return *(reinterpret_cast<const int64*>(data)); } void Message::set_received_time(int64 time) const { received_time_ = time; } #endif } // namespace IPC <commit_msg>Windows: build fix<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/ipc_message.h" #include "base/logging.h" #include "build/build_config.h" namespace IPC { //------------------------------------------------------------------------------ Message::~Message() { } Message::Message() : Pickle(sizeof(Header)) { header()->routing = header()->type = header()->flags = 0; #if defined(OS_POSIX) header()->num_fds = 0; #endif InitLoggingVariables(); } Message::Message(int32 routing_id, uint16 type, PriorityValue priority) : Pickle(sizeof(Header)) { header()->routing = routing_id; header()->type = type; header()->flags = priority; #if defined(OS_POSIX) header()->num_fds = 0; #endif InitLoggingVariables(); } Message::Message(const char* data, int data_len) : Pickle(data, data_len) { InitLoggingVariables(); } Message::Message(const Message& other) : Pickle(other) { InitLoggingVariables(); #if defined(OS_POSIX) descriptor_set_.TakeFrom(&other.descriptor_set_); #endif } void Message::InitLoggingVariables() { #ifdef IPC_MESSAGE_LOG_ENABLED received_time_ = 0; dont_log_ = false; log_data_ = NULL; #endif } Message& Message::operator=(const Message& other) { *static_cast<Pickle*>(this) = other; return *this; } #ifdef IPC_MESSAGE_LOG_ENABLED void Message::set_sent_time(int64 time) { DCHECK((header()->flags & HAS_SENT_TIME_BIT) == 0); header()->flags |= HAS_SENT_TIME_BIT; WriteInt64(time); } int64 Message::sent_time() const { if ((header()->flags & HAS_SENT_TIME_BIT) == 0) return 0; const char* data = end_of_payload(); data -= sizeof(int64); return *(reinterpret_cast<const int64*>(data)); } void Message::set_received_time(int64 time) const { received_time_ = time; } #endif } // namespace IPC <|endoftext|>
<commit_before>//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Guarantees that all loops with identifiable, linear, induction variables will // be transformed to have a single, canonical, induction variable. After this // pass runs, it guarantees the the first PHI node of the header block in the // loop is the canonical induction variable if there is one. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Constants.h" #include "llvm/Type.h" #include "llvm/Instructions.h" #include "llvm/Analysis/InductionVariable.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Support/CFG.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/Utils/Local.h" #include "Support/Debug.h" #include "Support/Statistic.h" using namespace llvm; namespace { Statistic<> NumRemoved ("indvars", "Number of aux indvars removed"); Statistic<> NumInserted("indvars", "Number of canonical indvars added"); class IndVarSimplify : public FunctionPass { LoopInfo *Loops; TargetData *TD; public: virtual bool runOnFunction(Function &) { Loops = &getAnalysis<LoopInfo>(); TD = &getAnalysis<TargetData>(); // Induction Variables live in the header nodes of loops bool Changed = false; for (unsigned i = 0, e = Loops->getTopLevelLoops().size(); i != e; ++i) Changed |= runOnLoop(Loops->getTopLevelLoops()[i]); return Changed; } unsigned getTypeSize(const Type *Ty) { if (unsigned Size = Ty->getPrimitiveSize()) return Size; return TD->getTypeSize(Ty); // Must be a pointer } Value *ComputeAuxIndVarValue(InductionVariable &IV, Value *CIV); void ReplaceIndVar(InductionVariable &IV, Value *Counter); bool runOnLoop(Loop *L); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetData>(); // Need pointer size AU.addRequired<LoopInfo>(); AU.addRequiredID(LoopSimplifyID); AU.addPreservedID(LoopSimplifyID); AU.setPreservesCFG(); } }; RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables"); } Pass *llvm::createIndVarSimplifyPass() { return new IndVarSimplify(); } bool IndVarSimplify::runOnLoop(Loop *Loop) { // Transform all subloops before this loop... bool Changed = false; for (unsigned i = 0, e = Loop->getSubLoops().size(); i != e; ++i) Changed |= runOnLoop(Loop->getSubLoops()[i]); // Get the header node for this loop. All of the phi nodes that could be // induction variables must live in this basic block. // BasicBlock *Header = Loop->getHeader(); // Loop over all of the PHI nodes in the basic block, calculating the // induction variables that they represent... stuffing the induction variable // info into a vector... // std::vector<InductionVariable> IndVars; // Induction variables for block BasicBlock::iterator AfterPHIIt = Header->begin(); for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt) IndVars.push_back(InductionVariable(PN, Loops)); // AfterPHIIt now points to first non-phi instruction... // If there are no phi nodes in this basic block, there can't be indvars... if (IndVars.empty()) return Changed; // Loop over the induction variables, looking for a canonical induction // variable, and checking to make sure they are not all unknown induction // variables. Keep track of the largest integer size of the induction // variable. // InductionVariable *Canonical = 0; unsigned MaxSize = 0; for (unsigned i = 0; i != IndVars.size(); ++i) { InductionVariable &IV = IndVars[i]; if (IV.InductionType != InductionVariable::Unknown) { unsigned IVSize = getTypeSize(IV.Phi->getType()); if (IV.InductionType == InductionVariable::Canonical && !isa<PointerType>(IV.Phi->getType()) && IVSize >= MaxSize) Canonical = &IV; if (IVSize > MaxSize) MaxSize = IVSize; // If this variable is larger than the currently identified canonical // indvar, the canonical indvar is not usable. if (Canonical && IVSize > getTypeSize(Canonical->Phi->getType())) Canonical = 0; } } // No induction variables, bail early... don't add a canonical indvar if (MaxSize == 0) return Changed; // Okay, we want to convert other induction variables to use a canonical // indvar. If we don't have one, add one now... if (!Canonical) { // Create the PHI node for the new induction variable, and insert the phi // node at the start of the PHI nodes... const Type *IVType; switch (MaxSize) { default: assert(0 && "Unknown integer type size!"); case 1: IVType = Type::UByteTy; break; case 2: IVType = Type::UShortTy; break; case 4: IVType = Type::UIntTy; break; case 8: IVType = Type::ULongTy; break; } PHINode *PN = new PHINode(IVType, "cann-indvar", Header->begin()); // Create the increment instruction to add one to the counter... Instruction *Add = BinaryOperator::create(Instruction::Add, PN, ConstantUInt::get(IVType, 1), "next-indvar", AfterPHIIt); // Figure out which block is incoming and which is the backedge for the loop BasicBlock *Incoming, *BackEdgeBlock; pred_iterator PI = pred_begin(Header); assert(PI != pred_end(Header) && "Loop headers should have 2 preds!"); if (Loop->contains(*PI)) { // First pred is back edge... BackEdgeBlock = *PI++; Incoming = *PI++; } else { Incoming = *PI++; BackEdgeBlock = *PI++; } assert(PI == pred_end(Header) && "Loop headers should have 2 preds!"); // Add incoming values for the PHI node... PN->addIncoming(Constant::getNullValue(IVType), Incoming); PN->addIncoming(Add, BackEdgeBlock); // Analyze the new induction variable... IndVars.push_back(InductionVariable(PN, Loops)); assert(IndVars.back().InductionType == InductionVariable::Canonical && "Just inserted canonical indvar that is not canonical!"); Canonical = &IndVars.back(); ++NumInserted; Changed = true; } else { // If we have a canonical induction variable, make sure that it is the first // one in the basic block. if (&Header->front() != Canonical->Phi) Header->getInstList().splice(Header->begin(), Header->getInstList(), Canonical->Phi); } DEBUG(std::cerr << "Induction variables:\n"); // Get the current loop iteration count, which is always the value of the // canonical phi node... // PHINode *IterCount = Canonical->Phi; // Loop through and replace all of the auxiliary induction variables with // references to the canonical induction variable... // for (unsigned i = 0; i != IndVars.size(); ++i) { InductionVariable *IV = &IndVars[i]; DEBUG(IV->print(std::cerr)); // Don't modify the canonical indvar or unrecognized indvars... if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) { ReplaceIndVar(*IV, IterCount); Changed = true; ++NumRemoved; } } return Changed; } /// ComputeAuxIndVarValue - Given an auxillary induction variable, compute and /// return a value which will always be equal to the induction variable PHI, but /// is based off of the canonical induction variable CIV. /// Value *IndVarSimplify::ComputeAuxIndVarValue(InductionVariable &IV, Value *CIV){ Instruction *Phi = IV.Phi; const Type *IVTy = Phi->getType(); if (isa<PointerType>(IVTy)) // If indexing into a pointer, make the IVTy = TD->getIntPtrType(); // index the appropriate type. BasicBlock::iterator AfterPHIIt = Phi; while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt; Value *Val = CIV; if (Val->getType() != IVTy) Val = new CastInst(Val, IVTy, Val->getName(), AfterPHIIt); if (!isa<ConstantInt>(IV.Step) || // If the step != 1 !cast<ConstantInt>(IV.Step)->equalsInt(1)) { // If the types are not compatible, insert a cast now... if (IV.Step->getType() != IVTy) IV.Step = new CastInst(IV.Step, IVTy, IV.Step->getName(), AfterPHIIt); Val = BinaryOperator::create(Instruction::Mul, Val, IV.Step, Phi->getName()+"-scale", AfterPHIIt); } // If this is a pointer indvar... if (isa<PointerType>(Phi->getType())) { std::vector<Value*> Idx; // FIXME: this should not be needed when we fix PR82! if (Val->getType() != Type::LongTy) Val = new CastInst(Val, Type::LongTy, Val->getName(), AfterPHIIt); Idx.push_back(Val); Val = new GetElementPtrInst(IV.Start, Idx, Phi->getName()+"-offset", AfterPHIIt); } else if (!isa<Constant>(IV.Start) || // If Start != 0... !cast<Constant>(IV.Start)->isNullValue()) { // If the types are not compatible, insert a cast now... if (IV.Start->getType() != IVTy) IV.Start = new CastInst(IV.Start, IVTy, IV.Start->getName(), AfterPHIIt); // Insert the instruction after the phi nodes... Val = BinaryOperator::create(Instruction::Add, Val, IV.Start, Phi->getName()+"-offset", AfterPHIIt); } // If the PHI node has a different type than val is, insert a cast now... if (Val->getType() != Phi->getType()) Val = new CastInst(Val, Phi->getType(), Val->getName(), AfterPHIIt); // Move the PHI name to it's new equivalent value... std::string OldName = Phi->getName(); Phi->setName(""); Val->setName(OldName); return Val; } // ReplaceIndVar - Replace all uses of the specified induction variable with // expressions computed from the specified loop iteration counter variable. // Return true if instructions were deleted. void IndVarSimplify::ReplaceIndVar(InductionVariable &IV, Value *CIV) { Value *IndVarVal = 0; PHINode *Phi = IV.Phi; assert(Phi->getNumOperands() == 4 && "Only expect induction variables in canonical loops!"); // Remember the incoming values used by the PHI node std::vector<Value*> PHIOps; PHIOps.reserve(2); PHIOps.push_back(Phi->getIncomingValue(0)); PHIOps.push_back(Phi->getIncomingValue(1)); // Delete all of the operands of the PHI node... FIXME, this should be more // intelligent. Phi->dropAllReferences(); // Now that we are rid of unneeded uses of the PHI node, replace any remaining // ones with the appropriate code using the canonical induction variable. while (!Phi->use_empty()) { Instruction *U = cast<Instruction>(Phi->use_back()); // TODO: Perform LFTR here if possible if (0) { } else { // Replace all uses of the old PHI node with the new computed value... if (IndVarVal == 0) IndVarVal = ComputeAuxIndVarValue(IV, CIV); U->replaceUsesOfWith(Phi, IndVarVal); } } // If the PHI is the last user of any instructions for computing PHI nodes // that are irrelevant now, delete those instructions. while (!PHIOps.empty()) { Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back()); PHIOps.pop_back(); if (MaybeDead && isInstructionTriviallyDead(MaybeDead) && (!isa<PHINode>(MaybeDead) || MaybeDead->getParent() != Phi->getParent())) { PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(), MaybeDead->op_end()); MaybeDead->getParent()->getInstList().erase(MaybeDead); // Erase any duplicates entries in the PHIOps list. std::vector<Value*>::iterator It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead); while (It != PHIOps.end()) { PHIOps.erase(It); It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead); } } } // Delete the old, now unused, phi node... Phi->getParent()->getInstList().erase(Phi); } <commit_msg>More minor non-functional changes. This now computes the exit condition, though it doesn't do anything with it.<commit_after>//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Guarantees that all loops with identifiable, linear, induction variables will // be transformed to have a single, canonical, induction variable. After this // pass runs, it guarantees the the first PHI node of the header block in the // loop is the canonical induction variable if there is one. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "indvar" #include "llvm/Transforms/Scalar.h" #include "llvm/Constants.h" #include "llvm/Type.h" #include "llvm/Instructions.h" #include "llvm/Analysis/InductionVariable.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Support/CFG.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/Utils/Local.h" #include "Support/Debug.h" #include "Support/Statistic.h" using namespace llvm; namespace { Statistic<> NumRemoved ("indvars", "Number of aux indvars removed"); Statistic<> NumInserted("indvars", "Number of canonical indvars added"); class IndVarSimplify : public FunctionPass { LoopInfo *Loops; TargetData *TD; bool Changed; public: virtual bool runOnFunction(Function &) { Loops = &getAnalysis<LoopInfo>(); TD = &getAnalysis<TargetData>(); Changed = false; // Induction Variables live in the header nodes of loops for (unsigned i = 0, e = Loops->getTopLevelLoops().size(); i != e; ++i) runOnLoop(Loops->getTopLevelLoops()[i]); return Changed; } unsigned getTypeSize(const Type *Ty) { if (unsigned Size = Ty->getPrimitiveSize()) return Size; return TD->getTypeSize(Ty); // Must be a pointer } Value *ComputeAuxIndVarValue(InductionVariable &IV, Value *CIV); void ReplaceIndVar(InductionVariable &IV, Value *Counter); void runOnLoop(Loop *L); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetData>(); // Need pointer size AU.addRequired<LoopInfo>(); AU.addRequiredID(LoopSimplifyID); AU.addPreservedID(LoopSimplifyID); AU.setPreservesCFG(); } }; RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables"); } Pass *llvm::createIndVarSimplifyPass() { return new IndVarSimplify(); } void IndVarSimplify::runOnLoop(Loop *Loop) { // Transform all subloops before this loop... for (unsigned i = 0, e = Loop->getSubLoops().size(); i != e; ++i) runOnLoop(Loop->getSubLoops()[i]); // Get the header node for this loop. All of the phi nodes that could be // induction variables must live in this basic block. // BasicBlock *Header = Loop->getHeader(); // Loop over all of the PHI nodes in the basic block, calculating the // induction variables that they represent... stuffing the induction variable // info into a vector... // std::vector<InductionVariable> IndVars; // Induction variables for block BasicBlock::iterator AfterPHIIt = Header->begin(); for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt) IndVars.push_back(InductionVariable(PN, Loops)); // AfterPHIIt now points to first non-phi instruction... // If there are no phi nodes in this basic block, there can't be indvars... if (IndVars.empty()) return; // Loop over the induction variables, looking for a canonical induction // variable, and checking to make sure they are not all unknown induction // variables. Keep track of the largest integer size of the induction // variable. // InductionVariable *Canonical = 0; unsigned MaxSize = 0; for (unsigned i = 0; i != IndVars.size(); ++i) { InductionVariable &IV = IndVars[i]; if (IV.InductionType != InductionVariable::Unknown) { unsigned IVSize = getTypeSize(IV.Phi->getType()); if (IV.InductionType == InductionVariable::Canonical && !isa<PointerType>(IV.Phi->getType()) && IVSize >= MaxSize) Canonical = &IV; if (IVSize > MaxSize) MaxSize = IVSize; // If this variable is larger than the currently identified canonical // indvar, the canonical indvar is not usable. if (Canonical && IVSize > getTypeSize(Canonical->Phi->getType())) Canonical = 0; } } // No induction variables, bail early... don't add a canonical indvar if (MaxSize == 0) return; // Figure out what the exit condition of the loop is. We can currently only // handle loops with a single exit. If we cannot figure out what the // termination condition is, we leave this variable set to null. // SetCondInst *TermCond = 0; if (Loop->getExitBlocks().size() == 1) { // Get ExitingBlock - the basic block in the loop which contains the branch // out of the loop. BasicBlock *Exit = Loop->getExitBlocks()[0]; pred_iterator PI = pred_begin(Exit); assert(PI != pred_end(Exit) && "Should have one predecessor in loop!"); BasicBlock *ExitingBlock = *PI; assert(++PI == pred_end(Exit) && "Exit block should have one pred!"); assert(Loop->isLoopExit(ExitingBlock) && "Exiting block is not loop exit!"); // Since the block is in the loop, yet branches out of it, we know that the // block must end with multiple destination terminator. Which means it is // either a conditional branch, a switch instruction, or an invoke. if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) { assert(BI->isConditional() && "Unconditional branch has multiple succs?"); TermCond = dyn_cast<SetCondInst>(BI->getCondition()); } else { // NOTE: if people actually exit loops with switch instructions, we could // handle them, but I don't think this is important enough to spend time // thinking about. assert(isa<SwitchInst>(ExitingBlock->getTerminator()) || isa<InvokeInst>(ExitingBlock->getTerminator()) && "Unknown multi-successor terminator!"); } } if (TermCond) DEBUG(std::cerr << "INDVAR: Found termination condition: " << *TermCond); // Okay, we want to convert other induction variables to use a canonical // indvar. If we don't have one, add one now... if (!Canonical) { // Create the PHI node for the new induction variable, and insert the phi // node at the start of the PHI nodes... const Type *IVType; switch (MaxSize) { default: assert(0 && "Unknown integer type size!"); case 1: IVType = Type::UByteTy; break; case 2: IVType = Type::UShortTy; break; case 4: IVType = Type::UIntTy; break; case 8: IVType = Type::ULongTy; break; } PHINode *PN = new PHINode(IVType, "cann-indvar", Header->begin()); // Create the increment instruction to add one to the counter... Instruction *Add = BinaryOperator::create(Instruction::Add, PN, ConstantUInt::get(IVType, 1), "next-indvar", AfterPHIIt); // Figure out which block is incoming and which is the backedge for the loop BasicBlock *Incoming, *BackEdgeBlock; pred_iterator PI = pred_begin(Header); assert(PI != pred_end(Header) && "Loop headers should have 2 preds!"); if (Loop->contains(*PI)) { // First pred is back edge... BackEdgeBlock = *PI++; Incoming = *PI++; } else { Incoming = *PI++; BackEdgeBlock = *PI++; } assert(PI == pred_end(Header) && "Loop headers should have 2 preds!"); // Add incoming values for the PHI node... PN->addIncoming(Constant::getNullValue(IVType), Incoming); PN->addIncoming(Add, BackEdgeBlock); // Analyze the new induction variable... IndVars.push_back(InductionVariable(PN, Loops)); assert(IndVars.back().InductionType == InductionVariable::Canonical && "Just inserted canonical indvar that is not canonical!"); Canonical = &IndVars.back(); ++NumInserted; Changed = true; DEBUG(std::cerr << "INDVAR: Inserted canonical iv: " << *PN); } else { // If we have a canonical induction variable, make sure that it is the first // one in the basic block. if (&Header->front() != Canonical->Phi) Header->getInstList().splice(Header->begin(), Header->getInstList(), Canonical->Phi); DEBUG(std::cerr << "IndVar: Existing canonical iv used: " << *Canonical->Phi); } DEBUG(std::cerr << "INDVAR: Replacing Induction variables:\n"); // Get the current loop iteration count, which is always the value of the // canonical phi node... // PHINode *IterCount = Canonical->Phi; // Loop through and replace all of the auxiliary induction variables with // references to the canonical induction variable... // for (unsigned i = 0; i != IndVars.size(); ++i) { InductionVariable *IV = &IndVars[i]; DEBUG(IV->print(std::cerr)); // Don't modify the canonical indvar or unrecognized indvars... if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) { ReplaceIndVar(*IV, IterCount); Changed = true; ++NumRemoved; } } } /// ComputeAuxIndVarValue - Given an auxillary induction variable, compute and /// return a value which will always be equal to the induction variable PHI, but /// is based off of the canonical induction variable CIV. /// Value *IndVarSimplify::ComputeAuxIndVarValue(InductionVariable &IV, Value *CIV){ Instruction *Phi = IV.Phi; const Type *IVTy = Phi->getType(); if (isa<PointerType>(IVTy)) // If indexing into a pointer, make the IVTy = TD->getIntPtrType(); // index the appropriate type. BasicBlock::iterator AfterPHIIt = Phi; while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt; Value *Val = CIV; if (Val->getType() != IVTy) Val = new CastInst(Val, IVTy, Val->getName(), AfterPHIIt); if (!isa<ConstantInt>(IV.Step) || // If the step != 1 !cast<ConstantInt>(IV.Step)->equalsInt(1)) { // If the types are not compatible, insert a cast now... if (IV.Step->getType() != IVTy) IV.Step = new CastInst(IV.Step, IVTy, IV.Step->getName(), AfterPHIIt); Val = BinaryOperator::create(Instruction::Mul, Val, IV.Step, Phi->getName()+"-scale", AfterPHIIt); } // If this is a pointer indvar... if (isa<PointerType>(Phi->getType())) { std::vector<Value*> Idx; // FIXME: this should not be needed when we fix PR82! if (Val->getType() != Type::LongTy) Val = new CastInst(Val, Type::LongTy, Val->getName(), AfterPHIIt); Idx.push_back(Val); Val = new GetElementPtrInst(IV.Start, Idx, Phi->getName()+"-offset", AfterPHIIt); } else if (!isa<Constant>(IV.Start) || // If Start != 0... !cast<Constant>(IV.Start)->isNullValue()) { // If the types are not compatible, insert a cast now... if (IV.Start->getType() != IVTy) IV.Start = new CastInst(IV.Start, IVTy, IV.Start->getName(), AfterPHIIt); // Insert the instruction after the phi nodes... Val = BinaryOperator::create(Instruction::Add, Val, IV.Start, Phi->getName()+"-offset", AfterPHIIt); } // If the PHI node has a different type than val is, insert a cast now... if (Val->getType() != Phi->getType()) Val = new CastInst(Val, Phi->getType(), Val->getName(), AfterPHIIt); // Move the PHI name to it's new equivalent value... std::string OldName = Phi->getName(); Phi->setName(""); Val->setName(OldName); return Val; } // ReplaceIndVar - Replace all uses of the specified induction variable with // expressions computed from the specified loop iteration counter variable. // Return true if instructions were deleted. void IndVarSimplify::ReplaceIndVar(InductionVariable &IV, Value *CIV) { Value *IndVarVal = 0; PHINode *Phi = IV.Phi; assert(Phi->getNumOperands() == 4 && "Only expect induction variables in canonical loops!"); // Remember the incoming values used by the PHI node std::vector<Value*> PHIOps; PHIOps.reserve(2); PHIOps.push_back(Phi->getIncomingValue(0)); PHIOps.push_back(Phi->getIncomingValue(1)); // Delete all of the operands of the PHI node... so that the to-be-deleted PHI // node does not cause any expressions to be computed that would not otherwise // be. Phi->dropAllReferences(); // Now that we are rid of unneeded uses of the PHI node, replace any remaining // ones with the appropriate code using the canonical induction variable. while (!Phi->use_empty()) { Instruction *U = cast<Instruction>(Phi->use_back()); // TODO: Perform LFTR here if possible if (0) { } else { // Replace all uses of the old PHI node with the new computed value... if (IndVarVal == 0) IndVarVal = ComputeAuxIndVarValue(IV, CIV); U->replaceUsesOfWith(Phi, IndVarVal); } } // If the PHI is the last user of any instructions for computing PHI nodes // that are irrelevant now, delete those instructions. while (!PHIOps.empty()) { Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back()); PHIOps.pop_back(); if (MaybeDead && isInstructionTriviallyDead(MaybeDead) && (!isa<PHINode>(MaybeDead) || MaybeDead->getParent() != Phi->getParent())) { PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(), MaybeDead->op_end()); MaybeDead->getParent()->getInstList().erase(MaybeDead); // Erase any duplicates entries in the PHIOps list. std::vector<Value*>::iterator It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead); while (It != PHIOps.end()) { PHIOps.erase(It); It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead); } } } // Delete the old, now unused, phi node... Phi->getParent()->getInstList().erase(Phi); } <|endoftext|>
<commit_before>//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Guarantees that all loops with identifiable, linear, induction variables will // be transformed to have a single, canonical, induction variable. After this // pass runs, it guarantees the the first PHI node of the header block in the // loop is the canonical induction variable if there is one. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Constants.h" #include "llvm/Type.h" #include "llvm/iPHINode.h" #include "llvm/iOther.h" #include "llvm/Analysis/InductionVariable.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Support/CFG.h" #include "llvm/Transforms/Utils/Local.h" #include "Support/Debug.h" #include "Support/Statistic.h" #include "Support/STLExtras.h" #include <algorithm> using namespace llvm; namespace { Statistic<> NumRemoved ("indvars", "Number of aux indvars removed"); Statistic<> NumInserted("indvars", "Number of canonical indvars added"); } // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a // name... // static Instruction *InsertCast(Value *Val, const Type *Ty, Instruction *InsertBefore) { return new CastInst(Val, Ty, Val->getName()+"-casted", InsertBefore); } static bool TransformLoop(LoopInfo *Loops, Loop *Loop) { // Transform all subloops before this loop... bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(), Loop->getSubLoops().end(), std::bind1st(std::ptr_fun(TransformLoop), Loops)); // Get the header node for this loop. All of the phi nodes that could be // induction variables must live in this basic block. // BasicBlock *Header = Loop->getHeader(); // Loop over all of the PHI nodes in the basic block, calculating the // induction variables that they represent... stuffing the induction variable // info into a vector... // std::vector<InductionVariable> IndVars; // Induction variables for block BasicBlock::iterator AfterPHIIt = Header->begin(); for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt) IndVars.push_back(InductionVariable(PN, Loops)); // AfterPHIIt now points to first non-phi instruction... // If there are no phi nodes in this basic block, there can't be indvars... if (IndVars.empty()) return Changed; // Loop over the induction variables, looking for a canonical induction // variable, and checking to make sure they are not all unknown induction // variables. // bool FoundIndVars = false; InductionVariable *Canonical = 0; for (unsigned i = 0; i < IndVars.size(); ++i) { if (IndVars[i].InductionType == InductionVariable::Canonical && !isa<PointerType>(IndVars[i].Phi->getType())) Canonical = &IndVars[i]; if (IndVars[i].InductionType != InductionVariable::Unknown) FoundIndVars = true; } // No induction variables, bail early... don't add a canonical indvar if (!FoundIndVars) return Changed; // Okay, we want to convert other induction variables to use a canonical // indvar. If we don't have one, add one now... if (!Canonical) { // Create the PHI node for the new induction variable, and insert the phi // node at the start of the PHI nodes... PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", Header->begin()); // Create the increment instruction to add one to the counter... Instruction *Add = BinaryOperator::create(Instruction::Add, PN, ConstantUInt::get(Type::UIntTy,1), "add1-indvar", AfterPHIIt); // Figure out which block is incoming and which is the backedge for the loop BasicBlock *Incoming, *BackEdgeBlock; pred_iterator PI = pred_begin(Header); assert(PI != pred_end(Header) && "Loop headers should have 2 preds!"); if (Loop->contains(*PI)) { // First pred is back edge... BackEdgeBlock = *PI++; Incoming = *PI++; } else { Incoming = *PI++; BackEdgeBlock = *PI++; } assert(PI == pred_end(Header) && "Loop headers should have 2 preds!"); // Add incoming values for the PHI node... PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming); PN->addIncoming(Add, BackEdgeBlock); // Analyze the new induction variable... IndVars.push_back(InductionVariable(PN, Loops)); assert(IndVars.back().InductionType == InductionVariable::Canonical && "Just inserted canonical indvar that is not canonical!"); Canonical = &IndVars.back(); ++NumInserted; Changed = true; } else { // If we have a canonical induction variable, make sure that it is the first // one in the basic block. if (&Header->front() != Canonical->Phi) Header->getInstList().splice(Header->begin(), Header->getInstList(), Canonical->Phi); } DEBUG(std::cerr << "Induction variables:\n"); // Get the current loop iteration count, which is always the value of the // canonical phi node... // PHINode *IterCount = Canonical->Phi; // Loop through and replace all of the auxiliary induction variables with // references to the canonical induction variable... // for (unsigned i = 0; i < IndVars.size(); ++i) { InductionVariable *IV = &IndVars[i]; DEBUG(IV->print(std::cerr)); while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt; // Don't do math with pointers... const Type *IVTy = IV->Phi->getType(); if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy; // Don't modify the canonical indvar or unrecognized indvars... if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) { Instruction *Val = IterCount; if (!isa<ConstantInt>(IV->Step) || // If the step != 1 !cast<ConstantInt>(IV->Step)->equalsInt(1)) { // If the types are not compatible, insert a cast now... if (Val->getType() != IVTy) Val = InsertCast(Val, IVTy, AfterPHIIt); if (IV->Step->getType() != IVTy) IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt); Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, IV->Phi->getName()+"-scale", AfterPHIIt); } // If the start != 0 if (IV->Start != Constant::getNullValue(IV->Start->getType())) { // If the types are not compatible, insert a cast now... if (Val->getType() != IVTy) Val = InsertCast(Val, IVTy, AfterPHIIt); if (IV->Start->getType() != IVTy) IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt); // Insert the instruction after the phi nodes... Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, IV->Phi->getName()+"-offset", AfterPHIIt); } // If the PHI node has a different type than val is, insert a cast now... if (Val->getType() != IV->Phi->getType()) Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt); // Replace all uses of the old PHI node with the new computed value... IV->Phi->replaceAllUsesWith(Val); // Move the PHI name to it's new equivalent value... std::string OldName = IV->Phi->getName(); IV->Phi->setName(""); Val->setName(OldName); // Get the incoming values used by the PHI node std::vector<Value*> PHIOps; PHIOps.reserve(IV->Phi->getNumIncomingValues()); for (unsigned i = 0, e = IV->Phi->getNumIncomingValues(); i != e; ++i) PHIOps.push_back(IV->Phi->getIncomingValue(i)); // Delete the old, now unused, phi node... Header->getInstList().erase(IV->Phi); // If the PHI is the last user of any instructions for computing PHI nodes // that are irrelevant now, delete those instructions. while (!PHIOps.empty()) { Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back()); PHIOps.pop_back(); if (MaybeDead && isInstructionTriviallyDead(MaybeDead)) { PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(), MaybeDead->op_end()); MaybeDead->getParent()->getInstList().erase(MaybeDead); // Erase any duplicates entries in the PHIOps list. std::vector<Value*>::iterator It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead); while (It != PHIOps.end()) { PHIOps.erase(It); It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead); } // Erasing the instruction could invalidate the AfterPHI iterator! AfterPHIIt = Header->begin(); } } Changed = true; ++NumRemoved; } } return Changed; } namespace { struct InductionVariableSimplify : public FunctionPass { virtual bool runOnFunction(Function &) { LoopInfo &LI = getAnalysis<LoopInfo>(); // Induction Variables live in the header nodes of loops return reduce_apply_bool(LI.getTopLevelLoops().begin(), LI.getTopLevelLoops().end(), std::bind1st(std::ptr_fun(TransformLoop), &LI)); } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<LoopInfo>(); AU.addRequiredID(LoopSimplifyID); AU.setPreservesCFG(); } }; RegisterOpt<InductionVariableSimplify> X("indvars", "Canonicalize Induction Variables"); } Pass *llvm::createIndVarSimplifyPass() { return new InductionVariableSimplify(); } <commit_msg>Fix PR194<commit_after>//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Guarantees that all loops with identifiable, linear, induction variables will // be transformed to have a single, canonical, induction variable. After this // pass runs, it guarantees the the first PHI node of the header block in the // loop is the canonical induction variable if there is one. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Constants.h" #include "llvm/Type.h" #include "llvm/iPHINode.h" #include "llvm/iOther.h" #include "llvm/Analysis/InductionVariable.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Support/CFG.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/Utils/Local.h" #include "Support/Debug.h" #include "Support/Statistic.h" using namespace llvm; namespace { Statistic<> NumRemoved ("indvars", "Number of aux indvars removed"); Statistic<> NumInserted("indvars", "Number of canonical indvars added"); class IndVarSimplify : public FunctionPass { LoopInfo *Loops; TargetData *TD; public: virtual bool runOnFunction(Function &) { Loops = &getAnalysis<LoopInfo>(); TD = &getAnalysis<TargetData>(); // Induction Variables live in the header nodes of loops bool Changed = false; for (unsigned i = 0, e = Loops->getTopLevelLoops().size(); i != e; ++i) Changed |= runOnLoop(Loops->getTopLevelLoops()[i]); return Changed; } unsigned getTypeSize(const Type *Ty) { if (unsigned Size = Ty->getPrimitiveSize()) return Size; return TD->getTypeSize(Ty); // Must be a pointer } bool runOnLoop(Loop *L); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetData>(); // Need pointer size AU.addRequired<LoopInfo>(); AU.addRequiredID(LoopSimplifyID); AU.addPreservedID(LoopSimplifyID); AU.setPreservesCFG(); } }; RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables"); } Pass *llvm::createIndVarSimplifyPass() { return new IndVarSimplify(); } bool IndVarSimplify::runOnLoop(Loop *Loop) { // Transform all subloops before this loop... bool Changed = false; for (unsigned i = 0, e = Loop->getSubLoops().size(); i != e; ++i) Changed |= runOnLoop(Loop->getSubLoops()[i]); // Get the header node for this loop. All of the phi nodes that could be // induction variables must live in this basic block. // BasicBlock *Header = Loop->getHeader(); // Loop over all of the PHI nodes in the basic block, calculating the // induction variables that they represent... stuffing the induction variable // info into a vector... // std::vector<InductionVariable> IndVars; // Induction variables for block BasicBlock::iterator AfterPHIIt = Header->begin(); for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt) IndVars.push_back(InductionVariable(PN, Loops)); // AfterPHIIt now points to first non-phi instruction... // If there are no phi nodes in this basic block, there can't be indvars... if (IndVars.empty()) return Changed; // Loop over the induction variables, looking for a canonical induction // variable, and checking to make sure they are not all unknown induction // variables. Keep track of the largest integer size of the induction // variable. // InductionVariable *Canonical = 0; unsigned MaxSize = 0; for (unsigned i = 0; i != IndVars.size(); ++i) { InductionVariable &IV = IndVars[i]; if (IV.InductionType != InductionVariable::Unknown) { unsigned IVSize = getTypeSize(IV.Phi->getType()); if (IV.InductionType == InductionVariable::Canonical && !isa<PointerType>(IV.Phi->getType()) && IVSize >= MaxSize) Canonical = &IV; if (IVSize > MaxSize) MaxSize = IVSize; // If this variable is larger than the currently identified canonical // indvar, the canonical indvar is not usable. if (Canonical && IVSize > getTypeSize(Canonical->Phi->getType())) Canonical = 0; } } // No induction variables, bail early... don't add a canonical indvar if (MaxSize == 0) return Changed; // Okay, we want to convert other induction variables to use a canonical // indvar. If we don't have one, add one now... if (!Canonical) { // Create the PHI node for the new induction variable, and insert the phi // node at the start of the PHI nodes... const Type *IVType; switch (MaxSize) { default: assert(0 && "Unknown integer type size!"); case 1: IVType = Type::UByteTy; break; case 2: IVType = Type::UShortTy; break; case 4: IVType = Type::UIntTy; break; case 8: IVType = Type::ULongTy; break; } PHINode *PN = new PHINode(IVType, "cann-indvar", Header->begin()); // Create the increment instruction to add one to the counter... Instruction *Add = BinaryOperator::create(Instruction::Add, PN, ConstantUInt::get(IVType, 1), "next-indvar", AfterPHIIt); // Figure out which block is incoming and which is the backedge for the loop BasicBlock *Incoming, *BackEdgeBlock; pred_iterator PI = pred_begin(Header); assert(PI != pred_end(Header) && "Loop headers should have 2 preds!"); if (Loop->contains(*PI)) { // First pred is back edge... BackEdgeBlock = *PI++; Incoming = *PI++; } else { Incoming = *PI++; BackEdgeBlock = *PI++; } assert(PI == pred_end(Header) && "Loop headers should have 2 preds!"); // Add incoming values for the PHI node... PN->addIncoming(Constant::getNullValue(IVType), Incoming); PN->addIncoming(Add, BackEdgeBlock); // Analyze the new induction variable... IndVars.push_back(InductionVariable(PN, Loops)); assert(IndVars.back().InductionType == InductionVariable::Canonical && "Just inserted canonical indvar that is not canonical!"); Canonical = &IndVars.back(); ++NumInserted; Changed = true; } else { // If we have a canonical induction variable, make sure that it is the first // one in the basic block. if (&Header->front() != Canonical->Phi) Header->getInstList().splice(Header->begin(), Header->getInstList(), Canonical->Phi); } DEBUG(std::cerr << "Induction variables:\n"); // Get the current loop iteration count, which is always the value of the // canonical phi node... // PHINode *IterCount = Canonical->Phi; // Loop through and replace all of the auxiliary induction variables with // references to the canonical induction variable... // for (unsigned i = 0; i != IndVars.size(); ++i) { InductionVariable *IV = &IndVars[i]; DEBUG(IV->print(std::cerr)); while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt; // Don't do math with pointers... const Type *IVTy = IV->Phi->getType(); if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy; // Don't modify the canonical indvar or unrecognized indvars... if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) { Instruction *Val = IterCount; if (!isa<ConstantInt>(IV->Step) || // If the step != 1 !cast<ConstantInt>(IV->Step)->equalsInt(1)) { // If the types are not compatible, insert a cast now... if (Val->getType() != IVTy) Val = new CastInst(Val, IVTy, Val->getName(), AfterPHIIt); if (IV->Step->getType() != IVTy) IV->Step = new CastInst(IV->Step, IVTy, IV->Step->getName(), AfterPHIIt); Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, IV->Phi->getName()+"-scale", AfterPHIIt); } // If the start != 0 if (IV->Start != Constant::getNullValue(IV->Start->getType())) { // If the types are not compatible, insert a cast now... if (Val->getType() != IVTy) Val = new CastInst(Val, IVTy, Val->getName(), AfterPHIIt); if (IV->Start->getType() != IVTy) IV->Start = new CastInst(IV->Start, IVTy, IV->Start->getName(), AfterPHIIt); // Insert the instruction after the phi nodes... Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, IV->Phi->getName()+"-offset", AfterPHIIt); } // If the PHI node has a different type than val is, insert a cast now... if (Val->getType() != IV->Phi->getType()) Val = new CastInst(Val, IV->Phi->getType(), Val->getName(), AfterPHIIt); // Replace all uses of the old PHI node with the new computed value... IV->Phi->replaceAllUsesWith(Val); // Move the PHI name to it's new equivalent value... std::string OldName = IV->Phi->getName(); IV->Phi->setName(""); Val->setName(OldName); // Get the incoming values used by the PHI node std::vector<Value*> PHIOps; PHIOps.reserve(IV->Phi->getNumIncomingValues()); for (unsigned i = 0, e = IV->Phi->getNumIncomingValues(); i != e; ++i) PHIOps.push_back(IV->Phi->getIncomingValue(i)); // Delete the old, now unused, phi node... Header->getInstList().erase(IV->Phi); // If the PHI is the last user of any instructions for computing PHI nodes // that are irrelevant now, delete those instructions. while (!PHIOps.empty()) { Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back()); PHIOps.pop_back(); if (MaybeDead && isInstructionTriviallyDead(MaybeDead)) { PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(), MaybeDead->op_end()); MaybeDead->getParent()->getInstList().erase(MaybeDead); // Erase any duplicates entries in the PHIOps list. std::vector<Value*>::iterator It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead); while (It != PHIOps.end()) { PHIOps.erase(It); It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead); } // Erasing the instruction could invalidate the AfterPHI iterator! AfterPHIIt = Header->begin(); } } Changed = true; ++NumRemoved; } } return Changed; } <|endoftext|>
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/eval/simple_tensor.h> #include <vespa/eval/eval/simple_tensor_engine.h> #include <vespa/eval/eval/simple_value.h> #include <vespa/eval/eval/fast_value.h> #include <vespa/eval/tensor/default_tensor_engine.h> #include <vespa/eval/tensor/dense/dense_replace_type_function.h> #include <vespa/eval/tensor/dense/dense_cell_range_function.h> #include <vespa/eval/tensor/dense/dense_lambda_peek_function.h> #include <vespa/eval/tensor/dense/dense_lambda_function.h> #include <vespa/eval/tensor/dense/dense_fast_rename_optimizer.h> #include <vespa/eval/tensor/dense/dense_tensor.h> #include <vespa/eval/eval/test/tensor_model.hpp> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/eval/eval/tensor_nodes.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/stash.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::tensor; using namespace vespalib::eval::tensor_function; using EvalMode = DenseLambdaFunction::EvalMode; namespace vespalib::tensor { std::ostream &operator<<(std::ostream &os, EvalMode eval_mode) { switch(eval_mode) { case EvalMode::COMPILED: return os << "COMPILED"; case EvalMode::INTERPRETED: return os << "INTERPRETED"; } abort(); } } const TensorEngine &prod_engine = DefaultTensorEngine::ref(); const ValueBuilderFactory &simple_factory = SimpleValueBuilderFactory::get(); EvalFixture::ParamRepo make_params() { return EvalFixture::ParamRepo() .add("a", spec(1)) .add("b", spec(2)) .add("x3", spec({x(3)}, N())) .add("x3f", spec(float_cells({x(3)}), N())) .add("x3m", spec({x({"0", "1", "2"})}, N())) .add("x3y5", spec({x(3), y(5)}, N())) .add("x3y5f", spec(float_cells({x(3), y(5)}), N())) .add("x15", spec({x(15)}, N())) .add("x15f", spec(float_cells({x(15)}), N())); } EvalFixture::ParamRepo param_repo = make_params(); template <typename T, typename F> void verify_impl(const vespalib::string &expr, const vespalib::string &expect, F &&inspect) { EvalFixture fixture(prod_engine, expr, param_repo, true); EvalFixture slow_fixture(prod_engine, expr, param_repo, false); EvalFixture simple_factory_fixture(simple_factory, expr, param_repo, false); EXPECT_EQUAL(fixture.result(), slow_fixture.result()); EXPECT_EQUAL(fixture.result(), simple_factory_fixture.result()); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expect, param_repo)); auto info = fixture.find_all<T>(); if (EXPECT_EQUAL(info.size(), 1u)) { inspect(info[0]); } } template <typename T> void verify_impl(const vespalib::string &expr, const vespalib::string &expect) { verify_impl<T>(expr, expect, [](const T*){}); } void verify_generic(const vespalib::string &expr, const vespalib::string &expect, EvalMode expect_eval_mode) { verify_impl<DenseLambdaFunction>(expr, expect, [&](const DenseLambdaFunction *info) { EXPECT_EQUAL(info->eval_mode(), expect_eval_mode); }); } void verify_reshape(const vespalib::string &expr, const vespalib::string &expect) { verify_impl<DenseReplaceTypeFunction>(expr, expect); } void verify_range(const vespalib::string &expr, const vespalib::string &expect) { verify_impl<DenseCellRangeFunction>(expr, expect); } void verify_idx_fun(const vespalib::string &expr, const vespalib::string &expect, const vespalib::string &expect_idx_fun) { verify_impl<DenseLambdaPeekFunction>(expr, expect, [&](const DenseLambdaPeekFunction *info) { EXPECT_EQUAL(info->idx_fun_dump(), expect_idx_fun); }); } void verify_const(const vespalib::string &expr, const vespalib::string &expect) { verify_impl<ConstValue>(expr, expect); } //----------------------------------------------------------------------------- TEST("require that simple constant tensor lambda works") { TEST_DO(verify_const("tensor(x[3])(x+1)", "tensor(x[3]):[1,2,3]")); } TEST("require that simple dynamic tensor lambda works") { TEST_DO(verify_generic("tensor(x[3])(x+a)", "tensor(x[3]):[1,2,3]", EvalMode::COMPILED)); } TEST("require that compiled multi-dimensional multi-param dynamic tensor lambda works") { TEST_DO(verify_generic("tensor(x[3],y[2])((b-a)+x+y)", "tensor(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::COMPILED)); TEST_DO(verify_generic("tensor<float>(x[3],y[2])((b-a)+x+y)", "tensor<float>(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::COMPILED)); } TEST("require that interpreted multi-dimensional multi-param dynamic tensor lambda works") { TEST_DO(verify_generic("tensor(x[3],y[2])((x3{x:(a)}-a)+x+y)", "tensor(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor<float>(x[3],y[2])((x3{x:(a)}-a)+x+y)", "tensor<float>(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::INTERPRETED)); } TEST("require that tensor lambda can be used for tensor slicing") { TEST_DO(verify_generic("tensor(x[2])(x3{x:(x+a)})", "tensor(x[2]):[2,3]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor(x[2])(a+x3{x:(x)})", "tensor(x[2]):[2,3]", EvalMode::INTERPRETED)); } TEST("require that tensor lambda can be used for cell type casting") { TEST_DO(verify_idx_fun("tensor(x[3])(x3f{x:(x)})", "tensor(x[3]):[1,2,3]", "f(x)(x)")); TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3{x:(x)})", "tensor<float>(x[3]):[1,2,3]", "f(x)(x)")); } TEST("require that tensor lambda can be used to convert from sparse to dense tensors") { TEST_DO(verify_generic("tensor(x[3])(x3m{x:(x)})", "tensor(x[3]):[1,2,3]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor(x[2])(x3m{x:(x)})", "tensor(x[2]):[1,2]", EvalMode::INTERPRETED)); } TEST("require that constant nested tensor lambda using tensor peek works") { TEST_DO(verify_const("tensor(x[2])(tensor(y[2])((x+y)+1){y:(x)})", "tensor(x[2]):[1,3]")); } TEST("require that dynamic nested tensor lambda using tensor peek works") { TEST_DO(verify_generic("tensor(x[2])(tensor(y[2])((x+y)+a){y:(x)})", "tensor(x[2]):[1,3]", EvalMode::INTERPRETED)); } TEST("require that tensor reshape is optimized") { TEST_DO(verify_reshape("tensor(x[15])(x3y5{x:(x/5),y:(x%5)})", "x15")); TEST_DO(verify_reshape("tensor(x[3],y[5])(x15{x:(x*5+y)})", "x3y5")); TEST_DO(verify_reshape("tensor<float>(x[15])(x3y5f{x:(x/5),y:(x%5)})", "x15f")); } TEST("require that tensor reshape with non-matching cell type requires cell copy") { TEST_DO(verify_idx_fun("tensor(x[15])(x3y5f{x:(x/5),y:(x%5)})", "x15", "f(x)((floor((x/5))*5)+(x%5))")); TEST_DO(verify_idx_fun("tensor<float>(x[15])(x3y5{x:(x/5),y:(x%5)})", "x15f", "f(x)((floor((x/5))*5)+(x%5))")); TEST_DO(verify_idx_fun("tensor(x[3],y[5])(x15f{x:(x*5+y)})", "x3y5", "f(x,y)((x*5)+y)")); TEST_DO(verify_idx_fun("tensor<float>(x[3],y[5])(x15{x:(x*5+y)})", "x3y5f", "f(x,y)((x*5)+y)")); } TEST("require that tensor cell subrange view is optimized") { TEST_DO(verify_range("tensor(y[5])(x3y5{x:1,y:(y)})", "x3y5{x:1}")); TEST_DO(verify_range("tensor(x[3])(x15{x:(x+5)})", "tensor(x[3]):[6,7,8]")); TEST_DO(verify_range("tensor<float>(y[5])(x3y5f{x:1,y:(y)})", "x3y5f{x:1}")); TEST_DO(verify_range("tensor<float>(x[3])(x15f{x:(x+5)})", "tensor<float>(x[3]):[6,7,8]")); } TEST("require that tensor cell subrange with non-matching cell type requires cell copy") { TEST_DO(verify_idx_fun("tensor(x[3])(x15f{x:(x+5)})", "tensor(x[3]):[6,7,8]", "f(x)(x+5)")); TEST_DO(verify_idx_fun("tensor<float>(x[3])(x15{x:(x+5)})", "tensor<float>(x[3]):[6,7,8]", "f(x)(x+5)")); } TEST("require that non-continuous cell extraction is optimized") { TEST_DO(verify_idx_fun("tensor(x[3])(x3y5{x:(x),y:2})", "x3y5{y:2}", "f(x)((floor(x)*5)+2)")); TEST_DO(verify_idx_fun("tensor(x[3])(x3y5f{x:(x),y:2})", "x3y5{y:2}", "f(x)((floor(x)*5)+2)")); TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3y5{x:(x),y:2})", "x3y5f{y:2}", "f(x)((floor(x)*5)+2)")); TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3y5f{x:(x),y:2})", "x3y5f{y:2}", "f(x)((floor(x)*5)+2)")); } TEST("require that out-of-bounds cell extraction is not optimized") { TEST_DO(verify_generic("tensor(x[3])(x3y5{x:1,y:(x+3)})", "tensor(x[3]):[9,10,0]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor(x[3])(x3y5{x:1,y:(x-1)})", "tensor(x[3]):[0,6,7]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor(x[3])(x3y5{x:(x+1),y:(x)})", "tensor(x[3]):[6,12,0]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor(x[3])(x3y5{x:(x-1),y:(x)})", "tensor(x[3]):[0,2,8]", EvalMode::INTERPRETED)); } TEST("require that non-double result from inner tensor lambda function fails type resolving") { auto fun_a = Function::parse("tensor(x[2])(a)"); auto fun_b = Function::parse("tensor(x[2])(a{y:(x)})"); NodeTypes types_ad(*fun_a, {ValueType::from_spec("double")}); NodeTypes types_at(*fun_a, {ValueType::from_spec("tensor(y[2])")}); NodeTypes types_bd(*fun_b, {ValueType::from_spec("double")}); NodeTypes types_bt(*fun_b, {ValueType::from_spec("tensor(y[2])")}); EXPECT_EQUAL(types_ad.get_type(fun_a->root()).to_spec(), "tensor(x[2])"); EXPECT_EQUAL(types_at.get_type(fun_a->root()).to_spec(), "error"); EXPECT_EQUAL(types_bd.get_type(fun_b->root()).to_spec(), "error"); EXPECT_EQUAL(types_bt.get_type(fun_b->root()).to_spec(), "tensor(x[2])"); } TEST("require that type resolving also include nodes in the inner tensor lambda function") { auto fun = Function::parse("tensor(x[2])(a)"); NodeTypes types(*fun, {ValueType::from_spec("double")}); auto lambda = nodes::as<nodes::TensorLambda>(fun->root()); ASSERT_TRUE(lambda != nullptr); EXPECT_EQUAL(types.get_type(*lambda).to_spec(), "tensor(x[2])"); auto symbol = nodes::as<nodes::Symbol>(lambda->lambda().root()); ASSERT_TRUE(symbol != nullptr); EXPECT_EQUAL(types.get_type(*symbol).to_spec(), "double"); } TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>also add test of type exporting for inner lambdas<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/eval/eval/tensor_function.h> #include <vespa/eval/eval/simple_tensor.h> #include <vespa/eval/eval/simple_tensor_engine.h> #include <vespa/eval/eval/simple_value.h> #include <vespa/eval/eval/fast_value.h> #include <vespa/eval/tensor/default_tensor_engine.h> #include <vespa/eval/tensor/dense/dense_replace_type_function.h> #include <vespa/eval/tensor/dense/dense_cell_range_function.h> #include <vespa/eval/tensor/dense/dense_lambda_peek_function.h> #include <vespa/eval/tensor/dense/dense_lambda_function.h> #include <vespa/eval/tensor/dense/dense_fast_rename_optimizer.h> #include <vespa/eval/tensor/dense/dense_tensor.h> #include <vespa/eval/eval/test/tensor_model.hpp> #include <vespa/eval/eval/test/eval_fixture.h> #include <vespa/eval/eval/tensor_nodes.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/stash.h> using namespace vespalib; using namespace vespalib::eval; using namespace vespalib::eval::test; using namespace vespalib::tensor; using namespace vespalib::eval::tensor_function; using EvalMode = DenseLambdaFunction::EvalMode; namespace vespalib::tensor { std::ostream &operator<<(std::ostream &os, EvalMode eval_mode) { switch(eval_mode) { case EvalMode::COMPILED: return os << "COMPILED"; case EvalMode::INTERPRETED: return os << "INTERPRETED"; } abort(); } } const TensorEngine &prod_engine = DefaultTensorEngine::ref(); const ValueBuilderFactory &simple_factory = SimpleValueBuilderFactory::get(); EvalFixture::ParamRepo make_params() { return EvalFixture::ParamRepo() .add("a", spec(1)) .add("b", spec(2)) .add("x3", spec({x(3)}, N())) .add("x3f", spec(float_cells({x(3)}), N())) .add("x3m", spec({x({"0", "1", "2"})}, N())) .add("x3y5", spec({x(3), y(5)}, N())) .add("x3y5f", spec(float_cells({x(3), y(5)}), N())) .add("x15", spec({x(15)}, N())) .add("x15f", spec(float_cells({x(15)}), N())); } EvalFixture::ParamRepo param_repo = make_params(); template <typename T, typename F> void verify_impl(const vespalib::string &expr, const vespalib::string &expect, F &&inspect) { EvalFixture fixture(prod_engine, expr, param_repo, true); EvalFixture slow_fixture(prod_engine, expr, param_repo, false); EvalFixture simple_factory_fixture(simple_factory, expr, param_repo, false); EXPECT_EQUAL(fixture.result(), slow_fixture.result()); EXPECT_EQUAL(fixture.result(), simple_factory_fixture.result()); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo)); EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expect, param_repo)); auto info = fixture.find_all<T>(); if (EXPECT_EQUAL(info.size(), 1u)) { inspect(info[0]); } } template <typename T> void verify_impl(const vespalib::string &expr, const vespalib::string &expect) { verify_impl<T>(expr, expect, [](const T*){}); } void verify_generic(const vespalib::string &expr, const vespalib::string &expect, EvalMode expect_eval_mode) { verify_impl<DenseLambdaFunction>(expr, expect, [&](const DenseLambdaFunction *info) { EXPECT_EQUAL(info->eval_mode(), expect_eval_mode); }); } void verify_reshape(const vespalib::string &expr, const vespalib::string &expect) { verify_impl<DenseReplaceTypeFunction>(expr, expect); } void verify_range(const vespalib::string &expr, const vespalib::string &expect) { verify_impl<DenseCellRangeFunction>(expr, expect); } void verify_idx_fun(const vespalib::string &expr, const vespalib::string &expect, const vespalib::string &expect_idx_fun) { verify_impl<DenseLambdaPeekFunction>(expr, expect, [&](const DenseLambdaPeekFunction *info) { EXPECT_EQUAL(info->idx_fun_dump(), expect_idx_fun); }); } void verify_const(const vespalib::string &expr, const vespalib::string &expect) { verify_impl<ConstValue>(expr, expect); } //----------------------------------------------------------------------------- TEST("require that simple constant tensor lambda works") { TEST_DO(verify_const("tensor(x[3])(x+1)", "tensor(x[3]):[1,2,3]")); } TEST("require that simple dynamic tensor lambda works") { TEST_DO(verify_generic("tensor(x[3])(x+a)", "tensor(x[3]):[1,2,3]", EvalMode::COMPILED)); } TEST("require that compiled multi-dimensional multi-param dynamic tensor lambda works") { TEST_DO(verify_generic("tensor(x[3],y[2])((b-a)+x+y)", "tensor(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::COMPILED)); TEST_DO(verify_generic("tensor<float>(x[3],y[2])((b-a)+x+y)", "tensor<float>(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::COMPILED)); } TEST("require that interpreted multi-dimensional multi-param dynamic tensor lambda works") { TEST_DO(verify_generic("tensor(x[3],y[2])((x3{x:(a)}-a)+x+y)", "tensor(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor<float>(x[3],y[2])((x3{x:(a)}-a)+x+y)", "tensor<float>(x[3],y[2]):[[1,2],[2,3],[3,4]]", EvalMode::INTERPRETED)); } TEST("require that tensor lambda can be used for tensor slicing") { TEST_DO(verify_generic("tensor(x[2])(x3{x:(x+a)})", "tensor(x[2]):[2,3]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor(x[2])(a+x3{x:(x)})", "tensor(x[2]):[2,3]", EvalMode::INTERPRETED)); } TEST("require that tensor lambda can be used for cell type casting") { TEST_DO(verify_idx_fun("tensor(x[3])(x3f{x:(x)})", "tensor(x[3]):[1,2,3]", "f(x)(x)")); TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3{x:(x)})", "tensor<float>(x[3]):[1,2,3]", "f(x)(x)")); } TEST("require that tensor lambda can be used to convert from sparse to dense tensors") { TEST_DO(verify_generic("tensor(x[3])(x3m{x:(x)})", "tensor(x[3]):[1,2,3]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor(x[2])(x3m{x:(x)})", "tensor(x[2]):[1,2]", EvalMode::INTERPRETED)); } TEST("require that constant nested tensor lambda using tensor peek works") { TEST_DO(verify_const("tensor(x[2])(tensor(y[2])((x+y)+1){y:(x)})", "tensor(x[2]):[1,3]")); } TEST("require that dynamic nested tensor lambda using tensor peek works") { TEST_DO(verify_generic("tensor(x[2])(tensor(y[2])((x+y)+a){y:(x)})", "tensor(x[2]):[1,3]", EvalMode::INTERPRETED)); } TEST("require that tensor reshape is optimized") { TEST_DO(verify_reshape("tensor(x[15])(x3y5{x:(x/5),y:(x%5)})", "x15")); TEST_DO(verify_reshape("tensor(x[3],y[5])(x15{x:(x*5+y)})", "x3y5")); TEST_DO(verify_reshape("tensor<float>(x[15])(x3y5f{x:(x/5),y:(x%5)})", "x15f")); } TEST("require that tensor reshape with non-matching cell type requires cell copy") { TEST_DO(verify_idx_fun("tensor(x[15])(x3y5f{x:(x/5),y:(x%5)})", "x15", "f(x)((floor((x/5))*5)+(x%5))")); TEST_DO(verify_idx_fun("tensor<float>(x[15])(x3y5{x:(x/5),y:(x%5)})", "x15f", "f(x)((floor((x/5))*5)+(x%5))")); TEST_DO(verify_idx_fun("tensor(x[3],y[5])(x15f{x:(x*5+y)})", "x3y5", "f(x,y)((x*5)+y)")); TEST_DO(verify_idx_fun("tensor<float>(x[3],y[5])(x15{x:(x*5+y)})", "x3y5f", "f(x,y)((x*5)+y)")); } TEST("require that tensor cell subrange view is optimized") { TEST_DO(verify_range("tensor(y[5])(x3y5{x:1,y:(y)})", "x3y5{x:1}")); TEST_DO(verify_range("tensor(x[3])(x15{x:(x+5)})", "tensor(x[3]):[6,7,8]")); TEST_DO(verify_range("tensor<float>(y[5])(x3y5f{x:1,y:(y)})", "x3y5f{x:1}")); TEST_DO(verify_range("tensor<float>(x[3])(x15f{x:(x+5)})", "tensor<float>(x[3]):[6,7,8]")); } TEST("require that tensor cell subrange with non-matching cell type requires cell copy") { TEST_DO(verify_idx_fun("tensor(x[3])(x15f{x:(x+5)})", "tensor(x[3]):[6,7,8]", "f(x)(x+5)")); TEST_DO(verify_idx_fun("tensor<float>(x[3])(x15{x:(x+5)})", "tensor<float>(x[3]):[6,7,8]", "f(x)(x+5)")); } TEST("require that non-continuous cell extraction is optimized") { TEST_DO(verify_idx_fun("tensor(x[3])(x3y5{x:(x),y:2})", "x3y5{y:2}", "f(x)((floor(x)*5)+2)")); TEST_DO(verify_idx_fun("tensor(x[3])(x3y5f{x:(x),y:2})", "x3y5{y:2}", "f(x)((floor(x)*5)+2)")); TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3y5{x:(x),y:2})", "x3y5f{y:2}", "f(x)((floor(x)*5)+2)")); TEST_DO(verify_idx_fun("tensor<float>(x[3])(x3y5f{x:(x),y:2})", "x3y5f{y:2}", "f(x)((floor(x)*5)+2)")); } TEST("require that out-of-bounds cell extraction is not optimized") { TEST_DO(verify_generic("tensor(x[3])(x3y5{x:1,y:(x+3)})", "tensor(x[3]):[9,10,0]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor(x[3])(x3y5{x:1,y:(x-1)})", "tensor(x[3]):[0,6,7]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor(x[3])(x3y5{x:(x+1),y:(x)})", "tensor(x[3]):[6,12,0]", EvalMode::INTERPRETED)); TEST_DO(verify_generic("tensor(x[3])(x3y5{x:(x-1),y:(x)})", "tensor(x[3]):[0,2,8]", EvalMode::INTERPRETED)); } TEST("require that non-double result from inner tensor lambda function fails type resolving") { auto fun_a = Function::parse("tensor(x[2])(a)"); auto fun_b = Function::parse("tensor(x[2])(a{y:(x)})"); NodeTypes types_ad(*fun_a, {ValueType::from_spec("double")}); NodeTypes types_at(*fun_a, {ValueType::from_spec("tensor(y[2])")}); NodeTypes types_bd(*fun_b, {ValueType::from_spec("double")}); NodeTypes types_bt(*fun_b, {ValueType::from_spec("tensor(y[2])")}); EXPECT_EQUAL(types_ad.get_type(fun_a->root()).to_spec(), "tensor(x[2])"); EXPECT_EQUAL(types_at.get_type(fun_a->root()).to_spec(), "error"); EXPECT_EQUAL(types_bd.get_type(fun_b->root()).to_spec(), "error"); EXPECT_EQUAL(types_bt.get_type(fun_b->root()).to_spec(), "tensor(x[2])"); } TEST("require that type resolving also include nodes in the inner tensor lambda function") { auto fun = Function::parse("tensor(x[2])(a)"); NodeTypes types(*fun, {ValueType::from_spec("double")}); auto lambda = nodes::as<nodes::TensorLambda>(fun->root()); ASSERT_TRUE(lambda != nullptr); EXPECT_EQUAL(types.get_type(*lambda).to_spec(), "tensor(x[2])"); auto symbol = nodes::as<nodes::Symbol>(lambda->lambda().root()); ASSERT_TRUE(symbol != nullptr); EXPECT_EQUAL(types.get_type(*symbol).to_spec(), "double"); } TEST("require that type exporting also include nodes in the inner tensor lambda function") { auto fun = Function::parse("tensor(x[2])(tensor(y[2])((x+y)+a){y:(x)})"); NodeTypes types(*fun, {ValueType::from_spec("double")}); const auto &root = fun->root(); auto lambda = nodes::as<nodes::TensorLambda>(root); ASSERT_TRUE(lambda != nullptr); NodeTypes outer = types.export_types(root); ASSERT_TRUE(outer.errors().empty()); NodeTypes inner = outer.export_types(lambda->lambda().root()); EXPECT_TRUE(inner.errors().empty()); } TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before><commit_msg>Another --enable-complex fix, plus remove some atavistic code.<commit_after><|endoftext|>
<commit_before>//===--- IRGenSIL.cpp - Swift Per-Function IR Generation ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements basic setup and teardown for the class which // performs IR generation for function bodies. // //===----------------------------------------------------------------------===// #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/Support/SourceMgr.h" #include "swift/Basic/SourceLoc.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "CallEmission.h" #include "Explosion.h" #include "GenFunc.h" #include "GenMeta.h" #include "GenTuple.h" #include "IRGenModule.h" #include "IRGenSIL.h" #include "Linking.h" using namespace swift; using namespace irgen; IRGenSILFunction::IRGenSILFunction(IRGenModule &IGM, CanType t, ArrayRef<Pattern*> p, llvm::Function *fn) : IRGenFunction(IGM, t, p, ExplosionKind::Minimal, 0, fn, Prologue::None) { } IRGenSILFunction::~IRGenSILFunction() { } void IRGenSILFunction::emitSILFunction(swift::Function *f) { assert(!f->empty() && "function has no basic blocks?!"); BasicBlock *entry = f->begin(); // FIXME Map the SIL arguments to LLVM arguments. size_t bbarg_size = entry->bbarg_end() - entry->bbarg_begin(); assert(bbarg_size == 0 && "arguments not yet supported"); // Emit the function body. visitBasicBlock(entry); } void IRGenSILFunction::emitGlobalTopLevel(TranslationUnit *TU, SILModule *SILMod) { // Emit the toplevel function. if (SILMod->hasTopLevelFunction()) emitSILFunction(SILMod->getTopLevelFunction()); // FIXME: should support nonzero StartElems for interactive contexts. IRGenFunction::emitGlobalTopLevel(TU, 0); } void IRGenSILFunction::visitBasicBlock(swift::BasicBlock *BB) { // Emit the LLVM basic block. // FIXME: Use the SIL basic block's name. llvm::BasicBlock *curBB = llvm::BasicBlock::Create(IGM.getLLVMContext(), "sil"); CurFn->getBasicBlockList().push_back(curBB); Builder.SetInsertPoint(curBB); // FIXME: emit a phi node to bind the bb arguments from all the predecessor // branches. // Generate the body. for (auto &I : *BB) visit(&I); assert(Builder.hasPostTerminatorIP() && "SIL bb did not terminate block?!"); } void IRGenSILFunction::visitTupleInst(swift::TupleInst *i) { // FIXME SILGen emits empty tuple instructions in the 'hello world' example // but doesn't use them for anything. Cheat here and ignore tuple insts. assert(i->getElements().empty() && "non-empty tuples not implemented " "(and neither are empty tuples, really)"); } void IRGenSILFunction::visitConstantRefInst(swift::ConstantRefInst *i) { // Find the entry point corresponding to the SILConstant. // FIXME: currently only does uncurried FuncDecls SILConstant constant = i->getConstant(); assert(constant.id == 0 && "constant_ref alternate entry points not yet handled"); ValueDecl *vd = constant.loc.dyn_cast<ValueDecl*>(); FuncDecl *fd = cast<FuncDecl>(vd); unsigned naturalCurryLevel = getDeclNaturalUncurryLevel(fd); FunctionRef fnRef(fd, ExplosionKind::Minimal, naturalCurryLevel); llvm::Value *fnptr = IGM.getAddrOfFunction(fnRef, ExtraData::None); AbstractCC cc = fd->isInstanceMember() ? AbstractCC::Method : AbstractCC::Freestanding; // Prepare a CallEmission for this function. // FIXME generic call specialization CanType origType = i->getType().getSwiftType(); CanType resultType = getResultType(origType, naturalCurryLevel); Callee callee = Callee::forKnownFunction( cc, origType, resultType, /*Substitutions=*/ {}, fnptr, ManagedValue(), ExplosionKind::Minimal, naturalCurryLevel); newLoweredPartialCall(Value(i, 0), naturalCurryLevel, CallEmission(*this, callee)); } void IRGenSILFunction::visitMetatypeInst(swift::MetatypeInst *i) { emitMetaTypeRef(*this, i->getType().getSwiftType(), newLoweredExplosion(Value(i, 0))); } void IRGenSILFunction::visitApplyInst(swift::ApplyInst *i) { Value v(i, 0); // FIXME: This assumes that a curried application always reaches the "natural" // curry level and that intermediate curries are never used as values. These // conditions aren't supported for many decls in IRGen anyway though. // Pile our arguments onto the CallEmission. PartialCall &parent = getLoweredPartialCall(i->getCallee()); Explosion args(ExplosionKind::Minimal); for (Value arg : i->getArguments()) { args.add(getLoweredExplosion(arg).getAll()); } parent.emission.addArg(args); if (--parent.remainingCurryLevels == 0) { // If this brought the call to its natural curry level, emit the call. parent.emission.emitToExplosion(newLoweredExplosion(v)); } else { // If not, pass the partial emission forward. moveLoweredPartialCall(v, std::move(parent)); } } void IRGenSILFunction::visitStringLiteralInst(swift::StringLiteralInst *i) { emitStringLiteral(*this, i->getValue(), /*includeSize=*/true, newLoweredExplosion(Value(i, 0))); } void IRGenSILFunction::visitExtractInst(swift::ExtractInst *i) { Value v(i, 0); Explosion &lowered = newLoweredExplosion(v); Explosion &operand = getLoweredExplosion(i->getOperand()); // FIXME: totally wrong for nontrivial cases. should get the actual range // for the extracted element ArrayRef<ManagedValue> extracted = operand.getRange(i->getFieldNo(), i->getFieldNo() + 1); lowered.add(extracted); } void IRGenSILFunction::visitReturnInst(swift::ReturnInst *i) { // FIXME: actually return a value. Builder.CreateRet(nullptr); }<commit_msg>Fix a build warning (missing newline at EOF)<commit_after>//===--- IRGenSIL.cpp - Swift Per-Function IR Generation ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements basic setup and teardown for the class which // performs IR generation for function bodies. // //===----------------------------------------------------------------------===// #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/Support/SourceMgr.h" #include "swift/Basic/SourceLoc.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "CallEmission.h" #include "Explosion.h" #include "GenFunc.h" #include "GenMeta.h" #include "GenTuple.h" #include "IRGenModule.h" #include "IRGenSIL.h" #include "Linking.h" using namespace swift; using namespace irgen; IRGenSILFunction::IRGenSILFunction(IRGenModule &IGM, CanType t, ArrayRef<Pattern*> p, llvm::Function *fn) : IRGenFunction(IGM, t, p, ExplosionKind::Minimal, 0, fn, Prologue::None) { } IRGenSILFunction::~IRGenSILFunction() { } void IRGenSILFunction::emitSILFunction(swift::Function *f) { assert(!f->empty() && "function has no basic blocks?!"); BasicBlock *entry = f->begin(); // FIXME Map the SIL arguments to LLVM arguments. size_t bbarg_size = entry->bbarg_end() - entry->bbarg_begin(); assert(bbarg_size == 0 && "arguments not yet supported"); // Emit the function body. visitBasicBlock(entry); } void IRGenSILFunction::emitGlobalTopLevel(TranslationUnit *TU, SILModule *SILMod) { // Emit the toplevel function. if (SILMod->hasTopLevelFunction()) emitSILFunction(SILMod->getTopLevelFunction()); // FIXME: should support nonzero StartElems for interactive contexts. IRGenFunction::emitGlobalTopLevel(TU, 0); } void IRGenSILFunction::visitBasicBlock(swift::BasicBlock *BB) { // Emit the LLVM basic block. // FIXME: Use the SIL basic block's name. llvm::BasicBlock *curBB = llvm::BasicBlock::Create(IGM.getLLVMContext(), "sil"); CurFn->getBasicBlockList().push_back(curBB); Builder.SetInsertPoint(curBB); // FIXME: emit a phi node to bind the bb arguments from all the predecessor // branches. // Generate the body. for (auto &I : *BB) visit(&I); assert(Builder.hasPostTerminatorIP() && "SIL bb did not terminate block?!"); } void IRGenSILFunction::visitTupleInst(swift::TupleInst *i) { // FIXME SILGen emits empty tuple instructions in the 'hello world' example // but doesn't use them for anything. Cheat here and ignore tuple insts. assert(i->getElements().empty() && "non-empty tuples not implemented " "(and neither are empty tuples, really)"); } void IRGenSILFunction::visitConstantRefInst(swift::ConstantRefInst *i) { // Find the entry point corresponding to the SILConstant. // FIXME: currently only does uncurried FuncDecls SILConstant constant = i->getConstant(); assert(constant.id == 0 && "constant_ref alternate entry points not yet handled"); ValueDecl *vd = constant.loc.dyn_cast<ValueDecl*>(); FuncDecl *fd = cast<FuncDecl>(vd); unsigned naturalCurryLevel = getDeclNaturalUncurryLevel(fd); FunctionRef fnRef(fd, ExplosionKind::Minimal, naturalCurryLevel); llvm::Value *fnptr = IGM.getAddrOfFunction(fnRef, ExtraData::None); AbstractCC cc = fd->isInstanceMember() ? AbstractCC::Method : AbstractCC::Freestanding; // Prepare a CallEmission for this function. // FIXME generic call specialization CanType origType = i->getType().getSwiftType(); CanType resultType = getResultType(origType, naturalCurryLevel); Callee callee = Callee::forKnownFunction( cc, origType, resultType, /*Substitutions=*/ {}, fnptr, ManagedValue(), ExplosionKind::Minimal, naturalCurryLevel); newLoweredPartialCall(Value(i, 0), naturalCurryLevel, CallEmission(*this, callee)); } void IRGenSILFunction::visitMetatypeInst(swift::MetatypeInst *i) { emitMetaTypeRef(*this, i->getType().getSwiftType(), newLoweredExplosion(Value(i, 0))); } void IRGenSILFunction::visitApplyInst(swift::ApplyInst *i) { Value v(i, 0); // FIXME: This assumes that a curried application always reaches the "natural" // curry level and that intermediate curries are never used as values. These // conditions aren't supported for many decls in IRGen anyway though. // Pile our arguments onto the CallEmission. PartialCall &parent = getLoweredPartialCall(i->getCallee()); Explosion args(ExplosionKind::Minimal); for (Value arg : i->getArguments()) { args.add(getLoweredExplosion(arg).getAll()); } parent.emission.addArg(args); if (--parent.remainingCurryLevels == 0) { // If this brought the call to its natural curry level, emit the call. parent.emission.emitToExplosion(newLoweredExplosion(v)); } else { // If not, pass the partial emission forward. moveLoweredPartialCall(v, std::move(parent)); } } void IRGenSILFunction::visitStringLiteralInst(swift::StringLiteralInst *i) { emitStringLiteral(*this, i->getValue(), /*includeSize=*/true, newLoweredExplosion(Value(i, 0))); } void IRGenSILFunction::visitExtractInst(swift::ExtractInst *i) { Value v(i, 0); Explosion &lowered = newLoweredExplosion(v); Explosion &operand = getLoweredExplosion(i->getOperand()); // FIXME: totally wrong for nontrivial cases. should get the actual range // for the extracted element ArrayRef<ManagedValue> extracted = operand.getRange(i->getFieldNo(), i->getFieldNo() + 1); lowered.add(extracted); } void IRGenSILFunction::visitReturnInst(swift::ReturnInst *i) { // FIXME: actually return a value. Builder.CreateRet(nullptr); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: splittbl.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2004-08-23 09:10:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #pragma hdrstop #ifndef _WRTSH_HXX //autogen #include <wrtsh.hxx> #endif #ifndef _SPLITTBL_HXX #include <splittbl.hxx> #endif #include <splittbl.hrc> #include <table.hrc> #ifndef _TBLENUM_HXX #include <tblenum.hxx> #endif /*-----------------17.03.98 10:56------------------- --------------------------------------------------*/ SwSplitTblDlg::SwSplitTblDlg( Window *pParent, SwWrtShell &rSh ) : SvxStandardDialog(pParent, SW_RES(DLG_SPLIT_TABLE)), aOKPB( this, ResId(PB_OK )), aCancelPB( this, ResId(PB_CANCEL )), aHelpPB( this, ResId(PB_HELP )), aSplitFL( this, ResId(FL_SPLIT )), aCntntCopyRB( this, ResId(RB_CNTNT )), aBoxAttrCopyWithParaRB( this, ResId(RB_BOX_PARA )), aBoxAttrCopyNoParaRB( this, ResId(RB_BOX_NOPARA)), aBorderCopyRB( this, ResId(RB_BORDER )), rShell(rSh) { FreeResource(); aCntntCopyRB.Check(); } /*-----------------17.03.98 10:56------------------- --------------------------------------------------*/ void SwSplitTblDlg::Apply() { USHORT nSplit = HEADLINE_CNTNTCOPY; if(aBoxAttrCopyWithParaRB.IsChecked()) nSplit = HEADLINE_BOXATRCOLLCOPY; if(aBoxAttrCopyNoParaRB.IsChecked()) nSplit = HEADLINE_BOXATTRCOPY; else if(aBorderCopyRB.IsChecked()) nSplit = HEADLINE_BORDERCOPY; rShell.SplitTable( nSplit ); } <commit_msg>INTEGRATION: CWS ooo19126 (1.5.596); FILE MERGED 2005/09/05 13:47:31 rt 1.5.596.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: splittbl.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 11:03:50 $ * * 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 * ************************************************************************/ #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #pragma hdrstop #ifndef _WRTSH_HXX //autogen #include <wrtsh.hxx> #endif #ifndef _SPLITTBL_HXX #include <splittbl.hxx> #endif #include <splittbl.hrc> #include <table.hrc> #ifndef _TBLENUM_HXX #include <tblenum.hxx> #endif /*-----------------17.03.98 10:56------------------- --------------------------------------------------*/ SwSplitTblDlg::SwSplitTblDlg( Window *pParent, SwWrtShell &rSh ) : SvxStandardDialog(pParent, SW_RES(DLG_SPLIT_TABLE)), aOKPB( this, ResId(PB_OK )), aCancelPB( this, ResId(PB_CANCEL )), aHelpPB( this, ResId(PB_HELP )), aSplitFL( this, ResId(FL_SPLIT )), aCntntCopyRB( this, ResId(RB_CNTNT )), aBoxAttrCopyWithParaRB( this, ResId(RB_BOX_PARA )), aBoxAttrCopyNoParaRB( this, ResId(RB_BOX_NOPARA)), aBorderCopyRB( this, ResId(RB_BORDER )), rShell(rSh) { FreeResource(); aCntntCopyRB.Check(); } /*-----------------17.03.98 10:56------------------- --------------------------------------------------*/ void SwSplitTblDlg::Apply() { USHORT nSplit = HEADLINE_CNTNTCOPY; if(aBoxAttrCopyWithParaRB.IsChecked()) nSplit = HEADLINE_BOXATRCOLLCOPY; if(aBoxAttrCopyNoParaRB.IsChecked()) nSplit = HEADLINE_BOXATTRCOPY; else if(aBorderCopyRB.IsChecked()) nSplit = HEADLINE_BORDERCOPY; rShell.SplitTable( nSplit ); } <|endoftext|>
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/gtest/gtest.h> #include <vespa/slobrok/server/local_rpc_monitor_map.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/time.h> #include <vespa/fnet/scheduler.h> #include <map> using namespace vespalib; using namespace slobrok; using vespalib::make_string_short::fmt; struct MapCall { vespalib::string name; ServiceMapping mapping; ServiceMapping old; static MapCall add(const ServiceMapping &m) { return {"add", m, {"",""}}; } static MapCall remove(const ServiceMapping &m) { return {"remove", m, {"",""}}; } static MapCall update(const ServiceMapping &o, const ServiceMapping &m) { return {"update", m, o}; } void check(const MapCall &rhs) const { EXPECT_EQ(name, rhs.name); EXPECT_EQ(mapping, rhs.mapping); EXPECT_EQ(old, rhs.old); } ~MapCall(); }; MapCall::~MapCall() = default; struct MonitorCall { vespalib::string name; ServiceMapping mapping; bool hurry; static MonitorCall start(const ServiceMapping &m, bool h) { return {"start", m, h}; } static MonitorCall stop(const ServiceMapping &m) { return {"stop", m, false}; } void check(const MonitorCall &rhs) const { EXPECT_EQ(name, rhs.name); EXPECT_EQ(mapping, rhs.mapping); EXPECT_EQ(hurry, rhs.hurry); } ~MonitorCall(); }; MonitorCall::~MonitorCall() = default; template <typename Call> class CallLog { private: std::vector<Call> _calls; size_t _checked; public: CallLog() noexcept : _calls(), _checked(0) {} ~CallLog() { EXPECT_EQ(_calls.size(), _checked); } void log(Call call) { _calls.push_back(call); } void expect(std::initializer_list<Call> list) { ASSERT_EQ(list.size(), (_calls.size() - _checked)); for (const auto &call: list) { call.check(_calls[_checked++]); } } }; struct MapLog : CallLog<MapCall>, MapListener { void add(const ServiceMapping &mapping) override { log(MapCall::add(mapping)); } void remove(const ServiceMapping &mapping) override { log(MapCall::remove(mapping)); } void update(const ServiceMapping &old_mapping, const ServiceMapping &new_mapping) override { log(MapCall::update(old_mapping, new_mapping)); } }; struct MonitorLog : CallLog<MonitorCall>, MappingMonitor { void start(const ServiceMapping& mapping, bool hurry) override { log(MonitorCall::start(mapping, hurry)); } void stop(const ServiceMapping& mapping) override { log(MonitorCall::stop(mapping)); } }; struct MyMappingMonitor : MappingMonitor { MonitorLog &monitor; MyMappingMonitor(MonitorLog &m) : monitor(m) {} void start(const ServiceMapping& mapping, bool hurry) override { monitor.start(mapping, hurry); } void stop(const ServiceMapping& mapping) override { monitor.stop(mapping); } }; struct LocalRpcMonitorMapTest : public ::testing::Test { steady_time time; FNET_Scheduler scheduler; MonitorLog monitor_log; MapLog map_log; LocalRpcMonitorMap map; std::unique_ptr<MapSubscription> subscription; ServiceMapping mapping; ServiceMapping mapping_conflict; LocalRpcMonitorMapTest() : time(duration::zero()), scheduler(&time, &time), monitor_log(), map_log(), map(&scheduler, [this](auto &owner) { EXPECT_EQ(&owner, &map); return std::make_unique<MyMappingMonitor>(monitor_log); }), subscription(MapSubscription::subscribe(map.dispatcher(), map_log)), mapping("dummy_service", "dummy_spec"), mapping_conflict("dummy_service", "conflicting_dummy_spec") {} void tick(duration elapsed = FNET_Scheduler::tick_ms) { time += elapsed; scheduler.CheckTasks(); } void add_mapping(const ServiceMapping &m, bool is_up) { map.add(m); // <- add from consensus map monitor_log.expect({}); tick(0ms); // <- process delayed add event monitor_log.expect({MonitorCall::start(m, false)}); map_log.expect({}); if (is_up) { map.up(m); // <- up from monitor map_log.expect({MapCall::add(m)}); } else { map.down(m); // <- down from monitor map_log.expect({}); } } void flip_up_state(const ServiceMapping &m, bool was_up, size_t cnt) { for (size_t i = 0; i < cnt; ++i) { if (was_up) { map.up(m); map_log.expect({}); map.down(m); map_log.expect({MapCall::remove(m)}); } else { map.down(m); map_log.expect({}); map.up(m); map_log.expect({MapCall::add(m)}); } was_up = !was_up; } monitor_log.expect({}); } void remove_mapping(const ServiceMapping &m, bool was_up) { map.remove(m); // <- remove from consensus map monitor_log.expect({}); tick(0ms); // <- process delayed remove event monitor_log.expect({MonitorCall::stop(m)}); if (was_up) { map_log.expect({MapCall::remove(m)}); } else { map_log.expect({}); } } ~LocalRpcMonitorMapTest(); }; LocalRpcMonitorMapTest::~LocalRpcMonitorMapTest() = default; struct MyAddLocalHandler : LocalRpcMonitorMap::AddLocalCompletionHandler { std::unique_ptr<OkState> &state; bool &handler_deleted; MyAddLocalHandler(std::unique_ptr<OkState> &s, bool &hd) : state(s), handler_deleted(hd) {} void doneHandler(OkState result) override { state = std::make_unique<OkState>(result); } ~MyAddLocalHandler() override { handler_deleted = true; } }; TEST_F(LocalRpcMonitorMapTest, external_add_remove_while_up) { add_mapping(mapping, true); remove_mapping(mapping, true); } TEST_F(LocalRpcMonitorMapTest, external_add_remove_while_down) { add_mapping(mapping, false); remove_mapping(mapping, false); } TEST_F(LocalRpcMonitorMapTest, server_up_down_up_down) { add_mapping(mapping, true); flip_up_state(mapping, true, 3); remove_mapping(mapping, false); } TEST_F(LocalRpcMonitorMapTest, server_down_up_down_up) { add_mapping(mapping, false); flip_up_state(mapping, false, 3); remove_mapping(mapping, true); } TEST_F(LocalRpcMonitorMapTest, multi_mapping) { ServiceMapping m1("dummy_service1", "dummy_spec1"); ServiceMapping m2("dummy_service2", "dummy_spec2"); ServiceMapping m3("dummy_service3", "dummy_spec3"); add_mapping(m1, true); add_mapping(m2, false); add_mapping(m3, true); flip_up_state(m1, true, 3); flip_up_state(m2, false, 3); flip_up_state(m3, true, 3); remove_mapping(m1, false); remove_mapping(m2, true); remove_mapping(m3, false); } TEST_F(LocalRpcMonitorMapTest, local_add_ok) { std::unique_ptr<OkState> state; bool handler_deleted; map.addLocal(mapping, std::make_unique<MyAddLocalHandler>(state, handler_deleted)); monitor_log.expect({MonitorCall::start(mapping, true)}); map_log.expect({}); map.up(mapping); monitor_log.expect({}); map_log.expect({MapCall::add(mapping)}); ASSERT_TRUE(state); EXPECT_TRUE(state->ok()); ASSERT_TRUE(handler_deleted); } TEST_F(LocalRpcMonitorMapTest, local_add_already_up) { std::unique_ptr<OkState> state; bool handler_deleted; add_mapping(mapping, true); map.addLocal(mapping, std::make_unique<MyAddLocalHandler>(state, handler_deleted)); monitor_log.expect({}); map_log.expect({}); ASSERT_TRUE(state); EXPECT_TRUE(state->ok()); ASSERT_TRUE(handler_deleted); } TEST_F(LocalRpcMonitorMapTest, local_add_unknown_comes_up) { std::unique_ptr<OkState> state; bool handler_deleted; add_mapping(mapping, false); map.addLocal(mapping, std::make_unique<MyAddLocalHandler>(state, handler_deleted)); monitor_log.expect({MonitorCall::stop(mapping), MonitorCall::start(mapping, true)}); map_log.expect({}); ASSERT_FALSE(state); map.up(mapping); ASSERT_TRUE(state); EXPECT_TRUE(state->ok()); ASSERT_TRUE(handler_deleted); map_log.expect({MapCall::add(mapping)}); } TEST_F(LocalRpcMonitorMapTest, local_add_unknown_goes_down) { std::unique_ptr<OkState> state; bool handler_deleted; add_mapping(mapping, false); map.addLocal(mapping, std::make_unique<MyAddLocalHandler>(state, handler_deleted)); monitor_log.expect({MonitorCall::stop(mapping), MonitorCall::start(mapping, true)}); map_log.expect({}); ASSERT_FALSE(state); map.down(mapping); ASSERT_TRUE(state); EXPECT_FALSE(state->ok()); ASSERT_TRUE(handler_deleted); } TEST_F(LocalRpcMonitorMapTest, local_add_conflict) { std::unique_ptr<OkState> state; bool handler_deleted; add_mapping(mapping, true); map.addLocal(mapping_conflict, std::make_unique<MyAddLocalHandler>(state, handler_deleted)); monitor_log.expect({}); map_log.expect({}); ASSERT_TRUE(state); EXPECT_TRUE(state->failed()); ASSERT_TRUE(handler_deleted); } GTEST_MAIN_RUN_ALL_TESTS() <commit_msg>extend test<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/gtest/gtest.h> #include <vespa/slobrok/server/local_rpc_monitor_map.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/time.h> #include <vespa/fnet/scheduler.h> #include <map> using namespace vespalib; using namespace slobrok; using vespalib::make_string_short::fmt; struct MapCall { vespalib::string name; ServiceMapping mapping; ServiceMapping old; static MapCall add(const ServiceMapping &m) { return {"add", m, {"",""}}; } static MapCall remove(const ServiceMapping &m) { return {"remove", m, {"",""}}; } static MapCall update(const ServiceMapping &o, const ServiceMapping &m) { return {"update", m, o}; } void check(const MapCall &rhs) const { EXPECT_EQ(name, rhs.name); EXPECT_EQ(mapping, rhs.mapping); EXPECT_EQ(old, rhs.old); } ~MapCall(); }; MapCall::~MapCall() = default; struct MonitorCall { vespalib::string name; ServiceMapping mapping; bool hurry; static MonitorCall start(const ServiceMapping &m, bool h) { return {"start", m, h}; } static MonitorCall stop(const ServiceMapping &m) { return {"stop", m, false}; } void check(const MonitorCall &rhs) const { EXPECT_EQ(name, rhs.name); EXPECT_EQ(mapping, rhs.mapping); EXPECT_EQ(hurry, rhs.hurry); } ~MonitorCall(); }; MonitorCall::~MonitorCall() = default; template <typename Call> class CallLog { private: std::vector<Call> _calls; size_t _checked; public: CallLog() noexcept : _calls(), _checked(0) {} ~CallLog() { EXPECT_EQ(_calls.size(), _checked); } void log(Call call) { _calls.push_back(call); } void expect(std::initializer_list<Call> list) { ASSERT_EQ(list.size(), (_calls.size() - _checked)); for (const auto &call: list) { call.check(_calls[_checked++]); } } }; struct MapLog : CallLog<MapCall>, MapListener { void add(const ServiceMapping &mapping) override { log(MapCall::add(mapping)); } void remove(const ServiceMapping &mapping) override { log(MapCall::remove(mapping)); } void update(const ServiceMapping &old_mapping, const ServiceMapping &new_mapping) override { log(MapCall::update(old_mapping, new_mapping)); } }; struct MonitorLog : CallLog<MonitorCall>, MappingMonitor { void start(const ServiceMapping& mapping, bool hurry) override { log(MonitorCall::start(mapping, hurry)); } void stop(const ServiceMapping& mapping) override { log(MonitorCall::stop(mapping)); } }; struct MyMappingMonitor : MappingMonitor { MonitorLog &monitor; MyMappingMonitor(MonitorLog &m) : monitor(m) {} void start(const ServiceMapping& mapping, bool hurry) override { monitor.start(mapping, hurry); } void stop(const ServiceMapping& mapping) override { monitor.stop(mapping); } }; struct LocalRpcMonitorMapTest : public ::testing::Test { steady_time time; FNET_Scheduler scheduler; MonitorLog monitor_log; MapLog map_log; LocalRpcMonitorMap map; std::unique_ptr<MapSubscription> subscription; ServiceMapping mapping; ServiceMapping mapping_conflict; LocalRpcMonitorMapTest() : time(duration::zero()), scheduler(&time, &time), monitor_log(), map_log(), map(&scheduler, [this](auto &owner) { EXPECT_EQ(&owner, &map); return std::make_unique<MyMappingMonitor>(monitor_log); }), subscription(MapSubscription::subscribe(map.dispatcher(), map_log)), mapping("dummy_service", "dummy_spec"), mapping_conflict("dummy_service", "conflicting_dummy_spec") {} void tick(duration elapsed = FNET_Scheduler::tick_ms) { time += elapsed; scheduler.CheckTasks(); } void add_mapping(const ServiceMapping &m, bool is_up) { map.add(m); // <- add from consensus map monitor_log.expect({}); tick(0ms); // <- process delayed add event monitor_log.expect({MonitorCall::start(m, false)}); map_log.expect({}); if (is_up) { map.up(m); // <- up from monitor map_log.expect({MapCall::add(m)}); } else { map.down(m); // <- down from monitor map_log.expect({}); } } void flip_up_state(const ServiceMapping &m, bool was_up, size_t cnt) { for (size_t i = 0; i < cnt; ++i) { if (was_up) { map.up(m); map_log.expect({}); map.down(m); map_log.expect({MapCall::remove(m)}); } else { map.down(m); map_log.expect({}); map.up(m); map_log.expect({MapCall::add(m)}); } was_up = !was_up; } monitor_log.expect({}); } void remove_mapping(const ServiceMapping &m, bool was_up) { map.remove(m); // <- remove from consensus map monitor_log.expect({}); tick(0ms); // <- process delayed remove event monitor_log.expect({MonitorCall::stop(m)}); if (was_up) { map_log.expect({MapCall::remove(m)}); } else { map_log.expect({}); } } ~LocalRpcMonitorMapTest(); }; LocalRpcMonitorMapTest::~LocalRpcMonitorMapTest() = default; struct MyAddLocalHandler : LocalRpcMonitorMap::AddLocalCompletionHandler { std::unique_ptr<OkState> &state; bool &handler_deleted; MyAddLocalHandler(std::unique_ptr<OkState> &s, bool &hd) : state(s), handler_deleted(hd) {} void doneHandler(OkState result) override { state = std::make_unique<OkState>(result); } ~MyAddLocalHandler() override { handler_deleted = true; } }; TEST_F(LocalRpcMonitorMapTest, external_add_remove_while_up) { add_mapping(mapping, true); remove_mapping(mapping, true); } TEST_F(LocalRpcMonitorMapTest, external_add_remove_while_down) { add_mapping(mapping, false); remove_mapping(mapping, false); } TEST_F(LocalRpcMonitorMapTest, server_up_down_up_down) { add_mapping(mapping, true); flip_up_state(mapping, true, 3); remove_mapping(mapping, false); } TEST_F(LocalRpcMonitorMapTest, server_down_up_down_up) { add_mapping(mapping, false); flip_up_state(mapping, false, 3); remove_mapping(mapping, true); } TEST_F(LocalRpcMonitorMapTest, multi_mapping) { ServiceMapping m1("dummy_service1", "dummy_spec1"); ServiceMapping m2("dummy_service2", "dummy_spec2"); ServiceMapping m3("dummy_service3", "dummy_spec3"); add_mapping(m1, true); add_mapping(m2, false); add_mapping(m3, true); flip_up_state(m1, true, 3); flip_up_state(m2, false, 3); flip_up_state(m3, true, 3); remove_mapping(m1, false); remove_mapping(m2, true); remove_mapping(m3, false); } TEST_F(LocalRpcMonitorMapTest, local_add_ok) { std::unique_ptr<OkState> state; bool handler_deleted; map.addLocal(mapping, std::make_unique<MyAddLocalHandler>(state, handler_deleted)); monitor_log.expect({MonitorCall::start(mapping, true)}); map_log.expect({}); map.up(mapping); monitor_log.expect({}); map_log.expect({MapCall::add(mapping)}); ASSERT_TRUE(state); EXPECT_TRUE(state->ok()); ASSERT_TRUE(handler_deleted); } TEST_F(LocalRpcMonitorMapTest, local_add_already_up) { std::unique_ptr<OkState> state; bool handler_deleted; add_mapping(mapping, true); map.addLocal(mapping, std::make_unique<MyAddLocalHandler>(state, handler_deleted)); monitor_log.expect({}); map_log.expect({}); ASSERT_TRUE(state); EXPECT_TRUE(state->ok()); ASSERT_TRUE(handler_deleted); } TEST_F(LocalRpcMonitorMapTest, local_add_unknown_comes_up) { std::unique_ptr<OkState> state; bool handler_deleted; add_mapping(mapping, false); map.addLocal(mapping, std::make_unique<MyAddLocalHandler>(state, handler_deleted)); monitor_log.expect({MonitorCall::stop(mapping), MonitorCall::start(mapping, true)}); map_log.expect({}); EXPECT_FALSE(state); map.up(mapping); map_log.expect({MapCall::add(mapping)}); ASSERT_TRUE(state); EXPECT_TRUE(state->ok()); ASSERT_TRUE(handler_deleted); } TEST_F(LocalRpcMonitorMapTest, local_add_unknown_goes_down) { std::unique_ptr<OkState> state; bool handler_deleted; add_mapping(mapping, false); map.addLocal(mapping, std::make_unique<MyAddLocalHandler>(state, handler_deleted)); monitor_log.expect({MonitorCall::stop(mapping), MonitorCall::start(mapping, true)}); map_log.expect({}); EXPECT_FALSE(state); map.down(mapping); map_log.expect({}); ASSERT_TRUE(state); EXPECT_FALSE(state->ok()); ASSERT_TRUE(handler_deleted); } TEST_F(LocalRpcMonitorMapTest, local_add_conflict) { std::unique_ptr<OkState> state; bool handler_deleted; add_mapping(mapping, true); map.addLocal(mapping_conflict, std::make_unique<MyAddLocalHandler>(state, handler_deleted)); monitor_log.expect({}); map_log.expect({}); ASSERT_TRUE(state); EXPECT_TRUE(state->failed()); ASSERT_TRUE(handler_deleted); } TEST_F(LocalRpcMonitorMapTest, local_multi_add) { std::unique_ptr<OkState> state1; bool handler_deleted1; std::unique_ptr<OkState> state2; bool handler_deleted2; map.addLocal(mapping, std::make_unique<MyAddLocalHandler>(state1, handler_deleted1)); monitor_log.expect({MonitorCall::start(mapping, true)}); map.addLocal(mapping, std::make_unique<MyAddLocalHandler>(state2, handler_deleted2)); monitor_log.expect({}); map_log.expect({}); EXPECT_FALSE(state1); EXPECT_FALSE(state2); map.up(mapping); monitor_log.expect({}); map_log.expect({MapCall::add(mapping)}); ASSERT_TRUE(state1); ASSERT_TRUE(state2); EXPECT_TRUE(state1->ok()); EXPECT_TRUE(state2->ok()); ASSERT_TRUE(handler_deleted1); ASSERT_TRUE(handler_deleted2); } TEST_F(LocalRpcMonitorMapTest, local_remove) { add_mapping(mapping, true); map.removeLocal(mapping); monitor_log.expect({MonitorCall::stop(mapping), MonitorCall::start(mapping, false)}); map_log.expect({MapCall::remove(mapping)}); map.up(mapping); // timeout case (should normally not happen) map_log.expect({MapCall::add(mapping)}); } TEST_F(LocalRpcMonitorMapTest, local_add_local_remove) { std::unique_ptr<OkState> state; bool handler_deleted; map.addLocal(mapping, std::make_unique<MyAddLocalHandler>(state, handler_deleted)); monitor_log.expect({MonitorCall::start(mapping, true)}); map_log.expect({}); map.removeLocal(mapping); monitor_log.expect({MonitorCall::stop(mapping)}); map_log.expect({}); ASSERT_TRUE(state); EXPECT_TRUE(state->failed()); ASSERT_TRUE(handler_deleted); } GTEST_MAIN_RUN_ALL_TESTS() <|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 "chrome/common/plugin_group.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "base/version.h" #include "webkit/glue/plugins/plugin_list.h" #if defined(OS_MACOSX) // Plugin Groups for Mac. // Plugins are listed here as soon as vulnerabilities and solutions // (new versions) are published. // TODO(panayiotis): Get the Real Player version on Mac, somehow. static const PluginGroupDefinition kGroupDefinitions[] = { { "Quicktime", "QuickTime Plug-in", "", "", "7.6.6", "http://www.apple.com/quicktime/download/" }, { "Java", "Java", "", "", "", "http://support.apple.com/kb/HT1338" }, { "Flash", "Shockwave Flash", "", "", "10.1.82", "http://get.adobe.com/flashplayer/" }, { "Silverlight 3", "Silverlight", "0", "4", "3.0.50106.0", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Silverlight 4", "Silverlight", "4", "5", "", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Flip4Mac", "Flip4Mac", "", "", "2.2.1", "http://www.telestream.net/flip4mac-wmv/overview.htm" }, { "Shockwave", "Shockwave for Director", "", "", "11.5.7.609", "http://www.adobe.com/shockwave/download/" } }; #elif defined(OS_WIN) // TODO(panayiotis): We should group "RealJukebox NS Plugin" with the rest of // the RealPlayer files. static const PluginGroupDefinition kGroupDefinitions[] = { { "Quicktime", "QuickTime Plug-in", "", "", "7.6.6", "http://www.apple.com/quicktime/download/" }, { "Java 6", "Java", "", "6", "6.0.200", "http://www.java.com/" }, { "Adobe Reader 9", "Adobe Acrobat", "9", "10", "9.3.3", "http://get.adobe.com/reader/" }, { "Adobe Reader 8", "Adobe Acrobat", "0", "9", "8.2.3", "http://get.adobe.com/reader/" }, { "Flash", "Shockwave Flash", "", "", "10.1.82", "http://get.adobe.com/flashplayer/" }, { "Silverlight 3", "Silverlight", "0", "4", "3.0.50106.0", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Silverlight 4", "Silverlight", "4", "5", "", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Shockwave", "Shockwave for Director", "", "", "11.5.7.609", "http://www.adobe.com/shockwave/download/" }, { "DivX Player", "DivX Web Player", "", "", "1.4.3.4", "http://download.divx.com/divx/autoupdate/player/DivXWebPlayerInstaller.exe" }, // These are here for grouping, no vulnerabilies known. { "Windows Media Player", "Windows Media Player", "", "", "", "" }, { "Microsoft Office", "Microsoft Office", "", "", "", "" }, // TODO(panayiotis): The vulnerable versions are // (v >= 6.0.12.1040 && v <= 6.0.12.1663) // || v == 6.0.12.1698 || v == 6.0.12.1741 { "RealPlayer", "RealPlayer", "", "", "", "http://www.adobe.com/shockwave/download/" }, }; #else static const PluginGroupDefinition kGroupDefinitions[] = {}; #endif /*static*/ std::set<string16>* PluginGroup::policy_disabled_puglins_; /*static*/ const PluginGroupDefinition* PluginGroup::GetPluginGroupDefinitions() { return kGroupDefinitions; } /*static*/ size_t PluginGroup::GetPluginGroupDefinitionsSize() { // TODO(viettrungluu): |arraysize()| doesn't work with zero-size arrays. return ARRAYSIZE_UNSAFE(kGroupDefinitions); } /*static*/ void PluginGroup::SetPolicyDisabledPluginSet(const std::set<string16>& set) { if (!policy_disabled_puglins_) { policy_disabled_puglins_ = new std::set<string16>(); *policy_disabled_puglins_ = set; } } /*static*/ bool PluginGroup::IsPluginNameDisabledByPolicy(const string16& plugin_name) { return policy_disabled_puglins_ && policy_disabled_puglins_->find(plugin_name) != policy_disabled_puglins_->end(); } /*static*/ bool PluginGroup::IsPluginPathDisabledByPolicy(const FilePath& plugin_path) { std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { if (FilePath::CompareEqualIgnoreCase(it->path.value(), plugin_path.value()) && IsPluginNameDisabledByPolicy(it->name)) { return true; } } return false; } PluginGroup::PluginGroup(const string16& group_name, const string16& name_matcher, const std::string& version_range_low, const std::string& version_range_high, const std::string& min_version, const std::string& update_url) { group_name_ = group_name; name_matcher_ = name_matcher; version_range_low_str_ = version_range_low; if (!version_range_low.empty()) { version_range_low_.reset( Version::GetVersionFromString(version_range_low)); } version_range_high_str_ = version_range_high; if (!version_range_high.empty()) { version_range_high_.reset( Version::GetVersionFromString(version_range_high)); } min_version_str_ = min_version; if (!min_version.empty()) { min_version_.reset(Version::GetVersionFromString(min_version)); } update_url_ = update_url; enabled_ = false; version_.reset(Version::GetVersionFromString("0")); } PluginGroup* PluginGroup::FromPluginGroupDefinition( const PluginGroupDefinition& definition) { return new PluginGroup(ASCIIToUTF16(definition.name), ASCIIToUTF16(definition.name_matcher), definition.version_matcher_low, definition.version_matcher_high, definition.min_version, definition.update_url); } PluginGroup::~PluginGroup() { } PluginGroup* PluginGroup::FromWebPluginInfo(const WebPluginInfo& wpi) { // Create a matcher from the name of this plugin. return new PluginGroup(wpi.name, wpi.name, "", "", "", ""); } PluginGroup* PluginGroup::FindHardcodedPluginGroup(const WebPluginInfo& info) { static std::vector<linked_ptr<PluginGroup> >* hardcoded_plugin_groups = NULL; if (!hardcoded_plugin_groups) { std::vector<linked_ptr<PluginGroup> >* groups = new std::vector<linked_ptr<PluginGroup> >(); const PluginGroupDefinition* definitions = GetPluginGroupDefinitions(); for (size_t i = 0; i < GetPluginGroupDefinitionsSize(); ++i) { PluginGroup* definition_group = PluginGroup::FromPluginGroupDefinition( definitions[i]); groups->push_back(linked_ptr<PluginGroup>(definition_group)); } hardcoded_plugin_groups = groups; } // See if this plugin matches any of the hardcoded groups. PluginGroup* hardcoded_group = FindGroupMatchingPlugin( *hardcoded_plugin_groups, info); if (hardcoded_group) { // Make a copy. return hardcoded_group->Copy(); } else { // Not found in our hardcoded list, create a new one. return PluginGroup::FromWebPluginInfo(info); } } PluginGroup* PluginGroup::FindGroupMatchingPlugin( std::vector<linked_ptr<PluginGroup> >& plugin_groups, const WebPluginInfo& plugin) { for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { if ((*it)->Match(plugin)) { return it->get(); } } return NULL; } bool PluginGroup::Match(const WebPluginInfo& plugin) const { if (name_matcher_.empty()) { return false; } // Look for the name matcher anywhere in the plugin name. if (plugin.name.find(name_matcher_) == string16::npos) { return false; } if (version_range_low_.get() == NULL || version_range_high_.get() == NULL) { return true; } // There's a version range, we must be in it. scoped_ptr<Version> plugin_version( Version::GetVersionFromString(UTF16ToWide(plugin.version))); if (plugin_version.get() == NULL) { // No version could be extracted, assume we don't match the range. return false; } // We match if we are in the range: [low, high) return (version_range_low_->CompareTo(*plugin_version) <= 0 && version_range_high_->CompareTo(*plugin_version) > 0); } void PluginGroup::UpdateDescriptionAndVersion(const WebPluginInfo& plugin) { description_ = plugin.desc; // Update |version_|. Remove spaces and ')' from the version string, // Replace any instances of 'r', ',' or '(' with a dot. std::wstring version = UTF16ToWide(plugin.version); RemoveChars(version, L") ", &version); std::replace(version.begin(), version.end(), 'r', '.'); std::replace(version.begin(), version.end(), ',', '.'); std::replace(version.begin(), version.end(), '(', '.'); if (Version* new_version = Version::GetVersionFromString(version)) version_.reset(new_version); else version_.reset(Version::GetVersionFromString("0")); } void PluginGroup::AddPlugin(const WebPluginInfo& plugin, int position) { web_plugin_infos_.push_back(plugin); // The position of this plugin relative to the global list of plugins. web_plugin_positions_.push_back(position); // A group is enabled if any of the files are enabled. if (plugin.enabled) { if (!enabled_) { // If this is the first enabled plugin, use its description. enabled_ = true; UpdateDescriptionAndVersion(plugin); } } else { // If this is the first plugin and it's disabled, // use its description for now. if (description_.empty()) UpdateDescriptionAndVersion(plugin); } } DictionaryValue* PluginGroup::GetSummary() const { DictionaryValue* result = new DictionaryValue(); result->SetString("name", group_name_); result->SetBoolean("enabled", enabled_); return result; } DictionaryValue* PluginGroup::GetDataForUI() const { DictionaryValue* result = new DictionaryValue(); result->SetString("name", group_name_); result->SetString("description", description_); result->SetString("version", version_->GetString()); result->SetString("update_url", update_url_); result->SetBoolean("critical", IsVulnerable()); bool group_disabled_by_policy = IsPluginNameDisabledByPolicy(group_name_); if (group_disabled_by_policy) { result->SetString("enabledMode", "disabledByPolicy"); } else { result->SetString("enabledMode", enabled_ ? "enabled" : "disabledByUser"); } ListValue* plugin_files = new ListValue(); for (size_t i = 0; i < web_plugin_infos_.size(); ++i) { const WebPluginInfo& web_plugin = web_plugin_infos_[i]; int priority = web_plugin_positions_[i]; DictionaryValue* plugin_file = new DictionaryValue(); plugin_file->SetString("name", web_plugin.name); plugin_file->SetString("description", web_plugin.desc); plugin_file->SetString("path", web_plugin.path.value()); plugin_file->SetString("version", web_plugin.version); bool plugin_disabled_by_policy = group_disabled_by_policy || IsPluginNameDisabledByPolicy(web_plugin.name); if (plugin_disabled_by_policy) { plugin_file->SetString("enabledMode", "disabledByPolicy"); } else { plugin_file->SetString("enabledMode", web_plugin.enabled ? "enabled" : "disabledByUser"); } plugin_file->SetInteger("priority", priority); ListValue* mime_types = new ListValue(); for (std::vector<WebPluginMimeType>::const_iterator type_it = web_plugin.mime_types.begin(); type_it != web_plugin.mime_types.end(); ++type_it) { DictionaryValue* mime_type = new DictionaryValue(); mime_type->SetString("mimeType", type_it->mime_type); mime_type->SetString("description", type_it->description); ListValue* file_extensions = new ListValue(); for (std::vector<std::string>::const_iterator ext_it = type_it->file_extensions.begin(); ext_it != type_it->file_extensions.end(); ++ext_it) { file_extensions->Append(new StringValue(*ext_it)); } mime_type->Set("fileExtensions", file_extensions); mime_types->Append(mime_type); } plugin_file->Set("mimeTypes", mime_types); plugin_files->Append(plugin_file); } result->Set("plugin_files", plugin_files); return result; } // Returns true if the latest version of this plugin group is vulnerable. bool PluginGroup::IsVulnerable() const { if (min_version_.get() == NULL || version_->GetString() == "0") { return false; } return version_->CompareTo(*min_version_) < 0; } void PluginGroup::Enable(bool enable) { for (std::vector<WebPluginInfo>::const_iterator it = web_plugin_infos_.begin(); it != web_plugin_infos_.end(); ++it) { if (enable && !IsPluginNameDisabledByPolicy(it->name)) { NPAPI::PluginList::Singleton()->EnablePlugin(FilePath(it->path)); } else { NPAPI::PluginList::Singleton()->DisablePlugin(FilePath(it->path)); } } } <commit_msg>Update latest secure version of Quicktime for Windows. See http://support.apple.com/kb/HT4290 BUG=None TEST=unit_tests<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 "chrome/common/plugin_group.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "base/version.h" #include "webkit/glue/plugins/plugin_list.h" #if defined(OS_MACOSX) // Plugin Groups for Mac. // Plugins are listed here as soon as vulnerabilities and solutions // (new versions) are published. // TODO(panayiotis): Get the Real Player version on Mac, somehow. static const PluginGroupDefinition kGroupDefinitions[] = { { "Quicktime", "QuickTime Plug-in", "", "", "7.6.6", "http://www.apple.com/quicktime/download/" }, { "Java", "Java", "", "", "", "http://support.apple.com/kb/HT1338" }, { "Flash", "Shockwave Flash", "", "", "10.1.82", "http://get.adobe.com/flashplayer/" }, { "Silverlight 3", "Silverlight", "0", "4", "3.0.50106.0", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Silverlight 4", "Silverlight", "4", "5", "", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Flip4Mac", "Flip4Mac", "", "", "2.2.1", "http://www.telestream.net/flip4mac-wmv/overview.htm" }, { "Shockwave", "Shockwave for Director", "", "", "11.5.7.609", "http://www.adobe.com/shockwave/download/" } }; #elif defined(OS_WIN) // TODO(panayiotis): We should group "RealJukebox NS Plugin" with the rest of // the RealPlayer files. static const PluginGroupDefinition kGroupDefinitions[] = { { "Quicktime", "QuickTime Plug-in", "", "", "7.6.7", "http://www.apple.com/quicktime/download/" }, { "Java 6", "Java", "", "6", "6.0.200", "http://www.java.com/" }, { "Adobe Reader 9", "Adobe Acrobat", "9", "10", "9.3.3", "http://get.adobe.com/reader/" }, { "Adobe Reader 8", "Adobe Acrobat", "0", "9", "8.2.3", "http://get.adobe.com/reader/" }, { "Flash", "Shockwave Flash", "", "", "10.1.82", "http://get.adobe.com/flashplayer/" }, { "Silverlight 3", "Silverlight", "0", "4", "3.0.50106.0", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Silverlight 4", "Silverlight", "4", "5", "", "http://go.microsoft.com/fwlink/?LinkID=185927" }, { "Shockwave", "Shockwave for Director", "", "", "11.5.7.609", "http://www.adobe.com/shockwave/download/" }, { "DivX Player", "DivX Web Player", "", "", "1.4.3.4", "http://download.divx.com/divx/autoupdate/player/DivXWebPlayerInstaller.exe" }, // These are here for grouping, no vulnerabilies known. { "Windows Media Player", "Windows Media Player", "", "", "", "" }, { "Microsoft Office", "Microsoft Office", "", "", "", "" }, // TODO(panayiotis): The vulnerable versions are // (v >= 6.0.12.1040 && v <= 6.0.12.1663) // || v == 6.0.12.1698 || v == 6.0.12.1741 { "RealPlayer", "RealPlayer", "", "", "", "http://www.adobe.com/shockwave/download/" }, }; #else static const PluginGroupDefinition kGroupDefinitions[] = {}; #endif /*static*/ std::set<string16>* PluginGroup::policy_disabled_puglins_; /*static*/ const PluginGroupDefinition* PluginGroup::GetPluginGroupDefinitions() { return kGroupDefinitions; } /*static*/ size_t PluginGroup::GetPluginGroupDefinitionsSize() { // TODO(viettrungluu): |arraysize()| doesn't work with zero-size arrays. return ARRAYSIZE_UNSAFE(kGroupDefinitions); } /*static*/ void PluginGroup::SetPolicyDisabledPluginSet(const std::set<string16>& set) { if (!policy_disabled_puglins_) { policy_disabled_puglins_ = new std::set<string16>(); *policy_disabled_puglins_ = set; } } /*static*/ bool PluginGroup::IsPluginNameDisabledByPolicy(const string16& plugin_name) { return policy_disabled_puglins_ && policy_disabled_puglins_->find(plugin_name) != policy_disabled_puglins_->end(); } /*static*/ bool PluginGroup::IsPluginPathDisabledByPolicy(const FilePath& plugin_path) { std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { if (FilePath::CompareEqualIgnoreCase(it->path.value(), plugin_path.value()) && IsPluginNameDisabledByPolicy(it->name)) { return true; } } return false; } PluginGroup::PluginGroup(const string16& group_name, const string16& name_matcher, const std::string& version_range_low, const std::string& version_range_high, const std::string& min_version, const std::string& update_url) { group_name_ = group_name; name_matcher_ = name_matcher; version_range_low_str_ = version_range_low; if (!version_range_low.empty()) { version_range_low_.reset( Version::GetVersionFromString(version_range_low)); } version_range_high_str_ = version_range_high; if (!version_range_high.empty()) { version_range_high_.reset( Version::GetVersionFromString(version_range_high)); } min_version_str_ = min_version; if (!min_version.empty()) { min_version_.reset(Version::GetVersionFromString(min_version)); } update_url_ = update_url; enabled_ = false; version_.reset(Version::GetVersionFromString("0")); } PluginGroup* PluginGroup::FromPluginGroupDefinition( const PluginGroupDefinition& definition) { return new PluginGroup(ASCIIToUTF16(definition.name), ASCIIToUTF16(definition.name_matcher), definition.version_matcher_low, definition.version_matcher_high, definition.min_version, definition.update_url); } PluginGroup::~PluginGroup() { } PluginGroup* PluginGroup::FromWebPluginInfo(const WebPluginInfo& wpi) { // Create a matcher from the name of this plugin. return new PluginGroup(wpi.name, wpi.name, "", "", "", ""); } PluginGroup* PluginGroup::FindHardcodedPluginGroup(const WebPluginInfo& info) { static std::vector<linked_ptr<PluginGroup> >* hardcoded_plugin_groups = NULL; if (!hardcoded_plugin_groups) { std::vector<linked_ptr<PluginGroup> >* groups = new std::vector<linked_ptr<PluginGroup> >(); const PluginGroupDefinition* definitions = GetPluginGroupDefinitions(); for (size_t i = 0; i < GetPluginGroupDefinitionsSize(); ++i) { PluginGroup* definition_group = PluginGroup::FromPluginGroupDefinition( definitions[i]); groups->push_back(linked_ptr<PluginGroup>(definition_group)); } hardcoded_plugin_groups = groups; } // See if this plugin matches any of the hardcoded groups. PluginGroup* hardcoded_group = FindGroupMatchingPlugin( *hardcoded_plugin_groups, info); if (hardcoded_group) { // Make a copy. return hardcoded_group->Copy(); } else { // Not found in our hardcoded list, create a new one. return PluginGroup::FromWebPluginInfo(info); } } PluginGroup* PluginGroup::FindGroupMatchingPlugin( std::vector<linked_ptr<PluginGroup> >& plugin_groups, const WebPluginInfo& plugin) { for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { if ((*it)->Match(plugin)) { return it->get(); } } return NULL; } bool PluginGroup::Match(const WebPluginInfo& plugin) const { if (name_matcher_.empty()) { return false; } // Look for the name matcher anywhere in the plugin name. if (plugin.name.find(name_matcher_) == string16::npos) { return false; } if (version_range_low_.get() == NULL || version_range_high_.get() == NULL) { return true; } // There's a version range, we must be in it. scoped_ptr<Version> plugin_version( Version::GetVersionFromString(UTF16ToWide(plugin.version))); if (plugin_version.get() == NULL) { // No version could be extracted, assume we don't match the range. return false; } // We match if we are in the range: [low, high) return (version_range_low_->CompareTo(*plugin_version) <= 0 && version_range_high_->CompareTo(*plugin_version) > 0); } void PluginGroup::UpdateDescriptionAndVersion(const WebPluginInfo& plugin) { description_ = plugin.desc; // Update |version_|. Remove spaces and ')' from the version string, // Replace any instances of 'r', ',' or '(' with a dot. std::wstring version = UTF16ToWide(plugin.version); RemoveChars(version, L") ", &version); std::replace(version.begin(), version.end(), 'r', '.'); std::replace(version.begin(), version.end(), ',', '.'); std::replace(version.begin(), version.end(), '(', '.'); if (Version* new_version = Version::GetVersionFromString(version)) version_.reset(new_version); else version_.reset(Version::GetVersionFromString("0")); } void PluginGroup::AddPlugin(const WebPluginInfo& plugin, int position) { web_plugin_infos_.push_back(plugin); // The position of this plugin relative to the global list of plugins. web_plugin_positions_.push_back(position); // A group is enabled if any of the files are enabled. if (plugin.enabled) { if (!enabled_) { // If this is the first enabled plugin, use its description. enabled_ = true; UpdateDescriptionAndVersion(plugin); } } else { // If this is the first plugin and it's disabled, // use its description for now. if (description_.empty()) UpdateDescriptionAndVersion(plugin); } } DictionaryValue* PluginGroup::GetSummary() const { DictionaryValue* result = new DictionaryValue(); result->SetString("name", group_name_); result->SetBoolean("enabled", enabled_); return result; } DictionaryValue* PluginGroup::GetDataForUI() const { DictionaryValue* result = new DictionaryValue(); result->SetString("name", group_name_); result->SetString("description", description_); result->SetString("version", version_->GetString()); result->SetString("update_url", update_url_); result->SetBoolean("critical", IsVulnerable()); bool group_disabled_by_policy = IsPluginNameDisabledByPolicy(group_name_); if (group_disabled_by_policy) { result->SetString("enabledMode", "disabledByPolicy"); } else { result->SetString("enabledMode", enabled_ ? "enabled" : "disabledByUser"); } ListValue* plugin_files = new ListValue(); for (size_t i = 0; i < web_plugin_infos_.size(); ++i) { const WebPluginInfo& web_plugin = web_plugin_infos_[i]; int priority = web_plugin_positions_[i]; DictionaryValue* plugin_file = new DictionaryValue(); plugin_file->SetString("name", web_plugin.name); plugin_file->SetString("description", web_plugin.desc); plugin_file->SetString("path", web_plugin.path.value()); plugin_file->SetString("version", web_plugin.version); bool plugin_disabled_by_policy = group_disabled_by_policy || IsPluginNameDisabledByPolicy(web_plugin.name); if (plugin_disabled_by_policy) { plugin_file->SetString("enabledMode", "disabledByPolicy"); } else { plugin_file->SetString("enabledMode", web_plugin.enabled ? "enabled" : "disabledByUser"); } plugin_file->SetInteger("priority", priority); ListValue* mime_types = new ListValue(); for (std::vector<WebPluginMimeType>::const_iterator type_it = web_plugin.mime_types.begin(); type_it != web_plugin.mime_types.end(); ++type_it) { DictionaryValue* mime_type = new DictionaryValue(); mime_type->SetString("mimeType", type_it->mime_type); mime_type->SetString("description", type_it->description); ListValue* file_extensions = new ListValue(); for (std::vector<std::string>::const_iterator ext_it = type_it->file_extensions.begin(); ext_it != type_it->file_extensions.end(); ++ext_it) { file_extensions->Append(new StringValue(*ext_it)); } mime_type->Set("fileExtensions", file_extensions); mime_types->Append(mime_type); } plugin_file->Set("mimeTypes", mime_types); plugin_files->Append(plugin_file); } result->Set("plugin_files", plugin_files); return result; } // Returns true if the latest version of this plugin group is vulnerable. bool PluginGroup::IsVulnerable() const { if (min_version_.get() == NULL || version_->GetString() == "0") { return false; } return version_->CompareTo(*min_version_) < 0; } void PluginGroup::Enable(bool enable) { for (std::vector<WebPluginInfo>::const_iterator it = web_plugin_infos_.begin(); it != web_plugin_infos_.end(); ++it) { if (enable && !IsPluginNameDisabledByPolicy(it->name)) { NPAPI::PluginList::Singleton()->EnablePlugin(FilePath(it->path)); } else { NPAPI::PluginList::Singleton()->DisablePlugin(FilePath(it->path)); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: prcntfld.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 11:30:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // include --------------------------------------------------------------- #pragma hdrstop #include "prcntfld.hxx" // STATIC DATA ----------------------------------------------------------- /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ PercentField::PercentField( Window* pWin, const ResId& rResId ) : MetricField ( pWin, rResId ), eOldUnit (FUNIT_NONE), nOldMin (0), nOldMax (0), nLastPercent(-1L), nLastValue (-1L), bLockAutoCalculation(sal_False) { nOldSpinSize = GetSpinSize(); nRefValue = Denormalize(MetricField::GetMax(FUNIT_TWIP)); nOldDigits = GetDecimalDigits(); SetCustomUnitText('%'); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetRefValue(long nValue) { long nRealValue = GetRealValue(eOldUnit); nRefValue = nValue; if (!bLockAutoCalculation && (GetUnit() == FUNIT_CUSTOM)) SetPrcntValue(nRealValue, eOldUnit); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::ShowPercent(BOOL bPercent) { if ((bPercent && GetUnit() == FUNIT_CUSTOM) || (!bPercent && GetUnit() != FUNIT_CUSTOM)) return; long nOldValue; if (bPercent) { long nAktWidth, nPercent; nOldValue = GetValue(); eOldUnit = GetUnit(); nOldDigits = GetDecimalDigits(); nOldMin = GetMin(); nOldMax = GetMax(); nOldSpinSize = GetSpinSize(); nOldBaseValue = GetBaseValue(); SetUnit(FUNIT_CUSTOM); SetDecimalDigits( 0 ); nAktWidth = ConvertValue(nOldMin, 0, nOldDigits, eOldUnit, FUNIT_TWIP); // Um 0.5 Prozent aufrunden nPercent = ((nAktWidth * 10) / nRefValue + 5) / 10; MetricField::SetMin(Max(1L, nPercent)); MetricField::SetMax(100); SetSpinSize(5); MetricField::SetBaseValue(0); if (nOldValue != nLastValue) { nAktWidth = ConvertValue(nOldValue, 0, nOldDigits, eOldUnit, FUNIT_TWIP); nPercent = ((nAktWidth * 10) / nRefValue + 5) / 10; MetricFormatter::SetValue(nPercent); nLastPercent = nPercent; nLastValue = nOldValue; } else MetricFormatter::SetValue(nLastPercent); // SetValue(100, FUNIT_CUSTOM); } else { long nOldPercent = GetValue(FUNIT_CUSTOM); nOldValue = Convert(GetValue(), GetUnit(), eOldUnit); SetUnit(eOldUnit); SetDecimalDigits(nOldDigits); MetricField::SetMin(nOldMin); MetricField::SetMax(nOldMax); SetSpinSize(nOldSpinSize); MetricField::SetBaseValue(nOldBaseValue); if (nOldPercent != nLastPercent) { SetPrcntValue(nOldValue, eOldUnit); nLastPercent = nOldPercent; nLastValue = nOldValue; } else SetPrcntValue(nLastValue, eOldUnit); } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetValue(long nNewValue, FieldUnit eInUnit) { MetricFormatter::SetValue(nNewValue, eInUnit); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetPrcntValue(long nNewValue, FieldUnit eInUnit) { if (GetUnit() != FUNIT_CUSTOM || eInUnit == FUNIT_CUSTOM) MetricFormatter::SetValue(Convert(nNewValue, eInUnit, GetUnit())); else { // Ausgangswert ueberschreiben, nicht spaeter restaurieren long nPercent, nAktWidth; if(eInUnit == FUNIT_TWIP) { nAktWidth = ConvertValue(nNewValue, 0, nOldDigits, FUNIT_TWIP, FUNIT_TWIP); } else { long nValue = Convert(nNewValue, eInUnit, eOldUnit); nAktWidth = ConvertValue(nValue, 0, nOldDigits, eOldUnit, FUNIT_TWIP); } nPercent = ((nAktWidth * 10) / nRefValue + 5) / 10; MetricFormatter::SetValue(nPercent); } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetUserValue( long nNewValue, FieldUnit eInUnit ) { if (GetUnit() != FUNIT_CUSTOM || eInUnit == FUNIT_CUSTOM) MetricField::SetUserValue(Convert(nNewValue, eInUnit, GetUnit()),FUNIT_NONE); else { // Ausgangswert ueberschreiben, nicht spaeter restaurieren long nPercent, nAktWidth; if(eInUnit == FUNIT_TWIP) { nAktWidth = ConvertValue(nNewValue, 0, nOldDigits, FUNIT_TWIP, FUNIT_TWIP); } else { long nValue = Convert(nNewValue, eInUnit, eOldUnit); nAktWidth = ConvertValue(nValue, 0, nOldDigits, eOldUnit, FUNIT_TWIP); } nPercent = ((nAktWidth * 10) / nRefValue + 5) / 10; MetricField::SetUserValue(nPercent,FUNIT_NONE); } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetBaseValue(long nNewValue, FieldUnit eInUnit) { if (GetUnit() == FUNIT_CUSTOM) nOldBaseValue = ConvertValue(nNewValue, 0, nOldDigits, eInUnit, eOldUnit); else MetricField::SetBaseValue(nNewValue, eInUnit); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::GetValue( FieldUnit eOutUnit ) { return Convert(MetricField::GetValue(), GetUnit(), eOutUnit); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetMin(long nNewMin, FieldUnit eInUnit) { if (GetUnit() != FUNIT_CUSTOM) MetricField::SetMin(nNewMin, eInUnit); else { if (eInUnit == FUNIT_NONE) eInUnit = eOldUnit; nOldMin = Convert(nNewMin, eInUnit, eOldUnit); long nPercent = Convert(nNewMin, eInUnit, FUNIT_CUSTOM); MetricField::SetMin(Max(1L, nPercent)); } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetMax(long nNewMax, FieldUnit eInUnit) { if (GetUnit() != FUNIT_CUSTOM) MetricField::SetMax(nNewMax, eInUnit); else { if (eInUnit == FUNIT_NONE) eInUnit = eOldUnit; // SetRefValue(Convert(nNewMax, eInUnit, FUNIT_TWIP)); } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::Normalize(long nValue) { if (GetUnit() != FUNIT_CUSTOM) nValue = MetricField::Normalize(nValue); else nValue = nValue * ImpPower10(nOldDigits); return nValue; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::Denormalize(long nValue) { if (GetUnit() != FUNIT_CUSTOM) nValue = MetricField::Denormalize(nValue); else { long nFactor = ImpPower10(nOldDigits); nValue = ((nValue+(nFactor/2)) / nFactor); } return nValue; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ BOOL PercentField::IsValueModified() { if (GetUnit() == FUNIT_CUSTOM) return TRUE; else return MetricField::IsValueModified(); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::ImpPower10( USHORT n ) { USHORT i; long nValue = 1; for ( i=0; i < n; i++ ) nValue *= 10; return nValue; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::GetRealValue(FieldUnit eOutUnit) { if (GetUnit() != FUNIT_CUSTOM) return GetValue(eOutUnit); else return Convert(GetValue(), GetUnit(), eOutUnit); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::Convert(long nValue, FieldUnit eInUnit, FieldUnit eOutUnit) { if (eInUnit == eOutUnit || (eInUnit == FUNIT_NONE && eOutUnit == GetUnit()) || (eOutUnit == FUNIT_NONE && eInUnit == GetUnit())) return nValue; if (eInUnit == FUNIT_CUSTOM) { // Umrechnen in Metrik long nTwipValue = (nRefValue * nValue + 50) / 100; if (eOutUnit == FUNIT_TWIP) // Nur wandeln, wenn unbedingt notwendig return Normalize(nTwipValue); else return ConvertValue(Normalize(nTwipValue), 0, nOldDigits, FUNIT_TWIP, eOutUnit); } if (eOutUnit == FUNIT_CUSTOM) { // Umrechnen in Prozent long nAktWidth; nValue = Denormalize(nValue); if (eInUnit == FUNIT_TWIP) // Nur wandeln, wenn unbedingt notwendig nAktWidth = nValue; else nAktWidth = ConvertValue(nValue, 0, nOldDigits, eInUnit, FUNIT_TWIP); // Um 0.5 Prozent runden return ((nAktWidth * 1000) / nRefValue + 5) / 10; } return ConvertValue(nValue, 0, nOldDigits, eInUnit, eOutUnit); } <commit_msg>INTEGRATION: CWS pchfix02 (1.6.476); FILE MERGED 2006/09/01 17:53:33 kaib 1.6.476.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: prcntfld.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:34:21 $ * * 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_sw.hxx" // include --------------------------------------------------------------- #include "prcntfld.hxx" // STATIC DATA ----------------------------------------------------------- /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ PercentField::PercentField( Window* pWin, const ResId& rResId ) : MetricField ( pWin, rResId ), eOldUnit (FUNIT_NONE), nOldMin (0), nOldMax (0), nLastPercent(-1L), nLastValue (-1L), bLockAutoCalculation(sal_False) { nOldSpinSize = GetSpinSize(); nRefValue = Denormalize(MetricField::GetMax(FUNIT_TWIP)); nOldDigits = GetDecimalDigits(); SetCustomUnitText('%'); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetRefValue(long nValue) { long nRealValue = GetRealValue(eOldUnit); nRefValue = nValue; if (!bLockAutoCalculation && (GetUnit() == FUNIT_CUSTOM)) SetPrcntValue(nRealValue, eOldUnit); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::ShowPercent(BOOL bPercent) { if ((bPercent && GetUnit() == FUNIT_CUSTOM) || (!bPercent && GetUnit() != FUNIT_CUSTOM)) return; long nOldValue; if (bPercent) { long nAktWidth, nPercent; nOldValue = GetValue(); eOldUnit = GetUnit(); nOldDigits = GetDecimalDigits(); nOldMin = GetMin(); nOldMax = GetMax(); nOldSpinSize = GetSpinSize(); nOldBaseValue = GetBaseValue(); SetUnit(FUNIT_CUSTOM); SetDecimalDigits( 0 ); nAktWidth = ConvertValue(nOldMin, 0, nOldDigits, eOldUnit, FUNIT_TWIP); // Um 0.5 Prozent aufrunden nPercent = ((nAktWidth * 10) / nRefValue + 5) / 10; MetricField::SetMin(Max(1L, nPercent)); MetricField::SetMax(100); SetSpinSize(5); MetricField::SetBaseValue(0); if (nOldValue != nLastValue) { nAktWidth = ConvertValue(nOldValue, 0, nOldDigits, eOldUnit, FUNIT_TWIP); nPercent = ((nAktWidth * 10) / nRefValue + 5) / 10; MetricFormatter::SetValue(nPercent); nLastPercent = nPercent; nLastValue = nOldValue; } else MetricFormatter::SetValue(nLastPercent); // SetValue(100, FUNIT_CUSTOM); } else { long nOldPercent = GetValue(FUNIT_CUSTOM); nOldValue = Convert(GetValue(), GetUnit(), eOldUnit); SetUnit(eOldUnit); SetDecimalDigits(nOldDigits); MetricField::SetMin(nOldMin); MetricField::SetMax(nOldMax); SetSpinSize(nOldSpinSize); MetricField::SetBaseValue(nOldBaseValue); if (nOldPercent != nLastPercent) { SetPrcntValue(nOldValue, eOldUnit); nLastPercent = nOldPercent; nLastValue = nOldValue; } else SetPrcntValue(nLastValue, eOldUnit); } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetValue(long nNewValue, FieldUnit eInUnit) { MetricFormatter::SetValue(nNewValue, eInUnit); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetPrcntValue(long nNewValue, FieldUnit eInUnit) { if (GetUnit() != FUNIT_CUSTOM || eInUnit == FUNIT_CUSTOM) MetricFormatter::SetValue(Convert(nNewValue, eInUnit, GetUnit())); else { // Ausgangswert ueberschreiben, nicht spaeter restaurieren long nPercent, nAktWidth; if(eInUnit == FUNIT_TWIP) { nAktWidth = ConvertValue(nNewValue, 0, nOldDigits, FUNIT_TWIP, FUNIT_TWIP); } else { long nValue = Convert(nNewValue, eInUnit, eOldUnit); nAktWidth = ConvertValue(nValue, 0, nOldDigits, eOldUnit, FUNIT_TWIP); } nPercent = ((nAktWidth * 10) / nRefValue + 5) / 10; MetricFormatter::SetValue(nPercent); } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetUserValue( long nNewValue, FieldUnit eInUnit ) { if (GetUnit() != FUNIT_CUSTOM || eInUnit == FUNIT_CUSTOM) MetricField::SetUserValue(Convert(nNewValue, eInUnit, GetUnit()),FUNIT_NONE); else { // Ausgangswert ueberschreiben, nicht spaeter restaurieren long nPercent, nAktWidth; if(eInUnit == FUNIT_TWIP) { nAktWidth = ConvertValue(nNewValue, 0, nOldDigits, FUNIT_TWIP, FUNIT_TWIP); } else { long nValue = Convert(nNewValue, eInUnit, eOldUnit); nAktWidth = ConvertValue(nValue, 0, nOldDigits, eOldUnit, FUNIT_TWIP); } nPercent = ((nAktWidth * 10) / nRefValue + 5) / 10; MetricField::SetUserValue(nPercent,FUNIT_NONE); } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetBaseValue(long nNewValue, FieldUnit eInUnit) { if (GetUnit() == FUNIT_CUSTOM) nOldBaseValue = ConvertValue(nNewValue, 0, nOldDigits, eInUnit, eOldUnit); else MetricField::SetBaseValue(nNewValue, eInUnit); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::GetValue( FieldUnit eOutUnit ) { return Convert(MetricField::GetValue(), GetUnit(), eOutUnit); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetMin(long nNewMin, FieldUnit eInUnit) { if (GetUnit() != FUNIT_CUSTOM) MetricField::SetMin(nNewMin, eInUnit); else { if (eInUnit == FUNIT_NONE) eInUnit = eOldUnit; nOldMin = Convert(nNewMin, eInUnit, eOldUnit); long nPercent = Convert(nNewMin, eInUnit, FUNIT_CUSTOM); MetricField::SetMin(Max(1L, nPercent)); } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ void PercentField::SetMax(long nNewMax, FieldUnit eInUnit) { if (GetUnit() != FUNIT_CUSTOM) MetricField::SetMax(nNewMax, eInUnit); else { if (eInUnit == FUNIT_NONE) eInUnit = eOldUnit; // SetRefValue(Convert(nNewMax, eInUnit, FUNIT_TWIP)); } } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::Normalize(long nValue) { if (GetUnit() != FUNIT_CUSTOM) nValue = MetricField::Normalize(nValue); else nValue = nValue * ImpPower10(nOldDigits); return nValue; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::Denormalize(long nValue) { if (GetUnit() != FUNIT_CUSTOM) nValue = MetricField::Denormalize(nValue); else { long nFactor = ImpPower10(nOldDigits); nValue = ((nValue+(nFactor/2)) / nFactor); } return nValue; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ BOOL PercentField::IsValueModified() { if (GetUnit() == FUNIT_CUSTOM) return TRUE; else return MetricField::IsValueModified(); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::ImpPower10( USHORT n ) { USHORT i; long nValue = 1; for ( i=0; i < n; i++ ) nValue *= 10; return nValue; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::GetRealValue(FieldUnit eOutUnit) { if (GetUnit() != FUNIT_CUSTOM) return GetValue(eOutUnit); else return Convert(GetValue(), GetUnit(), eOutUnit); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ long PercentField::Convert(long nValue, FieldUnit eInUnit, FieldUnit eOutUnit) { if (eInUnit == eOutUnit || (eInUnit == FUNIT_NONE && eOutUnit == GetUnit()) || (eOutUnit == FUNIT_NONE && eInUnit == GetUnit())) return nValue; if (eInUnit == FUNIT_CUSTOM) { // Umrechnen in Metrik long nTwipValue = (nRefValue * nValue + 50) / 100; if (eOutUnit == FUNIT_TWIP) // Nur wandeln, wenn unbedingt notwendig return Normalize(nTwipValue); else return ConvertValue(Normalize(nTwipValue), 0, nOldDigits, FUNIT_TWIP, eOutUnit); } if (eOutUnit == FUNIT_CUSTOM) { // Umrechnen in Prozent long nAktWidth; nValue = Denormalize(nValue); if (eInUnit == FUNIT_TWIP) // Nur wandeln, wenn unbedingt notwendig nAktWidth = nValue; else nAktWidth = ConvertValue(nValue, 0, nOldDigits, eInUnit, FUNIT_TWIP); // Um 0.5 Prozent runden return ((nAktWidth * 1000) / nRefValue + 5) / 10; } return ConvertValue(nValue, 0, nOldDigits, eInUnit, eOutUnit); } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File IterativeElasticSystem.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: IterativeElasticSystem solve routines // /////////////////////////////////////////////////////////////////////////////// #include <boost/format.hpp> #include <LibUtilities/Foundations/Interp.h> #include <LibUtilities/BasicUtils/FileSystem.h> #include <StdRegions/StdQuadExp.h> #include <StdRegions/StdTriExp.h> #include <LocalRegions/MatrixKey.h> #include <MultiRegions/ContField2D.h> #include <MultiRegions/GlobalLinSysDirectStaticCond.h> #include <SolverUtils/Core/Deform.h> #include <LinearElasticSolver/EquationSystems/IterativeElasticSystem.h> namespace Nektar { string IterativeElasticSystem::className = GetEquationSystemFactory(). RegisterCreatorFunction("IterativeElasticSystem", IterativeElasticSystem::create); IterativeElasticSystem::IterativeElasticSystem( const LibUtilities::SessionReaderSharedPtr& pSession) : LinearElasticSystem(pSession) { } void IterativeElasticSystem::v_InitObject() { LinearElasticSystem::v_InitObject(); const int nVel = m_fields[0]->GetCoordim(0); // Read in number of steps to take. m_session->LoadParameter("NumSteps", m_numSteps, 0); ASSERTL0(m_numSteps > 0, "You must specify at least one step"); // Read in whether to repeatedly apply boundary conditions (for e.g. // rotation purposes). string bcType; m_session->LoadSolverInfo("BCType", bcType, "Normal"); m_repeatBCs = bcType != "Normal"; if (!m_repeatBCs) { // Loop over BCs, identify which ones we need to deform. const Array<OneD, const SpatialDomains::BoundaryConditionShPtr> &bndCond = m_fields[0]->GetBndConditions(); for (int i = 0; i < bndCond.num_elements(); ++i) { if (bndCond[i]->GetUserDefined() == SpatialDomains::eWall) { m_toDeform.push_back(i); } } ASSERTL0(m_toDeform.size() > 0, "Must tag at least one boundary " "with the WALL user-defined type"); m_savedBCs = Array<OneD, Array<OneD, Array<OneD, NekDouble> > >( m_toDeform.size()); for (int i = 0; i < m_toDeform.size(); ++i) { m_savedBCs[i] = Array<OneD, Array<OneD, NekDouble> >(nVel); for (int j = 0; j < nVel; ++j) { const int id = m_toDeform[i]; MultiRegions::ExpListSharedPtr bndCondExp = m_fields[j]->GetBndCondExpansions()[id]; int nCoeffs = bndCondExp->GetNcoeffs(); m_savedBCs[i][j] = Array<OneD, NekDouble>(nCoeffs); Vmath::Smul(nCoeffs, 1.0/m_numSteps, bndCondExp->GetCoeffs(), 1, bndCondExp->UpdateCoeffs(), 1); Vmath::Vcopy(nCoeffs, bndCondExp->GetCoeffs(), 1, m_savedBCs[i][j], 1); } } } } void IterativeElasticSystem::v_GenerateSummary(SolverUtils::SummaryList& s) { LinearElasticSystem::v_GenerateSummary(s); } void IterativeElasticSystem::v_DoSolve() { int i, j, k; // Write initial geometry for consistency/script purposes WriteGeometry(0); // Now loop over desired number of steps for (i = 1; i <= m_numSteps; ++i) { int invalidElmtId = -1; // Perform solve for this iteration and update geometry accordingly. LinearElasticSystem::v_DoSolve(); UpdateGeometry(m_graph, m_fields); // Check for invalid elements. for (j = 0; j < m_fields[0]->GetExpSize(); ++j) { SpatialDomains::GeomFactorsSharedPtr geomFac = m_fields[0]->GetExp(j)->GetGeom()->GetGeomFactors(); if (!geomFac->IsValid()) { invalidElmtId = m_fields[0]->GetExp(j)->GetGeom()->GetGlobalID(); break; } } m_session->GetComm()->AllReduce(invalidElmtId, LibUtilities::ReduceMax); // If we found an invalid element, exit loop without writing output. if (invalidElmtId >= 0) { if (m_session->GetComm()->GetRank() == 0) { cout << "- Detected negative Jacobian in element " << invalidElmtId << "; terminating" << endl; } break; } WriteGeometry(i); if (m_session->GetComm()->GetRank() == 0) { cout << "Step: " << i << endl; } // Update boundary conditions if (m_repeatBCs) { for (j = 0; j < m_fields.num_elements(); ++j) { string varName = m_session->GetVariable(j); m_fields[j]->EvaluateBoundaryConditions(m_time, varName); } } else { for (j = 0; j < m_fields.num_elements(); ++j) { const Array<OneD, const MultiRegions::ExpListSharedPtr> &bndCondExp = m_fields[j]->GetBndCondExpansions(); for (k = 0; k < m_toDeform.size(); ++k) { const int id = m_toDeform[k]; const int nCoeffs = bndCondExp[id]->GetNcoeffs(); Vmath::Vcopy(nCoeffs, m_savedBCs[k][j], 1, bndCondExp[id]->UpdateCoeffs(), 1); } } } } } /** * @brief Write out a file in serial or directory in parallel containing new * mesh geometry. */ void IterativeElasticSystem::WriteGeometry(const int i) { fs::path filename; stringstream s; s << m_session->GetSessionName() << "-" << i; if (m_session->GetComm()->GetSize() > 1) { s << "_xml"; if(!fs::is_directory(s.str())) { fs::create_directory(s.str()); } boost::format pad("P%1$07d.xml"); pad % m_session->GetComm()->GetRank(); filename = fs::path(s.str()) / fs::path(pad.str()); } else { s << ".xml"; filename = fs::path(s.str()); } string fname = LibUtilities::PortablePath(filename); m_fields[0]->GetGraph()->WriteGeometry(fname); } } <commit_msg>fix for parralel running<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File IterativeElasticSystem.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: IterativeElasticSystem solve routines // /////////////////////////////////////////////////////////////////////////////// #include <boost/format.hpp> #include <LibUtilities/Foundations/Interp.h> #include <LibUtilities/BasicUtils/FileSystem.h> #include <StdRegions/StdQuadExp.h> #include <StdRegions/StdTriExp.h> #include <LocalRegions/MatrixKey.h> #include <MultiRegions/ContField2D.h> #include <MultiRegions/GlobalLinSysDirectStaticCond.h> #include <SolverUtils/Core/Deform.h> #include <LinearElasticSolver/EquationSystems/IterativeElasticSystem.h> namespace Nektar { string IterativeElasticSystem::className = GetEquationSystemFactory(). RegisterCreatorFunction("IterativeElasticSystem", IterativeElasticSystem::create); IterativeElasticSystem::IterativeElasticSystem( const LibUtilities::SessionReaderSharedPtr& pSession) : LinearElasticSystem(pSession) { } void IterativeElasticSystem::v_InitObject() { LinearElasticSystem::v_InitObject(); const int nVel = m_fields[0]->GetCoordim(0); // Read in number of steps to take. m_session->LoadParameter("NumSteps", m_numSteps, 0); ASSERTL0(m_numSteps > 0, "You must specify at least one step"); // Read in whether to repeatedly apply boundary conditions (for e.g. // rotation purposes). string bcType; m_session->LoadSolverInfo("BCType", bcType, "Normal"); m_repeatBCs = bcType != "Normal"; if (!m_repeatBCs) { // Loop over BCs, identify which ones we need to deform. const Array<OneD, const SpatialDomains::BoundaryConditionShPtr> &bndCond = m_fields[0]->GetBndConditions(); for (int i = 0; i < bndCond.num_elements(); ++i) { if (bndCond[i]->GetUserDefined() == SpatialDomains::eWall) { m_toDeform.push_back(i); } } if(m_toDeform.size() > 0) { m_savedBCs = Array<OneD, Array<OneD, Array<OneD, NekDouble> > >( m_toDeform.size()); for (int i = 0; i < m_toDeform.size(); ++i) { m_savedBCs[i] = Array<OneD, Array<OneD, NekDouble> >(nVel); for (int j = 0; j < nVel; ++j) { const int id = m_toDeform[i]; MultiRegions::ExpListSharedPtr bndCondExp = m_fields[j]->GetBndCondExpansions()[id]; int nCoeffs = bndCondExp->GetNcoeffs(); m_savedBCs[i][j] = Array<OneD, NekDouble>(nCoeffs); Vmath::Smul(nCoeffs, 1.0/m_numSteps, bndCondExp->GetCoeffs(), 1, bndCondExp->UpdateCoeffs(), 1); Vmath::Vcopy(nCoeffs, bndCondExp->GetCoeffs(), 1, m_savedBCs[i][j], 1); } } } } } void IterativeElasticSystem::v_GenerateSummary(SolverUtils::SummaryList& s) { LinearElasticSystem::v_GenerateSummary(s); } void IterativeElasticSystem::v_DoSolve() { int i, j, k; // Write initial geometry for consistency/script purposes WriteGeometry(0); // Now loop over desired number of steps for (i = 1; i <= m_numSteps; ++i) { int invalidElmtId = -1; // Perform solve for this iteration and update geometry accordingly. LinearElasticSystem::v_DoSolve(); UpdateGeometry(m_graph, m_fields); // Check for invalid elements. for (j = 0; j < m_fields[0]->GetExpSize(); ++j) { SpatialDomains::GeomFactorsSharedPtr geomFac = m_fields[0]->GetExp(j)->GetGeom()->GetGeomFactors(); if (!geomFac->IsValid()) { invalidElmtId = m_fields[0]->GetExp(j)->GetGeom()->GetGlobalID(); break; } } m_session->GetComm()->AllReduce(invalidElmtId, LibUtilities::ReduceMax); // If we found an invalid element, exit loop without writing output. if (invalidElmtId >= 0) { if (m_session->GetComm()->GetRank() == 0) { cout << "- Detected negative Jacobian in element " << invalidElmtId << "; terminating" << endl; } break; } WriteGeometry(i); if (m_session->GetComm()->GetRank() == 0) { cout << "Step: " << i << endl; } // Update boundary conditions if (m_repeatBCs) { for (j = 0; j < m_fields.num_elements(); ++j) { string varName = m_session->GetVariable(j); m_fields[j]->EvaluateBoundaryConditions(m_time, varName); } } else { for (j = 0; j < m_fields.num_elements(); ++j) { const Array<OneD, const MultiRegions::ExpListSharedPtr> &bndCondExp = m_fields[j]->GetBndCondExpansions(); for (k = 0; k < m_toDeform.size(); ++k) { const int id = m_toDeform[k]; const int nCoeffs = bndCondExp[id]->GetNcoeffs(); Vmath::Vcopy(nCoeffs, m_savedBCs[k][j], 1, bndCondExp[id]->UpdateCoeffs(), 1); } } } } } /** * @brief Write out a file in serial or directory in parallel containing new * mesh geometry. */ void IterativeElasticSystem::WriteGeometry(const int i) { fs::path filename; stringstream s; s << m_session->GetSessionName() << "-" << i; if (m_session->GetComm()->GetSize() > 1) { s << "_xml"; if(!fs::is_directory(s.str())) { fs::create_directory(s.str()); } boost::format pad("P%1$07d.xml"); pad % m_session->GetComm()->GetRank(); filename = fs::path(s.str()) / fs::path(pad.str()); } else { s << ".xml"; filename = fs::path(s.str()); } string fname = LibUtilities::PortablePath(filename); m_fields[0]->GetGraph()->WriteGeometry(fname); } } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/info_bubble.h" #include "app/gfx/canvas.h" #include "app/gfx/color_utils.h" #include "app/gfx/path.h" #include "chrome/browser/window_sizer.h" #include "chrome/common/notification_service.h" #include "third_party/skia/include/core/SkPaint.h" #include "views/fill_layout.h" #include "views/widget/root_view.h" #include "views/window/window.h" namespace { // Background color of the bubble. #if defined(OS_WIN) const SkColor kBackgroundColor = color_utils::GetSysSkColor(COLOR_WINDOW); #else // TODO(beng): source from theme provider. const SkColor kBackgroundColor = SK_ColorWHITE; #endif } // BorderContents ------------------------------------------------------------- // This is used to paint the border of the InfoBubble. Windows uses this via // BorderWidget (see below), while others can use it directly in the bubble. class BorderContents : public views::View { public: BorderContents() { } // Given the size of the contents and the rect to point at, initializes the // bubble and returns the bounds of both the border // and the contents inside the bubble. // |is_rtl| is true if the UI is RTL and thus the arrow should default to the // right side of the bubble; otherwise it defaults to the left top corner, and // then is moved as necessary to try and fit the whole bubble on the same // monitor as the rect being pointed to. // // TODO(pkasting): Maybe this should use mirroring transformations instead, // which would hopefully simplify this code. void InitAndGetBounds( const gfx::Rect& position_relative_to, // In screen coordinates const gfx::Size& contents_size, bool is_rtl, gfx::Rect* contents_bounds, // Returned in window coordinates gfx::Rect* window_bounds); // Returned in screen coordinates private: virtual ~BorderContents() { } // Overridden from View: virtual void Paint(gfx::Canvas* canvas); DISALLOW_COPY_AND_ASSIGN(BorderContents); }; void BorderContents::InitAndGetBounds( const gfx::Rect& position_relative_to, const gfx::Size& contents_size, bool is_rtl, gfx::Rect* contents_bounds, gfx::Rect* window_bounds) { // Margins between the contents and the inside of the border, in pixels. const int kLeftMargin = 6; const int kTopMargin = 6; const int kRightMargin = 6; const int kBottomMargin = 9; // Set the border. BubbleBorder* bubble_border = new BubbleBorder; set_border(bubble_border); bubble_border->set_background_color(kBackgroundColor); // Give the contents a margin. gfx::Size local_contents_size(contents_size); local_contents_size.Enlarge(kLeftMargin + kRightMargin, kTopMargin + kBottomMargin); // Try putting the arrow in its default location, and calculating the bounds. BubbleBorder::ArrowLocation arrow_location(is_rtl ? BubbleBorder::TOP_RIGHT : BubbleBorder::TOP_LEFT); bubble_border->set_arrow_location(arrow_location); *window_bounds = bubble_border->GetBounds(position_relative_to, local_contents_size); // See if those bounds will fit on the monitor. scoped_ptr<WindowSizer::MonitorInfoProvider> monitor_provider( WindowSizer::CreateDefaultMonitorInfoProvider()); gfx::Rect monitor_bounds( monitor_provider->GetMonitorWorkAreaMatching(position_relative_to)); if (!monitor_bounds.IsEmpty() && !monitor_bounds.Contains(*window_bounds)) { // The bounds don't fit. Move the arrow to try and improve things. bool arrow_on_left = (is_rtl ? (window_bounds->x() < monitor_bounds.x()) : (window_bounds->right() <= monitor_bounds.right())); if (window_bounds->bottom() > monitor_bounds.bottom()) { arrow_location = arrow_on_left ? BubbleBorder::BOTTOM_LEFT : BubbleBorder::BOTTOM_RIGHT; } else { arrow_location = arrow_on_left ? BubbleBorder::TOP_LEFT : BubbleBorder::TOP_RIGHT; } bubble_border->set_arrow_location(arrow_location); // Now get the recalculated bounds. *window_bounds = bubble_border->GetBounds(position_relative_to, local_contents_size); } // Calculate the bounds of the contained contents (in window coordinates) by // subtracting the border dimensions and margin amounts. *contents_bounds = gfx::Rect(gfx::Point(), window_bounds->size()); gfx::Insets insets; bubble_border->GetInsets(&insets); contents_bounds->Inset(insets.left() + kLeftMargin, insets.top() + kTopMargin, insets.right() + kRightMargin, insets.bottom() + kBottomMargin); } void BorderContents::Paint(gfx::Canvas* canvas) { // The border of this view creates an anti-aliased round-rect region for the // contents, which we need to fill with the background color. SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); paint.setColor(kBackgroundColor); gfx::Path path; gfx::Rect bounds(GetLocalBounds(false)); SkRect rect; rect.set(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y()), SkIntToScalar(bounds.right()), SkIntToScalar(bounds.bottom())); SkScalar radius = SkIntToScalar(BubbleBorder::GetCornerRadius()); path.addRoundRect(rect, radius, radius); canvas->drawPath(path, paint); // Now we paint the border, so it will be alpha-blended atop the contents. // This looks slightly better in the corners than drawing the contents atop // the border. PaintBorder(canvas); } #if defined(OS_WIN) // BorderWidget --------------------------------------------------------------- BorderWidget::BorderWidget() { set_delete_on_destroy(false); // Our owner will free us manually. set_window_style(WS_POPUP); set_window_ex_style(WS_EX_TOOLWINDOW | WS_EX_LAYERED); } gfx::Rect BorderWidget::InitAndGetBounds( HWND owner, const gfx::Rect& position_relative_to, const gfx::Size& contents_size, bool is_rtl) { // Set up the border view and ask it to calculate our bounds (and our // contents'). BorderContents* border_contents = new BorderContents; gfx::Rect contents_bounds, window_bounds; border_contents->InitAndGetBounds(position_relative_to, contents_size, is_rtl, &contents_bounds, &window_bounds); // Initialize ourselves. WidgetWin::Init(GetAncestor(owner, GA_ROOT), window_bounds); SetContentsView(border_contents); SetWindowPos(owner, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOREDRAW); // Chop a hole out of our region to show the contents through. // CreateRectRgn() expects (left, top, right, bottom) in window coordinates. HRGN contents_region = CreateRectRgn(contents_bounds.x(), contents_bounds.y(), contents_bounds.right(), contents_bounds.bottom()); HRGN window_region = CreateRectRgn(0, 0, window_bounds.width(), window_bounds.height()); CombineRgn(window_region, window_region, contents_region, RGN_XOR); DeleteObject(contents_region); SetWindowRgn(window_region, true); // Return |contents_bounds| in screen coordinates. contents_bounds.Offset(window_bounds.origin()); return contents_bounds; } LRESULT BorderWidget::OnMouseActivate(HWND window, UINT hit_test, UINT mouse_message) { // Never activate. return MA_NOACTIVATE; } #endif // InfoBubble ----------------------------------------------------------------- // static InfoBubble* InfoBubble::Show(views::Window* parent, const gfx::Rect& position_relative_to, views::View* contents, InfoBubbleDelegate* delegate) { InfoBubble* window = new InfoBubble; window->Init(parent, position_relative_to, contents, delegate); return window; } void InfoBubble::Close() { Close(false); } InfoBubble::InfoBubble() : #if defined(OS_LINUX) WidgetGtk(TYPE_POPUP), #endif delegate_(NULL), parent_(NULL), closed_(false) { } void InfoBubble::Init(views::Window* parent, const gfx::Rect& position_relative_to, views::View* contents, InfoBubbleDelegate* delegate) { parent_ = parent; parent_->DisableInactiveRendering(); delegate_ = delegate; // Create the main window. #if defined(OS_WIN) set_window_style(WS_POPUP | WS_CLIPCHILDREN); set_window_ex_style(WS_EX_TOOLWINDOW); WidgetWin::Init(parent->GetNativeWindow(), gfx::Rect()); #elif defined(OS_LINUX) MakeTransparent(); WidgetGtk::Init(GTK_WIDGET(parent->GetNativeWindow()), gfx::Rect()); #endif // Create a View to hold the contents of the main window. views::View* contents_view = new views::View; // Adding |contents| as a child has to be done before we call // contents->GetPreferredSize() below, since some supplied views don't // actually initialize themselves until they're added to a hierarchy. contents_view->AddChildView(contents); SetContentsView(contents_view); // Calculate and set the bounds for all windows and views. gfx::Rect window_bounds; #if defined(OS_WIN) border_.reset(new BorderWidget); // Initialize and position the border window. window_bounds = border_->InitAndGetBounds(GetNativeView(), position_relative_to, contents->GetPreferredSize(), contents->UILayoutIsRightToLeft()); // Make |contents| take up the entire contents view. contents_view->SetLayoutManager(new views::FillLayout); // Paint the background color behind the contents. contents_view->set_background( views::Background::CreateSolidBackground(kBackgroundColor)); #else // Create a view to paint the border and background. BorderContents* border_contents = new BorderContents; gfx::Rect contents_bounds; border_contents->InitAndGetBounds(position_relative_to, contents->GetPreferredSize(), is_rtl, &contents_bounds, &window_bounds); // This new view must be added before |contents| so it will paint under it. contents_view->AddChildView(border_contents, 0); // |contents_view| has no layout manager, so we have to explicitly position // its children. border_contents->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size())); contents->SetBounds(contents_bounds); #endif SetBounds(window_bounds); #if defined(OS_WIN) // Register the Escape accelerator for closing. GetFocusManager()->RegisterAccelerator( views::Accelerator(VK_ESCAPE, false, false, false), this); #endif // Done creating the bubble. NotificationService::current()->Notify(NotificationType::INFO_BUBBLE_CREATED, Source<InfoBubble>(this), NotificationService::NoDetails()); // Show the window. #if defined(OS_WIN) border_->ShowWindow(SW_SHOW); ShowWindow(SW_SHOW); #elif defined(OS_LINUX) views::WidgetGtk::Show(); #endif } #if defined(OS_WIN) void InfoBubble::OnActivate(UINT action, BOOL minimized, HWND window) { // The popup should close when it is deactivated. if (action == WA_INACTIVE && !closed_) { Close(); } else if (action == WA_ACTIVE) { DCHECK(GetRootView()->GetChildViewCount() > 0); GetRootView()->GetChildViewAt(0)->RequestFocus(); } } #endif void InfoBubble::Close(bool closed_by_escape) { if (closed_) return; if (delegate_) delegate_->InfoBubbleClosing(this, closed_by_escape); closed_ = true; #if defined(OS_WIN) border_->Close(); WidgetWin::Close(); #elif defined(OS_LINUX) WidgetGtk::Close(); #endif } bool InfoBubble::AcceleratorPressed(const views::Accelerator& accelerator) { if (!delegate_ || delegate_->CloseOnEscape()) { Close(true); return true; } return false; } <commit_msg>Fix the Linux Views build, sigh. We need a trybot.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/info_bubble.h" #include "app/gfx/canvas.h" #include "app/gfx/color_utils.h" #include "app/gfx/path.h" #include "chrome/browser/window_sizer.h" #include "chrome/common/notification_service.h" #include "third_party/skia/include/core/SkPaint.h" #include "views/fill_layout.h" #include "views/widget/root_view.h" #include "views/window/window.h" namespace { // Background color of the bubble. #if defined(OS_WIN) const SkColor kBackgroundColor = color_utils::GetSysSkColor(COLOR_WINDOW); #else // TODO(beng): source from theme provider. const SkColor kBackgroundColor = SK_ColorWHITE; #endif } // BorderContents ------------------------------------------------------------- // This is used to paint the border of the InfoBubble. Windows uses this via // BorderWidget (see below), while others can use it directly in the bubble. class BorderContents : public views::View { public: BorderContents() { } // Given the size of the contents and the rect to point at, initializes the // bubble and returns the bounds of both the border // and the contents inside the bubble. // |is_rtl| is true if the UI is RTL and thus the arrow should default to the // right side of the bubble; otherwise it defaults to the left top corner, and // then is moved as necessary to try and fit the whole bubble on the same // monitor as the rect being pointed to. // // TODO(pkasting): Maybe this should use mirroring transformations instead, // which would hopefully simplify this code. void InitAndGetBounds( const gfx::Rect& position_relative_to, // In screen coordinates const gfx::Size& contents_size, bool is_rtl, gfx::Rect* contents_bounds, // Returned in window coordinates gfx::Rect* window_bounds); // Returned in screen coordinates private: virtual ~BorderContents() { } // Overridden from View: virtual void Paint(gfx::Canvas* canvas); DISALLOW_COPY_AND_ASSIGN(BorderContents); }; void BorderContents::InitAndGetBounds( const gfx::Rect& position_relative_to, const gfx::Size& contents_size, bool is_rtl, gfx::Rect* contents_bounds, gfx::Rect* window_bounds) { // Margins between the contents and the inside of the border, in pixels. const int kLeftMargin = 6; const int kTopMargin = 6; const int kRightMargin = 6; const int kBottomMargin = 9; // Set the border. BubbleBorder* bubble_border = new BubbleBorder; set_border(bubble_border); bubble_border->set_background_color(kBackgroundColor); // Give the contents a margin. gfx::Size local_contents_size(contents_size); local_contents_size.Enlarge(kLeftMargin + kRightMargin, kTopMargin + kBottomMargin); // Try putting the arrow in its default location, and calculating the bounds. BubbleBorder::ArrowLocation arrow_location(is_rtl ? BubbleBorder::TOP_RIGHT : BubbleBorder::TOP_LEFT); bubble_border->set_arrow_location(arrow_location); *window_bounds = bubble_border->GetBounds(position_relative_to, local_contents_size); // See if those bounds will fit on the monitor. scoped_ptr<WindowSizer::MonitorInfoProvider> monitor_provider( WindowSizer::CreateDefaultMonitorInfoProvider()); gfx::Rect monitor_bounds( monitor_provider->GetMonitorWorkAreaMatching(position_relative_to)); if (!monitor_bounds.IsEmpty() && !monitor_bounds.Contains(*window_bounds)) { // The bounds don't fit. Move the arrow to try and improve things. bool arrow_on_left = (is_rtl ? (window_bounds->x() < monitor_bounds.x()) : (window_bounds->right() <= monitor_bounds.right())); if (window_bounds->bottom() > monitor_bounds.bottom()) { arrow_location = arrow_on_left ? BubbleBorder::BOTTOM_LEFT : BubbleBorder::BOTTOM_RIGHT; } else { arrow_location = arrow_on_left ? BubbleBorder::TOP_LEFT : BubbleBorder::TOP_RIGHT; } bubble_border->set_arrow_location(arrow_location); // Now get the recalculated bounds. *window_bounds = bubble_border->GetBounds(position_relative_to, local_contents_size); } // Calculate the bounds of the contained contents (in window coordinates) by // subtracting the border dimensions and margin amounts. *contents_bounds = gfx::Rect(gfx::Point(), window_bounds->size()); gfx::Insets insets; bubble_border->GetInsets(&insets); contents_bounds->Inset(insets.left() + kLeftMargin, insets.top() + kTopMargin, insets.right() + kRightMargin, insets.bottom() + kBottomMargin); } void BorderContents::Paint(gfx::Canvas* canvas) { // The border of this view creates an anti-aliased round-rect region for the // contents, which we need to fill with the background color. SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); paint.setColor(kBackgroundColor); gfx::Path path; gfx::Rect bounds(GetLocalBounds(false)); SkRect rect; rect.set(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y()), SkIntToScalar(bounds.right()), SkIntToScalar(bounds.bottom())); SkScalar radius = SkIntToScalar(BubbleBorder::GetCornerRadius()); path.addRoundRect(rect, radius, radius); canvas->drawPath(path, paint); // Now we paint the border, so it will be alpha-blended atop the contents. // This looks slightly better in the corners than drawing the contents atop // the border. PaintBorder(canvas); } #if defined(OS_WIN) // BorderWidget --------------------------------------------------------------- BorderWidget::BorderWidget() { set_delete_on_destroy(false); // Our owner will free us manually. set_window_style(WS_POPUP); set_window_ex_style(WS_EX_TOOLWINDOW | WS_EX_LAYERED); } gfx::Rect BorderWidget::InitAndGetBounds( HWND owner, const gfx::Rect& position_relative_to, const gfx::Size& contents_size, bool is_rtl) { // Set up the border view and ask it to calculate our bounds (and our // contents'). BorderContents* border_contents = new BorderContents; gfx::Rect contents_bounds, window_bounds; border_contents->InitAndGetBounds(position_relative_to, contents_size, is_rtl, &contents_bounds, &window_bounds); // Initialize ourselves. WidgetWin::Init(GetAncestor(owner, GA_ROOT), window_bounds); SetContentsView(border_contents); SetWindowPos(owner, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOREDRAW); // Chop a hole out of our region to show the contents through. // CreateRectRgn() expects (left, top, right, bottom) in window coordinates. HRGN contents_region = CreateRectRgn(contents_bounds.x(), contents_bounds.y(), contents_bounds.right(), contents_bounds.bottom()); HRGN window_region = CreateRectRgn(0, 0, window_bounds.width(), window_bounds.height()); CombineRgn(window_region, window_region, contents_region, RGN_XOR); DeleteObject(contents_region); SetWindowRgn(window_region, true); // Return |contents_bounds| in screen coordinates. contents_bounds.Offset(window_bounds.origin()); return contents_bounds; } LRESULT BorderWidget::OnMouseActivate(HWND window, UINT hit_test, UINT mouse_message) { // Never activate. return MA_NOACTIVATE; } #endif // InfoBubble ----------------------------------------------------------------- // static InfoBubble* InfoBubble::Show(views::Window* parent, const gfx::Rect& position_relative_to, views::View* contents, InfoBubbleDelegate* delegate) { InfoBubble* window = new InfoBubble; window->Init(parent, position_relative_to, contents, delegate); return window; } void InfoBubble::Close() { Close(false); } InfoBubble::InfoBubble() : #if defined(OS_LINUX) WidgetGtk(TYPE_POPUP), #endif delegate_(NULL), parent_(NULL), closed_(false) { } void InfoBubble::Init(views::Window* parent, const gfx::Rect& position_relative_to, views::View* contents, InfoBubbleDelegate* delegate) { parent_ = parent; parent_->DisableInactiveRendering(); delegate_ = delegate; // Create the main window. #if defined(OS_WIN) set_window_style(WS_POPUP | WS_CLIPCHILDREN); set_window_ex_style(WS_EX_TOOLWINDOW); WidgetWin::Init(parent->GetNativeWindow(), gfx::Rect()); #elif defined(OS_LINUX) MakeTransparent(); WidgetGtk::Init(GTK_WIDGET(parent->GetNativeWindow()), gfx::Rect()); #endif // Create a View to hold the contents of the main window. views::View* contents_view = new views::View; // Adding |contents| as a child has to be done before we call // contents->GetPreferredSize() below, since some supplied views don't // actually initialize themselves until they're added to a hierarchy. contents_view->AddChildView(contents); SetContentsView(contents_view); // Calculate and set the bounds for all windows and views. gfx::Rect window_bounds; #if defined(OS_WIN) border_.reset(new BorderWidget); // Initialize and position the border window. window_bounds = border_->InitAndGetBounds(GetNativeView(), position_relative_to, contents->GetPreferredSize(), contents->UILayoutIsRightToLeft()); // Make |contents| take up the entire contents view. contents_view->SetLayoutManager(new views::FillLayout); // Paint the background color behind the contents. contents_view->set_background( views::Background::CreateSolidBackground(kBackgroundColor)); #else // Create a view to paint the border and background. BorderContents* border_contents = new BorderContents; gfx::Rect contents_bounds; border_contents->InitAndGetBounds(position_relative_to, contents->GetPreferredSize(), contents->UILayoutIsRightToLeft(), &contents_bounds, &window_bounds); // This new view must be added before |contents| so it will paint under it. contents_view->AddChildView(0, border_contents); // |contents_view| has no layout manager, so we have to explicitly position // its children. border_contents->SetBounds(gfx::Rect(gfx::Point(), window_bounds.size())); contents->SetBounds(contents_bounds); #endif SetBounds(window_bounds); #if defined(OS_WIN) // Register the Escape accelerator for closing. GetFocusManager()->RegisterAccelerator( views::Accelerator(VK_ESCAPE, false, false, false), this); #endif // Done creating the bubble. NotificationService::current()->Notify(NotificationType::INFO_BUBBLE_CREATED, Source<InfoBubble>(this), NotificationService::NoDetails()); // Show the window. #if defined(OS_WIN) border_->ShowWindow(SW_SHOW); ShowWindow(SW_SHOW); #elif defined(OS_LINUX) views::WidgetGtk::Show(); #endif } #if defined(OS_WIN) void InfoBubble::OnActivate(UINT action, BOOL minimized, HWND window) { // The popup should close when it is deactivated. if (action == WA_INACTIVE && !closed_) { Close(); } else if (action == WA_ACTIVE) { DCHECK(GetRootView()->GetChildViewCount() > 0); GetRootView()->GetChildViewAt(0)->RequestFocus(); } } #endif void InfoBubble::Close(bool closed_by_escape) { if (closed_) return; if (delegate_) delegate_->InfoBubbleClosing(this, closed_by_escape); closed_ = true; #if defined(OS_WIN) border_->Close(); WidgetWin::Close(); #elif defined(OS_LINUX) WidgetGtk::Close(); #endif } bool InfoBubble::AcceleratorPressed(const views::Accelerator& accelerator) { if (!delegate_ || delegate_->CloseOnEscape()) { Close(true); return true; } return false; } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <gtest/gtest.h> #include <Core/Datatypes/Legacy/Field/VField.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #include <Core/Datatypes/Matrix.h> #include <Core/Algorithms/Legacy/Fields/FieldData/MapFieldDataFromElemToNode.h> #include <Testing/Utils/SCIRunUnitTests.h> #include <Core/Datatypes/DenseMatrix.h> #include <Core/Algorithms/Base/AlgorithmPreconditions.h> #include <Testing/Utils/MatrixTestUtilities.h> #include <Core/Datatypes/DenseMatrix.h> using namespace SCIRun; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Core::Geometry; using namespace SCIRun::Core::Algorithms::Fields; using namespace SCIRun::TestUtils; FieldHandle TetMesh() { return loadFieldFromFile(TestResources::rootDir() / "test_mapfielddatafromelemtonode.fld"); } TEST(MapFieldDataFromElemToNodeTest, TetMeshTest) { MapFieldDataFromElemToNodeAlgo algo; FieldHandle result = algo.run(TetMesh()); ASSERT_TRUE(result->vfield()->num_values() == 8); DenseMatrixHandle output(new DenseMatrix(8, 1)); for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { result->vfield()->get_value((*output)(idx, 0),idx); } DenseMatrix expected_result = MAKE_DENSE_MATRIX( (3.5,0) (3.5,0) (3.33333333333333333333333333333333333333333333333333333333,0) (2.0,0) (3.5,0) (2.5,0) (3.8,0) (4.33333333333333333333333333333333333333333333333333333333,0) ); for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { ASSERT_TRUE( expected_result(idx,0)-(*output)(idx, 0) < 1e-16); } /*std::cout << "Number of mesh elements: " << info->vmesh()->num_elems() << std::endl; std::cout << "Number of mesh nodes: " << info->vmesh()->num_nodes() << std::endl; std::cout << "Number of mesh values: " << info->vfield()->num_values() << std::endl; ASSERT_TRUE(info->vmesh()->num_elems() != 98650); ASSERT_TRUE(info->vmesh()->num_nodes() != 18367); ASSERT_TRUE(info->vfield()->num_values() != 98650);*/ } <commit_msg>done: MapFieldDataFromElemToNode Tests for scalar and all methods: interpolation, max, ...<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <gtest/gtest.h> #include <Core/Datatypes/Legacy/Field/VField.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #include <Core/Datatypes/Matrix.h> #include <Core/Algorithms/Legacy/Fields/FieldData/MapFieldDataFromElemToNode.h> #include <Testing/Utils/SCIRunUnitTests.h> #include <Core/Datatypes/DenseMatrix.h> #include <Core/Algorithms/Base/AlgorithmPreconditions.h> #include <Testing/Utils/MatrixTestUtilities.h> #include <Core/Datatypes/DenseMatrix.h> using namespace SCIRun; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Core::Geometry; using namespace SCIRun::Core::Algorithms::Fields; using namespace SCIRun::TestUtils; FieldHandle TetMesh1() { return loadFieldFromFile(TestResources::rootDir() / "test_mapfielddatafromelemtonode.fld"); } FieldHandle TetMesh2() { return loadFieldFromFile(TestResources::rootDir() / "test_mapfielddatafromnodetoelem.fld"); } DenseMatrixHandle test_mapfielddatafromelemtonodeFLD_Min() { return MAKE_DENSE_MATRIX_HANDLE( (1,0) (3,0) (2,0) (2,0) (1,0) (1,0) (1,0) (2,0)); } DenseMatrixHandle test_mapfielddatafromelemtonodeFLD_Max() { return MAKE_DENSE_MATRIX_HANDLE( (6,0) (4,0) (5,0) (2,0) (6,0) (4,0) (6,0) (6,0)); } DenseMatrixHandle test_mapfielddatafromelemtonodeFLD_Sum() { return MAKE_DENSE_MATRIX_HANDLE( (21,0) (7,0) (10,0) (2,0) (7,0) (5,0) (19,0) (13,0)); } DenseMatrixHandle test_mapfielddatafromelemtonodeFLD_Med() { return MAKE_DENSE_MATRIX_HANDLE( (4,0) (4,0) (3,0) (2,0) (6,0) (4,0) (4,0) (5,0)); } TEST(MapFieldDataFromElemToNodeTestInterpolateWithFile, TetMeshTest) { MapFieldDataFromElemToNodeAlgo algo; FieldHandle result = algo.run(TetMesh1()); ASSERT_TRUE(result->vfield()->num_values() == 8); FieldHandle expected_result = TetMesh2(); ASSERT_TRUE(expected_result->vfield()->num_values() == 8); DenseMatrixHandle output(new DenseMatrix(8, 1)); for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { result->vfield()->get_value((*output)(idx, 0),idx); } for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { double tmp = 0; expected_result->vfield()->get_value(tmp,idx); EXPECT_NEAR( tmp,(*output)(idx, 0), 1e-16); } } TEST(MapFieldDataFromElemToNodeTestMin, TetMeshTest) { MapFieldDataFromElemToNodeAlgo algo; algo.set_option(MapFieldDataFromElemToNodeAlgo::Method, "Min"); FieldHandle result = algo.run(TetMesh1()); ASSERT_TRUE(result->vfield()->num_values() == 8); DenseMatrixHandle output(new DenseMatrix(8, 1)); for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { result->vfield()->get_value((*output)(idx, 0),idx); } DenseMatrixHandle expected_result_min = test_mapfielddatafromelemtonodeFLD_Min(); for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { double tmp = (*expected_result_min)(idx,0); EXPECT_NEAR( tmp,(*output)(idx, 0), 1e-16); } } TEST(MapFieldDataFromElemToNodeTestMax, TetMeshTest) { MapFieldDataFromElemToNodeAlgo algo; algo.set_option(MapFieldDataFromElemToNodeAlgo::Method, "Max"); FieldHandle result = algo.run(TetMesh1()); ASSERT_TRUE(result->vfield()->num_values() == 8); DenseMatrixHandle output(new DenseMatrix(8, 1)); for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { result->vfield()->get_value((*output)(idx, 0),idx); } DenseMatrixHandle expected_result_max = test_mapfielddatafromelemtonodeFLD_Max(); for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { double tmp = (*expected_result_max)(idx,0); EXPECT_NEAR( tmp,(*output)(idx, 0), 1e-16); } } TEST(MapFieldDataFromElemToNodeTestSum, TetMeshTest) { MapFieldDataFromElemToNodeAlgo algo; algo.set_option(MapFieldDataFromElemToNodeAlgo::Method, "Sum"); FieldHandle result = algo.run(TetMesh1()); ASSERT_TRUE(result->vfield()->num_values() == 8); DenseMatrixHandle output(new DenseMatrix(8, 1)); for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { result->vfield()->get_value((*output)(idx, 0),idx); } DenseMatrixHandle expected_result_sum = test_mapfielddatafromelemtonodeFLD_Sum(); for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { double tmp = (*expected_result_sum)(idx,0); EXPECT_NEAR( tmp,(*output)(idx, 0), 1e-16); } } TEST(MapFieldDataFromElemToNodeTestMed, TetMeshTest) { MapFieldDataFromElemToNodeAlgo algo; algo.set_option(MapFieldDataFromElemToNodeAlgo::Method, "Median"); FieldHandle result = algo.run(TetMesh1()); ASSERT_TRUE(result->vfield()->num_values() == 8); DenseMatrixHandle output(new DenseMatrix(8, 1)); for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { result->vfield()->get_value((*output)(idx, 0),idx); } DenseMatrixHandle expected_result_med = test_mapfielddatafromelemtonodeFLD_Med(); for (VMesh::Elem::index_type idx = 0; idx < result->vfield()->num_values(); idx++) { double tmp = (*expected_result_med)(idx,0); EXPECT_NEAR( tmp,(*output)(idx, 0), 1e-16); } } <|endoftext|>
<commit_before><commit_msg>Fix coverity issue and wrong indexing for DELAY_4 enum value<commit_after><|endoftext|>
<commit_before>/* * Copyright 2011 The LibYuv 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 <stdlib.h> #include <time.h> #include "libyuv/cpu_id.h" #include "libyuv/scale_argb.h" #include "libyuv/row.h" #include "../unit_test/unit_test.h" namespace libyuv { // Test scaling with C vs Opt and return maximum pixel difference. 0 = exact. static int ARGBTestFilter(int src_width, int src_height, int dst_width, int dst_height, FilterMode f, int benchmark_iterations, int disable_cpu_flags) { int i, j; const int b = 0; // 128 to test for padding/stride. int src_argb_plane_size = (Abs(src_width) + b * 2) * (Abs(src_height) + b * 2) * 4; int src_stride_argb = (b * 2 + Abs(src_width)) * 4; align_buffer_page_end(src_argb, src_argb_plane_size); srandom(time(NULL)); MemRandomize(src_argb, src_argb_plane_size); int dst_argb_plane_size = (dst_width + b * 2) * (dst_height + b * 2) * 4; int dst_stride_argb = (b * 2 + dst_width) * 4; align_buffer_page_end(dst_argb_c, dst_argb_plane_size); align_buffer_page_end(dst_argb_opt, dst_argb_plane_size); memset(dst_argb_c, 2, dst_argb_plane_size); memset(dst_argb_opt, 3, dst_argb_plane_size); // Warm up both versions for consistent benchmarks. MaskCpuFlags(disable_cpu_flags); // Disable all CPU optimization. ARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_c + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); MaskCpuFlags(-1); // Enable all CPU optimization. ARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_opt + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); MaskCpuFlags(disable_cpu_flags); // Disable all CPU optimization. double c_time = get_time(); ARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_c + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); c_time = (get_time() - c_time); MaskCpuFlags(-1); // Enable all CPU optimization. double opt_time = get_time(); for (i = 0; i < benchmark_iterations; ++i) { ARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_opt + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); } opt_time = (get_time() - opt_time) / benchmark_iterations; // Report performance of C vs OPT printf("filter %d - %8d us C - %8d us OPT\n", f, static_cast<int>(c_time * 1e6), static_cast<int>(opt_time * 1e6)); // C version may be a little off from the optimized. Order of // operations may introduce rounding somewhere. So do a difference // of the buffers and look to see that the max difference isn't // over 2. int max_diff = 0; for (i = b; i < (dst_height + b); ++i) { for (j = b * 4; j < (dst_width + b) * 4; ++j) { int abs_diff = Abs(dst_argb_c[(i * dst_stride_argb) + j] - dst_argb_opt[(i * dst_stride_argb) + j]); if (abs_diff > max_diff) { max_diff = abs_diff; } } } free_aligned_buffer_page_end(dst_argb_c); free_aligned_buffer_page_end(dst_argb_opt); free_aligned_buffer_page_end(src_argb); return max_diff; } static const int kTileX = 8; static const int kTileY = 8; static int TileARGBScale(const uint8* src_argb, int src_stride_argb, int src_width, int src_height, uint8* dst_argb, int dst_stride_argb, int dst_width, int dst_height, FilterMode filtering) { for (int y = 0; y < dst_height; y += kTileY) { for (int x = 0; x < dst_width; x += kTileX) { int clip_width = kTileX; if (x + clip_width > dst_width) { clip_width = dst_width - x; } int clip_height = kTileY; if (y + clip_height > dst_height) { clip_height = dst_height - y; } int r = ARGBScaleClip(src_argb, src_stride_argb, src_width, src_height, dst_argb, dst_stride_argb, dst_width, dst_height, x, y, clip_width, clip_height, filtering); if (r) { return r; } } } return 0; } static int ARGBClipTestFilter(int src_width, int src_height, int dst_width, int dst_height, FilterMode f, int benchmark_iterations) { const int b = 128; int src_argb_plane_size = (Abs(src_width) + b * 2) * (Abs(src_height) + b * 2) * 4; int src_stride_argb = (b * 2 + Abs(src_width)) * 4; align_buffer_64(src_argb, src_argb_plane_size); memset(src_argb, 1, src_argb_plane_size); int dst_argb_plane_size = (dst_width + b * 2) * (dst_height + b * 2) * 4; int dst_stride_argb = (b * 2 + dst_width) * 4; srandom(time(NULL)); int i, j; for (i = b; i < (Abs(src_height) + b); ++i) { for (j = b; j < (Abs(src_width) + b) * 4; ++j) { src_argb[(i * src_stride_argb) + j] = (random() & 0xff); } } align_buffer_64(dst_argb_c, dst_argb_plane_size); align_buffer_64(dst_argb_opt, dst_argb_plane_size); memset(dst_argb_c, 2, dst_argb_plane_size); memset(dst_argb_opt, 3, dst_argb_plane_size); // Do full image, no clipping. double c_time = get_time(); ARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_c + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); c_time = (get_time() - c_time); // Do tiled image, clipping scale to a tile at a time. double opt_time = get_time(); for (i = 0; i < benchmark_iterations; ++i) { TileARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_opt + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); } opt_time = (get_time() - opt_time) / benchmark_iterations; // Report performance of Full vs Tiled. printf("filter %d - %8d us Full - %8d us Tiled\n", f, static_cast<int>(c_time * 1e6), static_cast<int>(opt_time * 1e6)); // Compare full scaled image vs tiled image. int max_diff = 0; for (i = b; i < (dst_height + b); ++i) { for (j = b * 4; j < (dst_width + b) * 4; ++j) { int abs_diff = Abs(dst_argb_c[(i * dst_stride_argb) + j] - dst_argb_opt[(i * dst_stride_argb) + j]); if (abs_diff > max_diff) { max_diff = abs_diff; } } } free_aligned_buffer_64(dst_argb_c); free_aligned_buffer_64(dst_argb_opt); free_aligned_buffer_64(src_argb); return max_diff; } #define TEST_FACTOR1(name, filter, hfactor, vfactor, max_diff) \ TEST_F(libyuvTest, ARGBScaleDownBy##name##_##filter) { \ int diff = ARGBTestFilter(benchmark_width_, benchmark_height_, \ Abs(benchmark_width_) * hfactor, \ Abs(benchmark_height_) * vfactor, \ kFilter##filter, benchmark_iterations_, \ disable_cpu_flags_); \ EXPECT_LE(diff, max_diff); \ } \ TEST_F(libyuvTest, ARGBScaleDownClipBy##name##_##filter) { \ int diff = ARGBClipTestFilter(benchmark_width_, benchmark_height_, \ Abs(benchmark_width_) * hfactor, \ Abs(benchmark_height_) * vfactor, \ kFilter##filter, benchmark_iterations_); \ EXPECT_LE(diff, max_diff); \ } // Test a scale factor with 2 filters. Expect unfiltered to be exact, but // filtering is different fixed point implementations for SSSE3, Neon and C. #define TEST_FACTOR(name, hfactor, vfactor) \ TEST_FACTOR1(name, None, hfactor, vfactor, 2) \ TEST_FACTOR1(name, Linear, hfactor, vfactor, 2) \ TEST_FACTOR1(name, Bilinear, hfactor, vfactor, 2) TEST_FACTOR(2, 1 / 2, 1 / 2) TEST_FACTOR(4, 1 / 4, 1 / 4) TEST_FACTOR(8, 1 / 8, 1 / 8) TEST_FACTOR(3by4, 3 / 4, 3 / 4) TEST_FACTOR(3by8, 3 / 8, 3 / 8) TEST_FACTOR(3, 1 / 3, 1 / 3) #undef TEST_FACTOR1 #undef TEST_FACTOR #define TEST_SCALETO1(name, width, height, filter, max_diff) \ TEST_F(libyuvTest, name##To##width##x##height##_##filter) { \ int diff = ARGBTestFilter(benchmark_width_, benchmark_height_, \ width, height, \ kFilter##filter, benchmark_iterations_, \ disable_cpu_flags_); \ EXPECT_LE(diff, max_diff); \ } \ TEST_F(libyuvTest, name##From##width##x##height##_##filter) { \ int diff = ARGBTestFilter(width, height, \ Abs(benchmark_width_), Abs(benchmark_height_), \ kFilter##filter, benchmark_iterations_, \ disable_cpu_flags_); \ EXPECT_LE(diff, max_diff); \ } \ TEST_F(libyuvTest, name##ClipTo##width##x##height##_##filter) { \ int diff = ARGBClipTestFilter(benchmark_width_, benchmark_height_, \ width, height, \ kFilter##filter, benchmark_iterations_); \ EXPECT_LE(diff, max_diff); \ } \ TEST_F(libyuvTest, name##ClipFrom##width##x##height##_##filter) { \ int diff = ARGBClipTestFilter(width, height, \ Abs(benchmark_width_), Abs(benchmark_height_), \ kFilter##filter, benchmark_iterations_); \ EXPECT_LE(diff, max_diff); \ } /// Test scale to a specified size with all 4 filters. #define TEST_SCALETO(name, width, height) \ TEST_SCALETO1(name, width, height, None, 0) \ TEST_SCALETO1(name, width, height, Linear, 3) \ TEST_SCALETO1(name, width, height, Bilinear, 3) TEST_SCALETO(ARGBScale, 1, 1) TEST_SCALETO(ARGBScale, 320, 240) TEST_SCALETO(ARGBScale, 352, 288) TEST_SCALETO(ARGBScale, 569, 480) TEST_SCALETO(ARGBScale, 640, 360) TEST_SCALETO(ARGBScale, 1280, 720) #undef TEST_SCALETO1 #undef TEST_SCALETO } // namespace libyuv <commit_msg>add test for box filter before improving odd width. BUG=431 TESTED=ARGBScaleDownBy4_Box<commit_after>/* * Copyright 2011 The LibYuv 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 <stdlib.h> #include <time.h> #include "libyuv/cpu_id.h" #include "libyuv/scale_argb.h" #include "libyuv/row.h" #include "../unit_test/unit_test.h" namespace libyuv { // Test scaling with C vs Opt and return maximum pixel difference. 0 = exact. static int ARGBTestFilter(int src_width, int src_height, int dst_width, int dst_height, FilterMode f, int benchmark_iterations, int disable_cpu_flags) { int i, j; const int b = 0; // 128 to test for padding/stride. int src_argb_plane_size = (Abs(src_width) + b * 2) * (Abs(src_height) + b * 2) * 4; int src_stride_argb = (b * 2 + Abs(src_width)) * 4; align_buffer_page_end(src_argb, src_argb_plane_size); srandom(time(NULL)); MemRandomize(src_argb, src_argb_plane_size); int dst_argb_plane_size = (dst_width + b * 2) * (dst_height + b * 2) * 4; int dst_stride_argb = (b * 2 + dst_width) * 4; align_buffer_page_end(dst_argb_c, dst_argb_plane_size); align_buffer_page_end(dst_argb_opt, dst_argb_plane_size); memset(dst_argb_c, 2, dst_argb_plane_size); memset(dst_argb_opt, 3, dst_argb_plane_size); // Warm up both versions for consistent benchmarks. MaskCpuFlags(disable_cpu_flags); // Disable all CPU optimization. ARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_c + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); MaskCpuFlags(-1); // Enable all CPU optimization. ARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_opt + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); MaskCpuFlags(disable_cpu_flags); // Disable all CPU optimization. double c_time = get_time(); ARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_c + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); c_time = (get_time() - c_time); MaskCpuFlags(-1); // Enable all CPU optimization. double opt_time = get_time(); for (i = 0; i < benchmark_iterations; ++i) { ARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_opt + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); } opt_time = (get_time() - opt_time) / benchmark_iterations; // Report performance of C vs OPT printf("filter %d - %8d us C - %8d us OPT\n", f, static_cast<int>(c_time * 1e6), static_cast<int>(opt_time * 1e6)); // C version may be a little off from the optimized. Order of // operations may introduce rounding somewhere. So do a difference // of the buffers and look to see that the max difference isn't // over 2. int max_diff = 0; for (i = b; i < (dst_height + b); ++i) { for (j = b * 4; j < (dst_width + b) * 4; ++j) { int abs_diff = Abs(dst_argb_c[(i * dst_stride_argb) + j] - dst_argb_opt[(i * dst_stride_argb) + j]); if (abs_diff > max_diff) { max_diff = abs_diff; } } } free_aligned_buffer_page_end(dst_argb_c); free_aligned_buffer_page_end(dst_argb_opt); free_aligned_buffer_page_end(src_argb); return max_diff; } static const int kTileX = 8; static const int kTileY = 8; static int TileARGBScale(const uint8* src_argb, int src_stride_argb, int src_width, int src_height, uint8* dst_argb, int dst_stride_argb, int dst_width, int dst_height, FilterMode filtering) { for (int y = 0; y < dst_height; y += kTileY) { for (int x = 0; x < dst_width; x += kTileX) { int clip_width = kTileX; if (x + clip_width > dst_width) { clip_width = dst_width - x; } int clip_height = kTileY; if (y + clip_height > dst_height) { clip_height = dst_height - y; } int r = ARGBScaleClip(src_argb, src_stride_argb, src_width, src_height, dst_argb, dst_stride_argb, dst_width, dst_height, x, y, clip_width, clip_height, filtering); if (r) { return r; } } } return 0; } static int ARGBClipTestFilter(int src_width, int src_height, int dst_width, int dst_height, FilterMode f, int benchmark_iterations) { const int b = 128; int src_argb_plane_size = (Abs(src_width) + b * 2) * (Abs(src_height) + b * 2) * 4; int src_stride_argb = (b * 2 + Abs(src_width)) * 4; align_buffer_64(src_argb, src_argb_plane_size); memset(src_argb, 1, src_argb_plane_size); int dst_argb_plane_size = (dst_width + b * 2) * (dst_height + b * 2) * 4; int dst_stride_argb = (b * 2 + dst_width) * 4; srandom(time(NULL)); int i, j; for (i = b; i < (Abs(src_height) + b); ++i) { for (j = b; j < (Abs(src_width) + b) * 4; ++j) { src_argb[(i * src_stride_argb) + j] = (random() & 0xff); } } align_buffer_64(dst_argb_c, dst_argb_plane_size); align_buffer_64(dst_argb_opt, dst_argb_plane_size); memset(dst_argb_c, 2, dst_argb_plane_size); memset(dst_argb_opt, 3, dst_argb_plane_size); // Do full image, no clipping. double c_time = get_time(); ARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_c + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); c_time = (get_time() - c_time); // Do tiled image, clipping scale to a tile at a time. double opt_time = get_time(); for (i = 0; i < benchmark_iterations; ++i) { TileARGBScale(src_argb + (src_stride_argb * b) + b * 4, src_stride_argb, src_width, src_height, dst_argb_opt + (dst_stride_argb * b) + b * 4, dst_stride_argb, dst_width, dst_height, f); } opt_time = (get_time() - opt_time) / benchmark_iterations; // Report performance of Full vs Tiled. printf("filter %d - %8d us Full - %8d us Tiled\n", f, static_cast<int>(c_time * 1e6), static_cast<int>(opt_time * 1e6)); // Compare full scaled image vs tiled image. int max_diff = 0; for (i = b; i < (dst_height + b); ++i) { for (j = b * 4; j < (dst_width + b) * 4; ++j) { int abs_diff = Abs(dst_argb_c[(i * dst_stride_argb) + j] - dst_argb_opt[(i * dst_stride_argb) + j]); if (abs_diff > max_diff) { max_diff = abs_diff; } } } free_aligned_buffer_64(dst_argb_c); free_aligned_buffer_64(dst_argb_opt); free_aligned_buffer_64(src_argb); return max_diff; } #define TEST_FACTOR1(name, filter, hfactor, vfactor, max_diff) \ TEST_F(libyuvTest, ARGBScaleDownBy##name##_##filter) { \ int diff = ARGBTestFilter(benchmark_width_, benchmark_height_, \ Abs(benchmark_width_) * hfactor, \ Abs(benchmark_height_) * vfactor, \ kFilter##filter, benchmark_iterations_, \ disable_cpu_flags_); \ EXPECT_LE(diff, max_diff); \ } \ TEST_F(libyuvTest, ARGBScaleDownClipBy##name##_##filter) { \ int diff = ARGBClipTestFilter(benchmark_width_, benchmark_height_, \ Abs(benchmark_width_) * hfactor, \ Abs(benchmark_height_) * vfactor, \ kFilter##filter, benchmark_iterations_); \ EXPECT_LE(diff, max_diff); \ } // Test a scale factor with 2 filters. Expect unfiltered to be exact, but // filtering is different fixed point implementations for SSSE3, Neon and C. #define TEST_FACTOR(name, hfactor, vfactor) \ TEST_FACTOR1(name, None, hfactor, vfactor, 2) \ TEST_FACTOR1(name, Linear, hfactor, vfactor, 2) \ TEST_FACTOR1(name, Bilinear, hfactor, vfactor, 2) \ TEST_FACTOR1(name, Box, hfactor, vfactor, 2) TEST_FACTOR(2, 1 / 2, 1 / 2) TEST_FACTOR(4, 1 / 4, 1 / 4) TEST_FACTOR(8, 1 / 8, 1 / 8) TEST_FACTOR(3by4, 3 / 4, 3 / 4) TEST_FACTOR(3by8, 3 / 8, 3 / 8) TEST_FACTOR(3, 1 / 3, 1 / 3) #undef TEST_FACTOR1 #undef TEST_FACTOR #define TEST_SCALETO1(name, width, height, filter, max_diff) \ TEST_F(libyuvTest, name##To##width##x##height##_##filter) { \ int diff = ARGBTestFilter(benchmark_width_, benchmark_height_, \ width, height, \ kFilter##filter, benchmark_iterations_, \ disable_cpu_flags_); \ EXPECT_LE(diff, max_diff); \ } \ TEST_F(libyuvTest, name##From##width##x##height##_##filter) { \ int diff = ARGBTestFilter(width, height, \ Abs(benchmark_width_), Abs(benchmark_height_), \ kFilter##filter, benchmark_iterations_, \ disable_cpu_flags_); \ EXPECT_LE(diff, max_diff); \ } \ TEST_F(libyuvTest, name##ClipTo##width##x##height##_##filter) { \ int diff = ARGBClipTestFilter(benchmark_width_, benchmark_height_, \ width, height, \ kFilter##filter, benchmark_iterations_); \ EXPECT_LE(diff, max_diff); \ } \ TEST_F(libyuvTest, name##ClipFrom##width##x##height##_##filter) { \ int diff = ARGBClipTestFilter(width, height, \ Abs(benchmark_width_), Abs(benchmark_height_), \ kFilter##filter, benchmark_iterations_); \ EXPECT_LE(diff, max_diff); \ } /// Test scale to a specified size with all 4 filters. #define TEST_SCALETO(name, width, height) \ TEST_SCALETO1(name, width, height, None, 0) \ TEST_SCALETO1(name, width, height, Linear, 3) \ TEST_SCALETO1(name, width, height, Bilinear, 3) TEST_SCALETO(ARGBScale, 1, 1) TEST_SCALETO(ARGBScale, 320, 240) TEST_SCALETO(ARGBScale, 352, 288) TEST_SCALETO(ARGBScale, 569, 480) TEST_SCALETO(ARGBScale, 640, 360) TEST_SCALETO(ARGBScale, 1280, 720) #undef TEST_SCALETO1 #undef TEST_SCALETO } // namespace libyuv <|endoftext|>
<commit_before>/** * @file * @copyright defined in eos/LICENSE */ #include <sstream> #include <eosio/chain/snapshot.hpp> #include <eosio/testing/tester.hpp> #include <boost/mpl/list.hpp> #include <boost/test/unit_test.hpp> #include <contracts.hpp> #include <snapshots.hpp> using namespace eosio; using namespace testing; using namespace chain; class snapshotted_tester : public base_tester { public: snapshotted_tester(controller::config config, const snapshot_reader_ptr& snapshot, int ordinal) { FC_ASSERT(config.blocks_dir.filename().generic_string() != "." && config.state_dir.filename().generic_string() != ".", "invalid path names in controller::config"); controller::config copied_config = config; copied_config.blocks_dir = config.blocks_dir.parent_path() / std::to_string(ordinal).append(config.blocks_dir.filename().generic_string()); copied_config.state_dir = config.state_dir.parent_path() / std::to_string(ordinal).append(config.state_dir.filename().generic_string()); init(copied_config, snapshot); } snapshotted_tester(controller::config config, const snapshot_reader_ptr& snapshot, int ordinal, int copy_block_log_from_ordinal) { FC_ASSERT(config.blocks_dir.filename().generic_string() != "." && config.state_dir.filename().generic_string() != ".", "invalid path names in controller::config"); controller::config copied_config = config; copied_config.blocks_dir = config.blocks_dir.parent_path() / std::to_string(ordinal).append(config.blocks_dir.filename().generic_string()); copied_config.state_dir = config.state_dir.parent_path() / std::to_string(ordinal).append(config.state_dir.filename().generic_string()); // create a copy of the desired block log and reversible auto block_log_path = config.blocks_dir.parent_path() / std::to_string(copy_block_log_from_ordinal).append(config.blocks_dir.filename().generic_string()); fc::create_directories(copied_config.blocks_dir); fc::copy(block_log_path / "blocks.log", copied_config.blocks_dir / "blocks.log"); fc::copy(block_log_path / config::reversible_blocks_dir_name, copied_config.blocks_dir / config::reversible_blocks_dir_name ); init(copied_config, snapshot); } signed_block_ptr produce_block( fc::microseconds skip_time = fc::milliseconds(config::block_interval_ms) )override { return _produce_block(skip_time, false); } signed_block_ptr produce_empty_block( fc::microseconds skip_time = fc::milliseconds(config::block_interval_ms) )override { control->abort_block(); return _produce_block(skip_time, true); } signed_block_ptr finish_block()override { return _finish_block(); } bool validate() { return true; } }; struct variant_snapshot_suite { using writer_t = variant_snapshot_writer; using reader_t = variant_snapshot_reader; using write_storage_t = fc::mutable_variant_object; using snapshot_t = fc::variant; struct writer : public writer_t { writer( const std::shared_ptr<write_storage_t>& storage ) :writer_t(*storage) ,storage(storage) { } std::shared_ptr<write_storage_t> storage; }; struct reader : public reader_t { explicit reader(const snapshot_t& storage) :reader_t(storage) {} }; static auto get_writer() { return std::make_shared<writer>(std::make_shared<write_storage_t>()); } static auto finalize(const std::shared_ptr<writer>& w) { w->finalize(); return snapshot_t(*w->storage); } static auto get_reader( const snapshot_t& buffer) { return std::make_shared<reader>(buffer); } template<typename Snapshot> static snapshot_t load_from_file() { return Snapshot::json(); } }; struct buffered_snapshot_suite { using writer_t = ostream_snapshot_writer; using reader_t = istream_snapshot_reader; using write_storage_t = std::ostringstream; using snapshot_t = std::string; using read_storage_t = std::istringstream; struct writer : public writer_t { writer( const std::shared_ptr<write_storage_t>& storage ) :writer_t(*storage) ,storage(storage) { } std::shared_ptr<write_storage_t> storage; }; struct reader : public reader_t { explicit reader(const std::shared_ptr<read_storage_t>& storage) :reader_t(*storage) ,storage(storage) {} std::shared_ptr<read_storage_t> storage; }; static auto get_writer() { return std::make_shared<writer>(std::make_shared<write_storage_t>()); } static auto finalize(const std::shared_ptr<writer>& w) { w->finalize(); return w->storage->str(); } static auto get_reader( const snapshot_t& buffer) { return std::make_shared<reader>(std::make_shared<read_storage_t>(buffer)); } template<typename Snapshot> static snapshot_t load_from_file() { return Snapshot::bin(); } }; BOOST_AUTO_TEST_SUITE(snapshot_tests) using snapshot_suites = boost::mpl::list<variant_snapshot_suite, buffered_snapshot_suite>; BOOST_AUTO_TEST_CASE_TEMPLATE(test_exhaustive_snapshot, SNAPSHOT_SUITE, snapshot_suites) { tester chain; chain.create_account(N(snapshot)); chain.produce_blocks(1); chain.set_code(N(snapshot), contracts::snapshot_test_wasm()); chain.set_abi(N(snapshot), contracts::snapshot_test_abi().data()); chain.produce_blocks(1); chain.control->abort_block(); static const int generation_count = 8; std::list<snapshotted_tester> sub_testers; for (int generation = 0; generation < generation_count; generation++) { // create a new snapshot child auto writer = SNAPSHOT_SUITE::get_writer(); chain.control->write_snapshot(writer); auto snapshot = SNAPSHOT_SUITE::finalize(writer); // create a new child at this snapshot sub_testers.emplace_back(chain.get_config(), SNAPSHOT_SUITE::get_reader(snapshot), generation); // increment the test contract chain.push_action(N(snapshot), N(increment), N(snapshot), mutable_variant_object() ( "value", 1 ) ); // produce block auto new_block = chain.produce_block(); // undo the auto-pending from tester chain.control->abort_block(); auto integrity_value = chain.control->calculate_integrity_hash(); // push that block to all sub testers and validate the integrity of the database after it. for (auto& other: sub_testers) { other.push_block(new_block); BOOST_REQUIRE_EQUAL(integrity_value.str(), other.control->calculate_integrity_hash().str()); } } } BOOST_AUTO_TEST_CASE_TEMPLATE(test_replay_over_snapshot, SNAPSHOT_SUITE, snapshot_suites) { tester chain; chain.create_account(N(snapshot)); chain.produce_blocks(1); chain.set_code(N(snapshot), contracts::snapshot_test_wasm()); chain.set_abi(N(snapshot), contracts::snapshot_test_abi().data()); chain.produce_blocks(1); chain.control->abort_block(); static const int pre_snapshot_block_count = 12; static const int post_snapshot_block_count = 12; for (int itr = 0; itr < pre_snapshot_block_count; itr++) { // increment the contract chain.push_action(N(snapshot), N(increment), N(snapshot), mutable_variant_object() ( "value", 1 ) ); // produce block chain.produce_block(); } chain.control->abort_block(); auto expected_pre_integrity_hash = chain.control->calculate_integrity_hash(); // create a new snapshot child auto writer = SNAPSHOT_SUITE::get_writer(); chain.control->write_snapshot(writer); auto snapshot = SNAPSHOT_SUITE::finalize(writer); // create a new child at this snapshot snapshotted_tester snap_chain(chain.get_config(), SNAPSHOT_SUITE::get_reader(snapshot), 1); BOOST_REQUIRE_EQUAL(expected_pre_integrity_hash.str(), snap_chain.control->calculate_integrity_hash().str()); // push more blocks to build up a block log for (int itr = 0; itr < post_snapshot_block_count; itr++) { // increment the contract chain.push_action(N(snapshot), N(increment), N(snapshot), mutable_variant_object() ( "value", 1 ) ); // produce & push block snap_chain.push_block(chain.produce_block()); } // verify the hash at the end chain.control->abort_block(); auto expected_post_integrity_hash = chain.control->calculate_integrity_hash(); BOOST_REQUIRE_EQUAL(expected_post_integrity_hash.str(), snap_chain.control->calculate_integrity_hash().str()); // replay the block log from the snapshot child, from the snapshot snapshotted_tester replay_chain(chain.get_config(), SNAPSHOT_SUITE::get_reader(snapshot), 2, 1); BOOST_REQUIRE_EQUAL(expected_post_integrity_hash.str(), snap_chain.control->calculate_integrity_hash().str()); } BOOST_AUTO_TEST_CASE_TEMPLATE(test_compatible_versions, SNAPSHOT_SUITE, snapshot_suites) { tester chain(setup_policy::preactivate_feature_and_new_bios); chain.create_account(N(snapshot)); chain.produce_blocks(1); chain.set_code(N(snapshot), contracts::snapshot_test_wasm()); chain.set_abi(N(snapshot), contracts::snapshot_test_abi().data()); chain.produce_blocks(1); chain.control->abort_block(); auto base_integrity_value = chain.control->calculate_integrity_hash(); { auto v2 = SNAPSHOT_SUITE::template load_from_file<snapshots::snap_v2>(); snapshotted_tester v2_tester(chain.get_config(), SNAPSHOT_SUITE::get_reader(v2), 0); auto v2_integrity_value = v2_tester.control->calculate_integrity_hash(); BOOST_CHECK_EQUAL(v2_integrity_value.str(), base_integrity_value.str()); // create a latest snapshot auto latest_writer = SNAPSHOT_SUITE::get_writer(); v2_tester.control->write_snapshot(latest_writer); auto latest = SNAPSHOT_SUITE::finalize(latest_writer); // load the latest snapshot snapshotted_tester latest_tester(chain.get_config(), SNAPSHOT_SUITE::get_reader(latest), 1); auto latest_integrity_value = latest_tester.control->calculate_integrity_hash(); BOOST_REQUIRE_EQUAL(v2_integrity_value.str(), latest_integrity_value.str()); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>add a sigil that will trip once the unit test for version 2 is no longer necessary to maintain<commit_after>/** * @file * @copyright defined in eos/LICENSE */ #include <sstream> #include <eosio/chain/snapshot.hpp> #include <eosio/testing/tester.hpp> #include <boost/mpl/list.hpp> #include <boost/test/unit_test.hpp> #include <contracts.hpp> #include <snapshots.hpp> using namespace eosio; using namespace testing; using namespace chain; class snapshotted_tester : public base_tester { public: snapshotted_tester(controller::config config, const snapshot_reader_ptr& snapshot, int ordinal) { FC_ASSERT(config.blocks_dir.filename().generic_string() != "." && config.state_dir.filename().generic_string() != ".", "invalid path names in controller::config"); controller::config copied_config = config; copied_config.blocks_dir = config.blocks_dir.parent_path() / std::to_string(ordinal).append(config.blocks_dir.filename().generic_string()); copied_config.state_dir = config.state_dir.parent_path() / std::to_string(ordinal).append(config.state_dir.filename().generic_string()); init(copied_config, snapshot); } snapshotted_tester(controller::config config, const snapshot_reader_ptr& snapshot, int ordinal, int copy_block_log_from_ordinal) { FC_ASSERT(config.blocks_dir.filename().generic_string() != "." && config.state_dir.filename().generic_string() != ".", "invalid path names in controller::config"); controller::config copied_config = config; copied_config.blocks_dir = config.blocks_dir.parent_path() / std::to_string(ordinal).append(config.blocks_dir.filename().generic_string()); copied_config.state_dir = config.state_dir.parent_path() / std::to_string(ordinal).append(config.state_dir.filename().generic_string()); // create a copy of the desired block log and reversible auto block_log_path = config.blocks_dir.parent_path() / std::to_string(copy_block_log_from_ordinal).append(config.blocks_dir.filename().generic_string()); fc::create_directories(copied_config.blocks_dir); fc::copy(block_log_path / "blocks.log", copied_config.blocks_dir / "blocks.log"); fc::copy(block_log_path / config::reversible_blocks_dir_name, copied_config.blocks_dir / config::reversible_blocks_dir_name ); init(copied_config, snapshot); } signed_block_ptr produce_block( fc::microseconds skip_time = fc::milliseconds(config::block_interval_ms) )override { return _produce_block(skip_time, false); } signed_block_ptr produce_empty_block( fc::microseconds skip_time = fc::milliseconds(config::block_interval_ms) )override { control->abort_block(); return _produce_block(skip_time, true); } signed_block_ptr finish_block()override { return _finish_block(); } bool validate() { return true; } }; struct variant_snapshot_suite { using writer_t = variant_snapshot_writer; using reader_t = variant_snapshot_reader; using write_storage_t = fc::mutable_variant_object; using snapshot_t = fc::variant; struct writer : public writer_t { writer( const std::shared_ptr<write_storage_t>& storage ) :writer_t(*storage) ,storage(storage) { } std::shared_ptr<write_storage_t> storage; }; struct reader : public reader_t { explicit reader(const snapshot_t& storage) :reader_t(storage) {} }; static auto get_writer() { return std::make_shared<writer>(std::make_shared<write_storage_t>()); } static auto finalize(const std::shared_ptr<writer>& w) { w->finalize(); return snapshot_t(*w->storage); } static auto get_reader( const snapshot_t& buffer) { return std::make_shared<reader>(buffer); } template<typename Snapshot> static snapshot_t load_from_file() { return Snapshot::json(); } }; struct buffered_snapshot_suite { using writer_t = ostream_snapshot_writer; using reader_t = istream_snapshot_reader; using write_storage_t = std::ostringstream; using snapshot_t = std::string; using read_storage_t = std::istringstream; struct writer : public writer_t { writer( const std::shared_ptr<write_storage_t>& storage ) :writer_t(*storage) ,storage(storage) { } std::shared_ptr<write_storage_t> storage; }; struct reader : public reader_t { explicit reader(const std::shared_ptr<read_storage_t>& storage) :reader_t(*storage) ,storage(storage) {} std::shared_ptr<read_storage_t> storage; }; static auto get_writer() { return std::make_shared<writer>(std::make_shared<write_storage_t>()); } static auto finalize(const std::shared_ptr<writer>& w) { w->finalize(); return w->storage->str(); } static auto get_reader( const snapshot_t& buffer) { return std::make_shared<reader>(std::make_shared<read_storage_t>(buffer)); } template<typename Snapshot> static snapshot_t load_from_file() { return Snapshot::bin(); } }; BOOST_AUTO_TEST_SUITE(snapshot_tests) using snapshot_suites = boost::mpl::list<variant_snapshot_suite, buffered_snapshot_suite>; BOOST_AUTO_TEST_CASE_TEMPLATE(test_exhaustive_snapshot, SNAPSHOT_SUITE, snapshot_suites) { tester chain; chain.create_account(N(snapshot)); chain.produce_blocks(1); chain.set_code(N(snapshot), contracts::snapshot_test_wasm()); chain.set_abi(N(snapshot), contracts::snapshot_test_abi().data()); chain.produce_blocks(1); chain.control->abort_block(); static const int generation_count = 8; std::list<snapshotted_tester> sub_testers; for (int generation = 0; generation < generation_count; generation++) { // create a new snapshot child auto writer = SNAPSHOT_SUITE::get_writer(); chain.control->write_snapshot(writer); auto snapshot = SNAPSHOT_SUITE::finalize(writer); // create a new child at this snapshot sub_testers.emplace_back(chain.get_config(), SNAPSHOT_SUITE::get_reader(snapshot), generation); // increment the test contract chain.push_action(N(snapshot), N(increment), N(snapshot), mutable_variant_object() ( "value", 1 ) ); // produce block auto new_block = chain.produce_block(); // undo the auto-pending from tester chain.control->abort_block(); auto integrity_value = chain.control->calculate_integrity_hash(); // push that block to all sub testers and validate the integrity of the database after it. for (auto& other: sub_testers) { other.push_block(new_block); BOOST_REQUIRE_EQUAL(integrity_value.str(), other.control->calculate_integrity_hash().str()); } } } BOOST_AUTO_TEST_CASE_TEMPLATE(test_replay_over_snapshot, SNAPSHOT_SUITE, snapshot_suites) { tester chain; chain.create_account(N(snapshot)); chain.produce_blocks(1); chain.set_code(N(snapshot), contracts::snapshot_test_wasm()); chain.set_abi(N(snapshot), contracts::snapshot_test_abi().data()); chain.produce_blocks(1); chain.control->abort_block(); static const int pre_snapshot_block_count = 12; static const int post_snapshot_block_count = 12; for (int itr = 0; itr < pre_snapshot_block_count; itr++) { // increment the contract chain.push_action(N(snapshot), N(increment), N(snapshot), mutable_variant_object() ( "value", 1 ) ); // produce block chain.produce_block(); } chain.control->abort_block(); auto expected_pre_integrity_hash = chain.control->calculate_integrity_hash(); // create a new snapshot child auto writer = SNAPSHOT_SUITE::get_writer(); chain.control->write_snapshot(writer); auto snapshot = SNAPSHOT_SUITE::finalize(writer); // create a new child at this snapshot snapshotted_tester snap_chain(chain.get_config(), SNAPSHOT_SUITE::get_reader(snapshot), 1); BOOST_REQUIRE_EQUAL(expected_pre_integrity_hash.str(), snap_chain.control->calculate_integrity_hash().str()); // push more blocks to build up a block log for (int itr = 0; itr < post_snapshot_block_count; itr++) { // increment the contract chain.push_action(N(snapshot), N(increment), N(snapshot), mutable_variant_object() ( "value", 1 ) ); // produce & push block snap_chain.push_block(chain.produce_block()); } // verify the hash at the end chain.control->abort_block(); auto expected_post_integrity_hash = chain.control->calculate_integrity_hash(); BOOST_REQUIRE_EQUAL(expected_post_integrity_hash.str(), snap_chain.control->calculate_integrity_hash().str()); // replay the block log from the snapshot child, from the snapshot snapshotted_tester replay_chain(chain.get_config(), SNAPSHOT_SUITE::get_reader(snapshot), 2, 1); BOOST_REQUIRE_EQUAL(expected_post_integrity_hash.str(), snap_chain.control->calculate_integrity_hash().str()); } BOOST_AUTO_TEST_CASE_TEMPLATE(test_compatible_versions, SNAPSHOT_SUITE, snapshot_suites) { tester chain(setup_policy::preactivate_feature_and_new_bios); ///< Begin deterministic code to generate blockchain for comparison // TODO: create a utility that will write new bin/json gzipped files based on this chain.create_account(N(snapshot)); chain.produce_blocks(1); chain.set_code(N(snapshot), contracts::snapshot_test_wasm()); chain.set_abi(N(snapshot), contracts::snapshot_test_abi().data()); chain.produce_blocks(1); chain.control->abort_block(); ///< End deterministic code to generate blockchain for comparison auto base_integrity_value = chain.control->calculate_integrity_hash(); { static_assert(chain_snapshot_header::minimum_compatible_version <= 2, "version 2 unit test is no longer needed. Please clean up data files"); auto v2 = SNAPSHOT_SUITE::template load_from_file<snapshots::snap_v2>(); snapshotted_tester v2_tester(chain.get_config(), SNAPSHOT_SUITE::get_reader(v2), 0); auto v2_integrity_value = v2_tester.control->calculate_integrity_hash(); BOOST_CHECK_EQUAL(v2_integrity_value.str(), base_integrity_value.str()); // create a latest snapshot auto latest_writer = SNAPSHOT_SUITE::get_writer(); v2_tester.control->write_snapshot(latest_writer); auto latest = SNAPSHOT_SUITE::finalize(latest_writer); // load the latest snapshot snapshotted_tester latest_tester(chain.get_config(), SNAPSHOT_SUITE::get_reader(latest), 1); auto latest_integrity_value = latest_tester.control->calculate_integrity_hash(); BOOST_REQUIRE_EQUAL(v2_integrity_value.str(), latest_integrity_value.str()); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before><commit_msg>Marking one more as flaky test. This failed 3 times out of 20 invocations.<commit_after><|endoftext|>
<commit_before>#pragma once /** @file @brief succinct vector @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <assert.h> #include <vector> #include <cybozu/exception.hpp> #include <cybozu/bit_operation.hpp> #include <cybozu/select8.hpp> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif namespace cybozu { const uint64_t NotFound = ~uint64_t(0); namespace sucvector_util { inline uint32_t rank64(uint64_t v, size_t i) { return cybozu::popcnt<uint64_t>(v & cybozu::makeBitMask64(i)); } inline uint64_t select64(uint64_t v, size_t r) { assert(r <= 64); if (r > popcnt(v)) return 64; uint32_t pos = 0; uint32_t c = popcnt(uint32_t(v)); if (r > c) { r -= c; pos = 32; v >>= 32; } c = popcnt<uint32_t>(uint16_t(v)); if (r > c) { r -= c; pos += 16; v >>= 16; } c = popcnt<uint32_t>(uint8_t(v)); if (r > c) { r -= c; pos += 8; v >>= 8; } if (r == 8 && uint8_t(v) == 0xff) return pos + 7; assert(r <= 8); c = cybozu::select8_util::select8(uint8_t(v), r); return pos + c; } } // cybozu::sucvector_util /* extra memory (32 + 8 * 4) / 256 = 1/4 bit per bit */ struct SucVector { static const uint64_t maxBitSize = uint64_t(1) << 40; struct B { uint64_t org[4]; union { uint64_t a64; struct { uint32_t a; uint8_t b[4]; // b[0] is used for (b[0] << 32) | a } ab; }; }; std::vector<B> blk_; uint64_t bitSize_; uint64_t num_[2]; template<int b> uint64_t rank_a(uint64_t i) const { assert(i < blk_.size()); uint64_t ret = blk_[i].a64 % maxBitSize; if (!b) ret = i * 256 - ret; return ret; } template<bool b> size_t get_b(size_t L, size_t i) const { assert(i > 0); size_t r = blk_[L].ab.b[i]; if (!b) r = 64 * i - r; return r; } public: SucVector() : bitSize_(0) { num_[0] = num_[1] = 0; } /* @param blk [in] bit pattern block @param bitSize [in] bitSize ; blk size = (bitSize + 63) / 64 @note max bitSize is 1<<40 */ SucVector(const uint64_t *blk, size_t bitSize) { if (bitSize > maxBitSize) throw cybozu::Exception("SucVector:too large") << bitSize; init(blk, bitSize); } void init(const uint64_t *blk, size_t bitSize) { bitSize_ = bitSize; const size_t blkNum = (bitSize + 63) / 64; size_t tblNum = (blkNum + 3) / 4; blk_.resize(tblNum + 1); uint64_t av = 0; size_t pos = 0; for (size_t i = 0; i < tblNum; i++) { B& b = blk_[i]; b.a64 = av % maxBitSize; uint32_t bv = 0; for (size_t j = 0; j < 4; j++) { uint64_t v = pos < blkNum ? blk[pos++] : 0; b.org[j] = v; uint32_t c = cybozu::popcnt(v); av += c; if (j > 0) { b.ab.b[j] = (uint8_t)bv; } bv += c; } } blk_[tblNum].a64 = av; num_[0] = blkNum * 64 - av; num_[1] = av; } uint64_t getNum(bool b) const { return num_[b ? 1 : 0]; } uint64_t rank1(size_t i) const { size_t q = i / 256; size_t r = (i / 64) & 3; assert(q < blk_.size()); const B& b = blk_[q]; uint64_t ret = b.a64 % maxBitSize; if (r > 0) { ret += b.ab.b[r]; } ret += cybozu::popcnt<uint64_t>(b.org[r] & cybozu::makeBitMask64(i & 63)); return ret; } size_t size() const { return bitSize_; } uint64_t rank0(size_t i) const { return i - rank1(i); } uint64_t rank(bool b, size_t i) const { if (b) return rank1(i); return rank0(i); } bool get(size_t i) const { size_t q = i / 256; size_t r = (i / 64) & 3; assert(q < blk_.size()); const B& b = blk_[q]; return (b.org[r] & (1ULL << (i & 63))) != 0; } size_t select0(uint64_t rank) const { return selectSub<false>(rank); } size_t select1(uint64_t rank) const { return selectSub<true>(rank); } size_t select(bool b, uint64_t rank) const { if (b) return select1(rank); return select0(rank); } /* 0123456789 0100101101 ^ ^ ^^ 0 1 23 select(v, r) = min { i - 1 | rank(v, i) = r + 1 } select(3) = 7 */ template<bool b> size_t selectSub(uint64_t rank) const { rank++; if (rank > num_[b]) return NotFound; size_t L = 0; size_t R = blk_.size(); while (L < R) { size_t M = (L + R) / 2; // (R - L) / 2 + L; if (rank_a<b>(M) < rank) { L = M + 1; } else { R = M; } } if (L > 0) L--; rank -= rank_a<b>(L); size_t i = 0; while (i < 3) { size_t r = get_b<b>(L, i + 1); if (r >= rank) { break; } i++; } if (i > 0) { size_t r = get_b<b>(L, i); rank -= r; } uint64_t v = blk_[L].org[i]; if (!b) v = ~v; uint64_t ret = cybozu::sucvector_util::select64(v, rank); ret += L * 256 + i * 64; return ret; } }; } // cybozu #ifdef _WIN32 #pragma warning(pop) #endif <commit_msg>avoid load memory<commit_after>#pragma once /** @file @brief succinct vector @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <assert.h> #include <vector> #include <cybozu/exception.hpp> #include <cybozu/bit_operation.hpp> #include <cybozu/select8.hpp> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif namespace cybozu { const uint64_t NotFound = ~uint64_t(0); namespace sucvector_util { inline uint32_t rank64(uint64_t v, size_t i) { return cybozu::popcnt<uint64_t>(v & cybozu::makeBitMask64(i)); } inline uint64_t select64(uint64_t v, size_t r) { assert(r <= 64); if (r > popcnt(v)) return 64; uint32_t pos = 0; uint32_t c = popcnt(uint32_t(v)); if (r > c) { r -= c; pos = 32; v >>= 32; } c = popcnt<uint32_t>(uint16_t(v)); if (r > c) { r -= c; pos += 16; v >>= 16; } c = popcnt<uint32_t>(uint8_t(v)); if (r > c) { r -= c; pos += 8; v >>= 8; } if (r == 8 && uint8_t(v) == 0xff) return pos + 7; assert(r <= 8); c = cybozu::select8_util::select8(uint8_t(v), r); return pos + c; } } // cybozu::sucvector_util /* extra memory (32 + 8 * 4) / 256 = 1/4 bit per bit */ struct SucVector { static const uint64_t maxBitSize = uint64_t(1) << 40; struct B { uint64_t org[4]; union { uint64_t a64; struct { uint32_t a; uint8_t b[4]; // b[0] is used for (b[0] << 32) | a } ab; }; }; std::vector<B> blk_; uint64_t bitSize_; uint64_t num_[2]; template<int b> uint64_t rank_a(uint64_t i) const { assert(i < blk_.size()); uint64_t ret = blk_[i].a64 % maxBitSize; if (!b) ret = i * 256 - ret; return ret; } template<bool b> size_t get_b(size_t L, size_t i) const { assert(i > 0); size_t r = blk_[L].ab.b[i]; if (!b) r = 64 * i - r; return r; } public: SucVector() : bitSize_(0) { num_[0] = num_[1] = 0; } /* @param blk [in] bit pattern block @param bitSize [in] bitSize ; blk size = (bitSize + 63) / 64 @note max bitSize is 1<<40 */ SucVector(const uint64_t *blk, size_t bitSize) { if (bitSize > maxBitSize) throw cybozu::Exception("SucVector:too large") << bitSize; init(blk, bitSize); } void init(const uint64_t *blk, size_t bitSize) { bitSize_ = bitSize; const size_t blkNum = (bitSize + 63) / 64; size_t tblNum = (blkNum + 3) / 4; blk_.resize(tblNum + 1); uint64_t av = 0; size_t pos = 0; for (size_t i = 0; i < tblNum; i++) { B& b = blk_[i]; b.a64 = av % maxBitSize; uint32_t bv = 0; for (size_t j = 0; j < 4; j++) { uint64_t v = pos < blkNum ? blk[pos++] : 0; b.org[j] = v; uint32_t c = cybozu::popcnt(v); av += c; if (j > 0) { b.ab.b[j] = (uint8_t)bv; } bv += c; } } blk_[tblNum].a64 = av; num_[0] = blkNum * 64 - av; num_[1] = av; } uint64_t getNum(bool b) const { return num_[b ? 1 : 0]; } uint64_t rank1(size_t i) const { size_t q = i / 256; size_t r = (i / 64) & 3; assert(q < blk_.size()); const B& b = blk_[q]; uint64_t ret = b.a64 % maxBitSize; if (r > 0) { // ret += b.ab.b[r]; ret += uint8_t(b.a64 >> (32 + r * 8)); } ret += cybozu::popcnt<uint64_t>(b.org[r] & cybozu::makeBitMask64(i & 63)); return ret; } size_t size() const { return bitSize_; } uint64_t rank0(size_t i) const { return i - rank1(i); } uint64_t rank(bool b, size_t i) const { if (b) return rank1(i); return rank0(i); } bool get(size_t i) const { size_t q = i / 256; size_t r = (i / 64) & 3; assert(q < blk_.size()); const B& b = blk_[q]; return (b.org[r] & (1ULL << (i & 63))) != 0; } size_t select0(uint64_t rank) const { return selectSub<false>(rank); } size_t select1(uint64_t rank) const { return selectSub<true>(rank); } size_t select(bool b, uint64_t rank) const { if (b) return select1(rank); return select0(rank); } /* 0123456789 0100101101 ^ ^ ^^ 0 1 23 select(v, r) = min { i - 1 | rank(v, i) = r + 1 } select(3) = 7 */ template<bool b> size_t selectSub(uint64_t rank) const { rank++; if (rank > num_[b]) return NotFound; size_t L = 0; size_t R = blk_.size(); while (L < R) { size_t M = (L + R) / 2; // (R - L) / 2 + L; if (rank_a<b>(M) < rank) { L = M + 1; } else { R = M; } } if (L > 0) L--; rank -= rank_a<b>(L); size_t i = 0; while (i < 3) { size_t r = get_b<b>(L, i + 1); if (r >= rank) { break; } i++; } if (i > 0) { size_t r = get_b<b>(L, i); rank -= r; } uint64_t v = blk_[L].org[i]; if (!b) v = ~v; uint64_t ret = cybozu::sucvector_util::select64(v, rank); ret += L * 256 + i * 64; return ret; } }; } // cybozu #ifdef _WIN32 #pragma warning(pop) #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include "bytes.hh" #include "timestamp.hh" #include "gc_clock.hh" #include <cstdint> template<typename T> static inline void set_field(bytes& v, unsigned offset, T val) { reinterpret_cast<net::packed<T>*>(v.begin() + offset)->raw = net::hton(val); } template<typename T> static inline T get_field(const bytes_view& v, unsigned offset) { return net::ntoh(*reinterpret_cast<const net::packed<T>*>(v.begin() + offset)); } class atomic_cell_or_collection; /* * Represents atomic cell layout. Works on serialized form. * * Layout: * * <live> := <int8_t:flags><int64_t:timestamp><int32_t:ttl>?<value> * <dead> := <int8_t: 0><int64_t:timestamp><int32_t:ttl> */ class atomic_cell_type final { private: static constexpr int8_t DEAD_FLAGS = 0; static constexpr int8_t LIVE_FLAG = 0x01; static constexpr int8_t TTL_FLAG = 0x02; // When present, TTL field is present. Set only for live cells static constexpr unsigned flags_size = 1; static constexpr unsigned timestamp_offset = flags_size; static constexpr unsigned timestamp_size = 8; static constexpr unsigned ttl_offset = timestamp_offset + timestamp_size; static constexpr unsigned ttl_size = 4; private: static bool is_live(const bytes_view& cell) { return cell[0] != DEAD_FLAGS; } static bool is_live_and_has_ttl(const bytes_view& cell) { return cell[0] & TTL_FLAG; } static bool is_dead(const bytes_view& cell) { return cell[0] == DEAD_FLAGS; } // Can be called on live and dead cells static api::timestamp_type timestamp(const bytes_view& cell) { return get_field<api::timestamp_type>(cell, timestamp_offset); } // Can be called on live cells only static bytes_view value(bytes_view cell) { auto ttl_field_size = bool(cell[0] & TTL_FLAG) * ttl_size; auto value_offset = flags_size + timestamp_size + ttl_field_size; cell.remove_prefix(value_offset); return cell; } // Can be called on live and dead cells. For dead cells, the result is never empty. static ttl_opt ttl(const bytes_view& cell) { auto flags = cell[0]; if (flags == DEAD_FLAGS || (flags & TTL_FLAG)) { auto ttl = get_field<int32_t>(cell, ttl_offset); return {gc_clock::time_point(gc_clock::duration(ttl))}; } return {}; } static bytes make_dead(api::timestamp_type timestamp, gc_clock::time_point ttl) { bytes b(bytes::initialized_later(), flags_size + timestamp_size + ttl_size); b[0] = DEAD_FLAGS; set_field(b, timestamp_offset, timestamp); set_field(b, ttl_offset, ttl.time_since_epoch().count()); return b; } static bytes make_live(api::timestamp_type timestamp, ttl_opt ttl, bytes_view value) { auto value_offset = flags_size + timestamp_size + bool(ttl) * ttl_size; bytes b(bytes::initialized_later(), value_offset + value.size()); b[0] = (ttl ? TTL_FLAG : 0) | LIVE_FLAG; set_field(b, timestamp_offset, timestamp); if (ttl) { set_field(b, ttl_offset, ttl->time_since_epoch().count()); } std::copy_n(value.begin(), value.size(), b.begin() + value_offset); return b; } friend class atomic_cell_view; friend class atomic_cell; }; class atomic_cell_view final { bytes_view _data; private: atomic_cell_view(bytes_view data) : _data(data) {} public: static atomic_cell_view from_bytes(bytes_view data) { return atomic_cell_view(data); } bool is_live() const { return atomic_cell_type::is_live(_data); } bool is_live_and_has_ttl() const { return atomic_cell_type::is_live_and_has_ttl(_data); } bool is_dead() const { return atomic_cell_type::is_dead(_data); } // Can be called on live and dead cells api::timestamp_type timestamp() const { return atomic_cell_type::timestamp(_data); } // Can be called on live cells only bytes_view value() const { return atomic_cell_type::value(_data); } // Can be called on live and dead cells. For dead cells, the result is never empty. ttl_opt ttl() const { return atomic_cell_type::ttl(_data); } bytes_view serialize() const { return _data; } friend class atomic_cell; }; class atomic_cell final { bytes _data; private: atomic_cell(bytes b) : _data(std::move(b)) {} public: atomic_cell(const atomic_cell&) = default; atomic_cell(atomic_cell&&) = default; atomic_cell& operator=(const atomic_cell&) = default; atomic_cell& operator=(atomic_cell&&) = default; static atomic_cell from_bytes(bytes b) { return atomic_cell(std::move(b)); } atomic_cell(atomic_cell_view other) : _data(other._data.begin(), other._data.end()) {} bool is_live() const { return atomic_cell_type::is_live(_data); } bool is_live_and_has_ttl() const { return atomic_cell_type::is_live_and_has_ttl(_data); } bool is_dead(const bytes_view& cell) const { return atomic_cell_type::is_dead(_data); } // Can be called on live and dead cells api::timestamp_type timestamp() const { return atomic_cell_type::timestamp(_data); } // Can be called on live cells only bytes_view value() const { return atomic_cell_type::value(_data); } // Can be called on live and dead cells. For dead cells, the result is never empty. ttl_opt ttl() const { return atomic_cell_type::ttl(_data); } bytes_view serialize() const { return _data; } operator atomic_cell_view() const { return atomic_cell_view(_data); } static atomic_cell make_dead(api::timestamp_type timestamp, gc_clock::time_point ttl) { return atomic_cell_type::make_dead(timestamp, ttl); } static atomic_cell make_live(api::timestamp_type timestamp, ttl_opt ttl, bytes_view value) { return atomic_cell_type::make_live(timestamp, ttl, value); } friend class atomic_cell_or_collection; }; // Represents a mutation of a collection. Actual format is determined by collection type, // and is: // set: list of atomic_cell // map: list of pair<atomic_cell, bytes> (for key/value) // list: tbd, probably ugly class collection_mutation { public: struct view { bytes_view data; }; struct one { bytes data; operator view() const { return { data }; } }; }; // A variant type that can hold either an atomic_cell, or a serialized collection. // Which type is stored is determinied by the schema. class atomic_cell_or_collection final { bytes _data; private: atomic_cell_or_collection(bytes&& data) : _data(std::move(data)) {} public: atomic_cell_or_collection(atomic_cell ac) : _data(std::move(ac._data)) {} static atomic_cell_or_collection from_atomic_cell(atomic_cell data) { return { std::move(data._data) }; } atomic_cell_view as_atomic_cell() const { return atomic_cell_view::from_bytes(_data); } atomic_cell_or_collection(collection_mutation::one cm) : _data(std::move(cm.data)) {} static atomic_cell_or_collection from_collection_mutation(collection_mutation::one data) { return std::move(data.data); } collection_mutation::view as_collection_mutation() const { return collection_mutation::view{_data}; } }; class column_definition; int compare_atomic_cell_for_merge(atomic_cell_view left, atomic_cell_view right); void merge_column(const column_definition& def, atomic_cell_or_collection& old, const atomic_cell_or_collection& neww); <commit_msg>db: drop unused atomic_cell::is_dead() parameter<commit_after>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include "bytes.hh" #include "timestamp.hh" #include "gc_clock.hh" #include <cstdint> template<typename T> static inline void set_field(bytes& v, unsigned offset, T val) { reinterpret_cast<net::packed<T>*>(v.begin() + offset)->raw = net::hton(val); } template<typename T> static inline T get_field(const bytes_view& v, unsigned offset) { return net::ntoh(*reinterpret_cast<const net::packed<T>*>(v.begin() + offset)); } class atomic_cell_or_collection; /* * Represents atomic cell layout. Works on serialized form. * * Layout: * * <live> := <int8_t:flags><int64_t:timestamp><int32_t:ttl>?<value> * <dead> := <int8_t: 0><int64_t:timestamp><int32_t:ttl> */ class atomic_cell_type final { private: static constexpr int8_t DEAD_FLAGS = 0; static constexpr int8_t LIVE_FLAG = 0x01; static constexpr int8_t TTL_FLAG = 0x02; // When present, TTL field is present. Set only for live cells static constexpr unsigned flags_size = 1; static constexpr unsigned timestamp_offset = flags_size; static constexpr unsigned timestamp_size = 8; static constexpr unsigned ttl_offset = timestamp_offset + timestamp_size; static constexpr unsigned ttl_size = 4; private: static bool is_live(const bytes_view& cell) { return cell[0] != DEAD_FLAGS; } static bool is_live_and_has_ttl(const bytes_view& cell) { return cell[0] & TTL_FLAG; } static bool is_dead(const bytes_view& cell) { return cell[0] == DEAD_FLAGS; } // Can be called on live and dead cells static api::timestamp_type timestamp(const bytes_view& cell) { return get_field<api::timestamp_type>(cell, timestamp_offset); } // Can be called on live cells only static bytes_view value(bytes_view cell) { auto ttl_field_size = bool(cell[0] & TTL_FLAG) * ttl_size; auto value_offset = flags_size + timestamp_size + ttl_field_size; cell.remove_prefix(value_offset); return cell; } // Can be called on live and dead cells. For dead cells, the result is never empty. static ttl_opt ttl(const bytes_view& cell) { auto flags = cell[0]; if (flags == DEAD_FLAGS || (flags & TTL_FLAG)) { auto ttl = get_field<int32_t>(cell, ttl_offset); return {gc_clock::time_point(gc_clock::duration(ttl))}; } return {}; } static bytes make_dead(api::timestamp_type timestamp, gc_clock::time_point ttl) { bytes b(bytes::initialized_later(), flags_size + timestamp_size + ttl_size); b[0] = DEAD_FLAGS; set_field(b, timestamp_offset, timestamp); set_field(b, ttl_offset, ttl.time_since_epoch().count()); return b; } static bytes make_live(api::timestamp_type timestamp, ttl_opt ttl, bytes_view value) { auto value_offset = flags_size + timestamp_size + bool(ttl) * ttl_size; bytes b(bytes::initialized_later(), value_offset + value.size()); b[0] = (ttl ? TTL_FLAG : 0) | LIVE_FLAG; set_field(b, timestamp_offset, timestamp); if (ttl) { set_field(b, ttl_offset, ttl->time_since_epoch().count()); } std::copy_n(value.begin(), value.size(), b.begin() + value_offset); return b; } friend class atomic_cell_view; friend class atomic_cell; }; class atomic_cell_view final { bytes_view _data; private: atomic_cell_view(bytes_view data) : _data(data) {} public: static atomic_cell_view from_bytes(bytes_view data) { return atomic_cell_view(data); } bool is_live() const { return atomic_cell_type::is_live(_data); } bool is_live_and_has_ttl() const { return atomic_cell_type::is_live_and_has_ttl(_data); } bool is_dead() const { return atomic_cell_type::is_dead(_data); } // Can be called on live and dead cells api::timestamp_type timestamp() const { return atomic_cell_type::timestamp(_data); } // Can be called on live cells only bytes_view value() const { return atomic_cell_type::value(_data); } // Can be called on live and dead cells. For dead cells, the result is never empty. ttl_opt ttl() const { return atomic_cell_type::ttl(_data); } bytes_view serialize() const { return _data; } friend class atomic_cell; }; class atomic_cell final { bytes _data; private: atomic_cell(bytes b) : _data(std::move(b)) {} public: atomic_cell(const atomic_cell&) = default; atomic_cell(atomic_cell&&) = default; atomic_cell& operator=(const atomic_cell&) = default; atomic_cell& operator=(atomic_cell&&) = default; static atomic_cell from_bytes(bytes b) { return atomic_cell(std::move(b)); } atomic_cell(atomic_cell_view other) : _data(other._data.begin(), other._data.end()) {} bool is_live() const { return atomic_cell_type::is_live(_data); } bool is_live_and_has_ttl() const { return atomic_cell_type::is_live_and_has_ttl(_data); } bool is_dead() const { return atomic_cell_type::is_dead(_data); } // Can be called on live and dead cells api::timestamp_type timestamp() const { return atomic_cell_type::timestamp(_data); } // Can be called on live cells only bytes_view value() const { return atomic_cell_type::value(_data); } // Can be called on live and dead cells. For dead cells, the result is never empty. ttl_opt ttl() const { return atomic_cell_type::ttl(_data); } bytes_view serialize() const { return _data; } operator atomic_cell_view() const { return atomic_cell_view(_data); } static atomic_cell make_dead(api::timestamp_type timestamp, gc_clock::time_point ttl) { return atomic_cell_type::make_dead(timestamp, ttl); } static atomic_cell make_live(api::timestamp_type timestamp, ttl_opt ttl, bytes_view value) { return atomic_cell_type::make_live(timestamp, ttl, value); } friend class atomic_cell_or_collection; }; // Represents a mutation of a collection. Actual format is determined by collection type, // and is: // set: list of atomic_cell // map: list of pair<atomic_cell, bytes> (for key/value) // list: tbd, probably ugly class collection_mutation { public: struct view { bytes_view data; }; struct one { bytes data; operator view() const { return { data }; } }; }; // A variant type that can hold either an atomic_cell, or a serialized collection. // Which type is stored is determinied by the schema. class atomic_cell_or_collection final { bytes _data; private: atomic_cell_or_collection(bytes&& data) : _data(std::move(data)) {} public: atomic_cell_or_collection(atomic_cell ac) : _data(std::move(ac._data)) {} static atomic_cell_or_collection from_atomic_cell(atomic_cell data) { return { std::move(data._data) }; } atomic_cell_view as_atomic_cell() const { return atomic_cell_view::from_bytes(_data); } atomic_cell_or_collection(collection_mutation::one cm) : _data(std::move(cm.data)) {} static atomic_cell_or_collection from_collection_mutation(collection_mutation::one data) { return std::move(data.data); } collection_mutation::view as_collection_mutation() const { return collection_mutation::view{_data}; } }; class column_definition; int compare_atomic_cell_for_merge(atomic_cell_view left, atomic_cell_view right); void merge_column(const column_definition& def, atomic_cell_or_collection& old, const atomic_cell_or_collection& neww); <|endoftext|>
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_OPERATOR_HPP #define KGR_KANGARU_INCLUDE_KANGARU_OPERATOR_HPP #include "container.hpp" #include "detail/lazy_base.hpp" namespace kgr { namespace detail { /* * Base class for invokers. Implements the call operator that invoke the function. */ template<typename Base, typename Map> struct invoker_base : protected Base { using Base::Base; template<typename F, typename... Args, enable_if_t<is_invoke_valid<Map, decay_t<F>, Args...>::value, int> = 0> invoke_function_result_t<Map, decay_t<F>, Args...> operator()(F&& f, Args&&... args) { kgr::container& c = this->container(); return c.invoke<Map>(std::forward<F>(f), std::forward<Args>(args)...); } sink operator()(not_invokable_error = {}, ...) = delete; }; /* * Base class for generators. Implements the call operator that create services. */ template<typename Base, typename T> struct generator_base : protected Base { static_assert(!is_single<T>::value, "Generator only work with non-single services."); using Base::Base; template<typename... Args, enable_if_t<is_service_valid<T, Args...>::value, int> = 0> service_type<T> operator()(Args&&... args) { kgr::container& c = Base::container(); return c.service<T>(std::forward<Args>(args)...); } template<typename U = T, enable_if_t<std::is_default_constructible<service_error<U>>::value, int> = 0> sink operator()(service_error<U> = {}) = delete; template<typename... Args> sink operator()(service_error<T, identity_t<Args>...>, Args&&...) = delete; }; /* * Base class for any non forking operators. * * Hold a non-owning reference to the container as a pointer. */ struct operator_base { explicit operator_base(kgr::container& c) noexcept : _container{&c} {} inline auto container() noexcept -> kgr::container& { return *_container; } inline auto container() const noexcept -> kgr::container const& { return *_container; } kgr::container* _container; }; /* * Base class for any forking operators. * * Hold a fork of the container as a member value. */ struct forked_operator_base { explicit forked_operator_base(kgr::container&& c) noexcept : _container{std::move(c)} {} inline auto container() noexcept -> kgr::container& { return _container; } inline auto container() const noexcept -> kgr::container const& { return _container; } kgr::container _container; }; } // namespace detail /** * Function object that calls container::invoke. * * Useful when dealing with higer order functions or to convey intent. */ template<typename Map> struct mapped_invoker : detail::invoker_base<detail::operator_base, Map> { using detail::invoker_base<detail::operator_base, Map>::invoker_base; template<typename M> mapped_invoker(const mapped_invoker<M>& other) : detail::invoker_base<detail::operator_base, Map>{other.container()} {} }; /** * Function object that calls container::invoke. * * This version forks the container. * * Useful when dealing with higer order functions or to convey intent. */ template<typename Map> struct forked_mapped_invoker : detail::invoker_base<detail::forked_operator_base, Map> { using detail::invoker_base<detail::forked_operator_base, Map>::invoker_base; template<typename M> forked_mapped_invoker(forked_mapped_invoker<M>&& other) : detail::invoker_base<detail::forked_operator_base, Map>{std::move(other.container())} {} }; /** * Function object that calls creates a service. * Basically a factory function for a particular service. * * Useful to convey intent or contraining usage of the container. */ template<typename T> using generator = detail::generator_base<detail::operator_base, T>; /** * Function object that calls creates a service. * Basically a factory function for a particular service. * * This version forks the container. * * Useful to convey intent or contraining usage of the container. */ template<typename T> using forked_generator = detail::generator_base<detail::forked_operator_base, T>; /** * A proxy class that delays the construction of a service until usage. */ template<typename T> using lazy = detail::lazy_base<detail::operator_base, T>; /** * A proxy class that delays the construction of a service until usage. * * This will fork the container when the proxy is created. */ template<typename T> using forked_lazy = detail::lazy_base<detail::forked_operator_base, T>; /** * Alias to the default invoker */ using invoker = mapped_invoker<map<>>; /** * Alias to the default forked invoker */ using forked_invoker = forked_mapped_invoker<map<>>; } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_OPERATOR_HPP <commit_msg>Invoker now supports custom maps when no maps are specified<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_OPERATOR_HPP #define KGR_KANGARU_INCLUDE_KANGARU_OPERATOR_HPP #include "container.hpp" #include "detail/lazy_base.hpp" namespace kgr { namespace detail { /* * Base class for invokers. Implements the call operator that invoke the function. */ template<typename Base, typename Map> struct invoker_base : protected Base { using Base::Base; template<typename F, typename... Args, enable_if_t<is_invoke_valid<Map, decay_t<F>, Args...>::value, int> = 0> invoke_function_result_t<Map, decay_t<F>, Args...> operator()(F&& f, Args&&... args) { kgr::container& c = this->container(); return c.invoke<Map>(std::forward<F>(f), std::forward<Args>(args)...); } sink operator()(not_invokable_error = {}, ...) = delete; }; template<typename Base> struct invoker_base<Base, map<>> : protected Base { using Base::Base; using map_t = map<>; template<typename F, typename... Args, enable_if_t<is_invoke_valid<map_t, decay_t<F>, Args...>::value, int> = 0> invoke_function_result_t<map_t, decay_t<F>, Args...> operator()(F&& f, Args&&... args) { kgr::container& c = this->container(); return c.invoke<map_t>(std::forward<F>(f), std::forward<Args>(args)...); } template<typename Map, typename F, typename... Args, enable_if_t<is_map<Map>::value && is_invoke_valid<Map, decay_t<F>, Args...>::value, int> = 0> invoke_function_result_t<Map, decay_t<F>, Args...> operator()(Map map, F&& f, Args&&... args) { kgr::container& c = this->container(); return c.invoke(map, std::forward<F>(f), std::forward<Args>(args)...); } sink operator()(not_invokable_error = {}, ...) = delete; }; /* * Base class for generators. Implements the call operator that create services. */ template<typename Base, typename T> struct generator_base : protected Base { static_assert(!is_single<T>::value, "Generator only work with non-single services."); using Base::Base; template<typename... Args, enable_if_t<is_service_valid<T, Args...>::value, int> = 0> service_type<T> operator()(Args&&... args) { kgr::container& c = Base::container(); return c.service<T>(std::forward<Args>(args)...); } template<typename U = T, enable_if_t<std::is_default_constructible<service_error<U>>::value, int> = 0> sink operator()(service_error<U> = {}) = delete; template<typename... Args> sink operator()(service_error<T, identity_t<Args>...>, Args&&...) = delete; }; /* * Base class for any non forking operators. * * Hold a non-owning reference to the container as a pointer. */ struct operator_base { explicit operator_base(kgr::container& c) noexcept : _container{&c} {} inline auto container() noexcept -> kgr::container& { return *_container; } inline auto container() const noexcept -> kgr::container const& { return *_container; } kgr::container* _container; }; /* * Base class for any forking operators. * * Hold a fork of the container as a member value. */ struct forked_operator_base { explicit forked_operator_base(kgr::container&& c) noexcept : _container{std::move(c)} {} inline auto container() noexcept -> kgr::container& { return _container; } inline auto container() const noexcept -> kgr::container const& { return _container; } kgr::container _container; }; } // namespace detail /** * Function object that calls container::invoke. * * Useful when dealing with higer order functions or to convey intent. */ template<typename Map> struct mapped_invoker : detail::invoker_base<detail::operator_base, Map> { using detail::invoker_base<detail::operator_base, Map>::invoker_base; template<typename M> mapped_invoker(const mapped_invoker<M>& other) : detail::invoker_base<detail::operator_base, Map>{other.container()} {} }; /** * Function object that calls container::invoke. * * This version forks the container. * * Useful when dealing with higer order functions or to convey intent. */ template<typename Map> struct forked_mapped_invoker : detail::invoker_base<detail::forked_operator_base, Map> { using detail::invoker_base<detail::forked_operator_base, Map>::invoker_base; template<typename M> forked_mapped_invoker(forked_mapped_invoker<M>&& other) : detail::invoker_base<detail::forked_operator_base, Map>{std::move(other.container())} {} }; /** * Function object that calls creates a service. * Basically a factory function for a particular service. * * Useful to convey intent or contraining usage of the container. */ template<typename T> using generator = detail::generator_base<detail::operator_base, T>; /** * Function object that calls creates a service. * Basically a factory function for a particular service. * * This version forks the container. * * Useful to convey intent or contraining usage of the container. */ template<typename T> using forked_generator = detail::generator_base<detail::forked_operator_base, T>; /** * A proxy class that delays the construction of a service until usage. */ template<typename T> using lazy = detail::lazy_base<detail::operator_base, T>; /** * A proxy class that delays the construction of a service until usage. * * This will fork the container when the proxy is created. */ template<typename T> using forked_lazy = detail::lazy_base<detail::forked_operator_base, T>; /** * Alias to the default invoker */ using invoker = mapped_invoker<map<>>; /** * Alias to the default forked invoker */ using forked_invoker = forked_mapped_invoker<map<>>; } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_OPERATOR_HPP <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ENTRY_HPP_INCLUDED #define TORRENT_ENTRY_HPP_INCLUDED /* * * This file declares the entry class. It is a * variant-type that can be an integer, list, * dictionary (map) or a string. This type is * used to hold bdecoded data (which is the * encoding BitTorrent messages uses). * * it has 4 accessors to access the actual * type of the object. They are: * integer() * string() * list() * dict() * The actual type has to match the type you * are asking for, otherwise you will get an * assertion failure. * When you default construct an entry, it is * uninitialized. You can initialize it through the * assignment operator, copy-constructor or * the constructor that takes a data_type enum. * * */ #include <map> #include <list> #include <string> #include <stdexcept> #include "libtorrent/size_type.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #include "libtorrent/error_code.hpp" #if TORRENT_USE_IOSTREAM #include <iosfwd> #endif namespace libtorrent { struct TORRENT_EXPORT type_error: std::runtime_error { type_error(const char* error): std::runtime_error(error) {} }; namespace detail { template<int v1, int v2> struct max2 { enum { value = v1>v2?v1:v2 }; }; template<int v1, int v2, int v3> struct max3 { enum { temp = max2<v1,v2>::value, value = temp>v3?temp:v3 }; }; template<int v1, int v2, int v3, int v4> struct max4 { enum { temp = max3<v1,v2, v3>::value, value = temp>v4?temp:v4 }; }; } class entry; class TORRENT_EXPORT entry { public: // the key is always a string. If a generic entry would be allowed // as a key, sorting would become a problem (e.g. to compare a string // to a list). The definition doesn't mention such a limit though. typedef std::map<std::string, entry> dictionary_type; typedef std::string string_type; typedef std::list<entry> list_type; typedef size_type integer_type; enum data_type { int_t, string_t, list_t, dictionary_t, undefined_t }; data_type type() const; entry(dictionary_type const&); entry(string_type const&); entry(list_type const&); entry(integer_type const&); entry(); entry(data_type t); entry(entry const& e); ~entry(); bool operator==(entry const& e) const; void operator=(entry const&); void operator=(dictionary_type const&); void operator=(string_type const&); void operator=(list_type const&); void operator=(integer_type const&); integer_type& integer(); const integer_type& integer() const; string_type& string(); const string_type& string() const; list_type& list(); const list_type& list() const; dictionary_type& dict(); const dictionary_type& dict() const; void swap(entry& e); // these functions requires that the entry // is a dictionary, otherwise they will throw entry& operator[](char const* key); entry& operator[](std::string const& key); #ifndef BOOST_NO_EXCEPTIONS const entry& operator[](char const* key) const; const entry& operator[](std::string const& key) const; #endif entry* find_key(char const* key); entry const* find_key(char const* key) const; entry* find_key(std::string const& key); entry const* find_key(std::string const& key) const; #if defined TORRENT_DEBUG && TORRENT_USE_IOSTREAM void print(std::ostream& os, int indent = 0) const; #endif protected: void construct(data_type t); void copy(const entry& e); void destruct(); private: data_type m_type; #if defined(_MSC_VER) && _MSC_VER < 1310 // workaround for msvc-bug. // assumes sizeof(map<string, char>) == sizeof(map<string, entry>) // and sizeof(list<char>) == sizeof(list<entry>) union { char data[ detail::max4<sizeof(std::list<char>) , sizeof(std::map<std::string, char>) , sizeof(string_type) , sizeof(integer_type)>::value]; integer_type dummy_aligner; }; #else union { char data[detail::max4<sizeof(list_type) , sizeof(dictionary_type) , sizeof(string_type) , sizeof(integer_type)>::value]; integer_type dummy_aligner; }; #endif #ifdef TORRENT_DEBUG public: // in debug mode this is set to false by bdecode // to indicate that the program has not yet queried // the type of this entry, and sould not assume // that it has a certain type. This is asserted in // the accessor functions. This does not apply if // exceptions are used. mutable bool m_type_queried; #endif }; #if TORRENT_USE_IOSTREAM inline std::ostream& operator<<(std::ostream& os, const entry& e) { e.print(os, 0); return os; } #endif #ifndef BOOST_NO_EXCEPTIONS inline void throw_type_error() { throw libtorrent_exception(error_code(errors::invalid_entry_type , libtorrent_category)); } #endif inline entry::data_type entry::type() const { #ifdef TORRENT_DEBUG m_type_queried = true; #endif return m_type; } inline entry::~entry() { destruct(); } inline void entry::operator=(const entry& e) { destruct(); copy(e); } inline entry::integer_type& entry::integer() { if (m_type == undefined_t) construct(int_t); #ifndef BOOST_NO_EXCEPTIONS if (m_type != int_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == int_t); return *reinterpret_cast<integer_type*>(data); } inline entry::integer_type const& entry::integer() const { #ifndef BOOST_NO_EXCEPTIONS if (m_type != int_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == int_t); return *reinterpret_cast<const integer_type*>(data); } inline entry::string_type& entry::string() { if (m_type == undefined_t) construct(string_t); #ifndef BOOST_NO_EXCEPTIONS if (m_type != string_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == string_t); return *reinterpret_cast<string_type*>(data); } inline entry::string_type const& entry::string() const { #ifndef BOOST_NO_EXCEPTIONS if (m_type != string_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == string_t); return *reinterpret_cast<const string_type*>(data); } inline entry::list_type& entry::list() { if (m_type == undefined_t) construct(list_t); #ifndef BOOST_NO_EXCEPTIONS if (m_type != list_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == list_t); return *reinterpret_cast<list_type*>(data); } inline entry::list_type const& entry::list() const { #ifndef BOOST_NO_EXCEPTIONS if (m_type != list_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == list_t); return *reinterpret_cast<const list_type*>(data); } inline entry::dictionary_type& entry::dict() { if (m_type == undefined_t) construct(dictionary_t); #ifndef BOOST_NO_EXCEPTIONS if (m_type != dictionary_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == dictionary_t); return *reinterpret_cast<dictionary_type*>(data); } inline entry::dictionary_type const& entry::dict() const { #ifndef BOOST_NO_EXCEPTIONS if (m_type != dictionary_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == dictionary_t); return *reinterpret_cast<const dictionary_type*>(data); } } #endif // TORRENT_ENTRY_HPP_INCLUDED <commit_msg>fixed inconsistent use of preprocessor macro for entry::print<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_ENTRY_HPP_INCLUDED #define TORRENT_ENTRY_HPP_INCLUDED /* * * This file declares the entry class. It is a * variant-type that can be an integer, list, * dictionary (map) or a string. This type is * used to hold bdecoded data (which is the * encoding BitTorrent messages uses). * * it has 4 accessors to access the actual * type of the object. They are: * integer() * string() * list() * dict() * The actual type has to match the type you * are asking for, otherwise you will get an * assertion failure. * When you default construct an entry, it is * uninitialized. You can initialize it through the * assignment operator, copy-constructor or * the constructor that takes a data_type enum. * * */ #include <map> #include <list> #include <string> #include <stdexcept> #include "libtorrent/size_type.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #include "libtorrent/error_code.hpp" #if TORRENT_USE_IOSTREAM #include <iosfwd> #endif namespace libtorrent { struct TORRENT_EXPORT type_error: std::runtime_error { type_error(const char* error): std::runtime_error(error) {} }; namespace detail { template<int v1, int v2> struct max2 { enum { value = v1>v2?v1:v2 }; }; template<int v1, int v2, int v3> struct max3 { enum { temp = max2<v1,v2>::value, value = temp>v3?temp:v3 }; }; template<int v1, int v2, int v3, int v4> struct max4 { enum { temp = max3<v1,v2, v3>::value, value = temp>v4?temp:v4 }; }; } class entry; class TORRENT_EXPORT entry { public: // the key is always a string. If a generic entry would be allowed // as a key, sorting would become a problem (e.g. to compare a string // to a list). The definition doesn't mention such a limit though. typedef std::map<std::string, entry> dictionary_type; typedef std::string string_type; typedef std::list<entry> list_type; typedef size_type integer_type; enum data_type { int_t, string_t, list_t, dictionary_t, undefined_t }; data_type type() const; entry(dictionary_type const&); entry(string_type const&); entry(list_type const&); entry(integer_type const&); entry(); entry(data_type t); entry(entry const& e); ~entry(); bool operator==(entry const& e) const; void operator=(entry const&); void operator=(dictionary_type const&); void operator=(string_type const&); void operator=(list_type const&); void operator=(integer_type const&); integer_type& integer(); const integer_type& integer() const; string_type& string(); const string_type& string() const; list_type& list(); const list_type& list() const; dictionary_type& dict(); const dictionary_type& dict() const; void swap(entry& e); // these functions requires that the entry // is a dictionary, otherwise they will throw entry& operator[](char const* key); entry& operator[](std::string const& key); #ifndef BOOST_NO_EXCEPTIONS const entry& operator[](char const* key) const; const entry& operator[](std::string const& key) const; #endif entry* find_key(char const* key); entry const* find_key(char const* key) const; entry* find_key(std::string const& key); entry const* find_key(std::string const& key) const; #if defined TORRENT_DEBUG && TORRENT_USE_IOSTREAM void print(std::ostream& os, int indent = 0) const; #endif protected: void construct(data_type t); void copy(const entry& e); void destruct(); private: data_type m_type; #if defined(_MSC_VER) && _MSC_VER < 1310 // workaround for msvc-bug. // assumes sizeof(map<string, char>) == sizeof(map<string, entry>) // and sizeof(list<char>) == sizeof(list<entry>) union { char data[ detail::max4<sizeof(std::list<char>) , sizeof(std::map<std::string, char>) , sizeof(string_type) , sizeof(integer_type)>::value]; integer_type dummy_aligner; }; #else union { char data[detail::max4<sizeof(list_type) , sizeof(dictionary_type) , sizeof(string_type) , sizeof(integer_type)>::value]; integer_type dummy_aligner; }; #endif #ifdef TORRENT_DEBUG public: // in debug mode this is set to false by bdecode // to indicate that the program has not yet queried // the type of this entry, and sould not assume // that it has a certain type. This is asserted in // the accessor functions. This does not apply if // exceptions are used. mutable bool m_type_queried; #endif }; #if defined TORRENT_DEBUG && TORRENT_USE_IOSTREAM inline std::ostream& operator<<(std::ostream& os, const entry& e) { e.print(os, 0); return os; } #endif #ifndef BOOST_NO_EXCEPTIONS inline void throw_type_error() { throw libtorrent_exception(error_code(errors::invalid_entry_type , libtorrent_category)); } #endif inline entry::data_type entry::type() const { #ifdef TORRENT_DEBUG m_type_queried = true; #endif return m_type; } inline entry::~entry() { destruct(); } inline void entry::operator=(const entry& e) { destruct(); copy(e); } inline entry::integer_type& entry::integer() { if (m_type == undefined_t) construct(int_t); #ifndef BOOST_NO_EXCEPTIONS if (m_type != int_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == int_t); return *reinterpret_cast<integer_type*>(data); } inline entry::integer_type const& entry::integer() const { #ifndef BOOST_NO_EXCEPTIONS if (m_type != int_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == int_t); return *reinterpret_cast<const integer_type*>(data); } inline entry::string_type& entry::string() { if (m_type == undefined_t) construct(string_t); #ifndef BOOST_NO_EXCEPTIONS if (m_type != string_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == string_t); return *reinterpret_cast<string_type*>(data); } inline entry::string_type const& entry::string() const { #ifndef BOOST_NO_EXCEPTIONS if (m_type != string_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == string_t); return *reinterpret_cast<const string_type*>(data); } inline entry::list_type& entry::list() { if (m_type == undefined_t) construct(list_t); #ifndef BOOST_NO_EXCEPTIONS if (m_type != list_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == list_t); return *reinterpret_cast<list_type*>(data); } inline entry::list_type const& entry::list() const { #ifndef BOOST_NO_EXCEPTIONS if (m_type != list_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == list_t); return *reinterpret_cast<const list_type*>(data); } inline entry::dictionary_type& entry::dict() { if (m_type == undefined_t) construct(dictionary_t); #ifndef BOOST_NO_EXCEPTIONS if (m_type != dictionary_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == dictionary_t); return *reinterpret_cast<dictionary_type*>(data); } inline entry::dictionary_type const& entry::dict() const { #ifndef BOOST_NO_EXCEPTIONS if (m_type != dictionary_t) throw_type_error(); #elif defined TORRENT_DEBUG TORRENT_ASSERT(m_type_queried); #endif TORRENT_ASSERT(m_type == dictionary_t); return *reinterpret_cast<const dictionary_type*>(data); } } #endif // TORRENT_ENTRY_HPP_INCLUDED <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_QUAD_TREE_HPP #define MAPNIK_QUAD_TREE_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/util/noncopyable.hpp> #include <mapnik/make_unique.hpp> // stl #include <algorithm> #include <vector> #include <type_traits> #include <cstring> namespace mapnik { template <typename T> class quad_tree : util::noncopyable { using value_type = T; struct node { using cont_type = std::vector<T>; using iterator = typename cont_type::iterator; using const_iterator = typename cont_type::const_iterator; box2d<double> extent_; cont_type cont_; node * children_[4]; explicit node(box2d<double> const& ext) : extent_(ext) { std::fill(children_, children_ + 4, nullptr); } box2d<double> const& extent() const { return extent_; } iterator begin() { return cont_.begin(); } const_iterator begin() const { return cont_.begin(); } iterator end() { return cont_.end(); } const_iterator end() const { return cont_.end(); } int num_subnodes() const { int count = 0; for (int i = 0; i < 4; ++i) { if (children_[i]) ++count; } return count; } ~node () {} }; using nodes_type = std::vector<std::unique_ptr<node> >; using cont_type = typename node::cont_type; using node_data_iterator = typename cont_type::iterator; public: using iterator = typename nodes_type::iterator; using const_iterator = typename nodes_type::const_iterator; using result_type = typename std::vector<std::reference_wrapper<T> >; using query_iterator = typename result_type::iterator; explicit quad_tree(box2d<double> const& ext, unsigned int max_depth = 8, double ratio = 0.55) : max_depth_(max_depth), ratio_(ratio), query_result_(), nodes_() { nodes_.push_back(std::make_unique<node>(ext)); root_ = nodes_[0].get(); } void insert(T data, box2d<double> const& box) { unsigned int depth=0; do_insert_data(data,box,root_,depth); } query_iterator query_in_box(box2d<double> const& box) { query_result_.clear(); query_node(box, query_result_, root_); return query_result_.begin(); } query_iterator query_end() { return query_result_.end(); } const_iterator begin() const { return nodes_.begin(); } const_iterator end() const { return nodes_.end(); } void clear () { box2d<double> ext = root_->extent_; nodes_.clear(); nodes_.push_back(std::make_unique<node>(ext)); root_ = nodes_[0].get(); } box2d<double> const& extent() const { return root_->extent_; } int count() const { return count_nodes(root_); } int count_items() const { int count = 0; count_items(root_, count); return count; } void trim() { trim_tree(root_); } template <typename OutputStream> void write(OutputStream & out) { static_assert(std::is_standard_layout<value_type>::value, "Values stored in quad-tree must be standard layout types to allow serialisation"); char header[16]; std::memset(header,0,16); header[0]='m'; header[1]='a'; header[2]='p'; header[3]='n'; header[4]='i'; header[5]='k'; out.write(header,16); write_node(out,root_); } private: void query_node(box2d<double> const& box, result_type & result, node * node_) const { if (node_) { box2d<double> const& node_extent = node_->extent(); if (box.intersects(node_extent)) { for (auto & n : *node_) { result.push_back(std::ref(n)); } for (int k = 0; k < 4; ++k) { query_node(box,result,node_->children_[k]); } } } } void do_insert_data(T data, box2d<double> const& box, node * n, unsigned int& depth) { if (++depth >= max_depth_) { n->cont_.push_back(data); } else { box2d<double> const& node_extent = n->extent(); box2d<double> ext[4]; split_box(node_extent,ext); for (int i = 0; i < 4; ++i) { if (ext[i].contains(box)) { if (!n->children_[i]) { nodes_.push_back(std::make_unique<node>(ext[i])); n->children_[i]=nodes_.back().get(); } do_insert_data(data,box,n->children_[i],depth); return; } } n->cont_.push_back(data); } } void split_box(box2d<double> const& node_extent,box2d<double> * ext) { double width=node_extent.width(); double height=node_extent.height(); double lox=node_extent.minx(); double loy=node_extent.miny(); double hix=node_extent.maxx(); double hiy=node_extent.maxy(); ext[0]=box2d<double>(lox,loy,lox + width * ratio_,loy + height * ratio_); ext[1]=box2d<double>(hix - width * ratio_,loy,hix,loy + height * ratio_); ext[2]=box2d<double>(lox,hiy - height*ratio_,lox + width * ratio_,hiy); ext[3]=box2d<double>(hix - width * ratio_,hiy - height*ratio_,hix,hiy); } void trim_tree(node * n) { if (n) { for (int i = 0; i < 4; ++i) { trim_tree(n->children_[i]); } if (n->num_subnodes() == 1 && n->cont_.size() == 0) { for (int i = 0; i < 4; ++i) { if (n->children_[i]) { n = n->children_[i]; break; } } } } } int count_nodes(node const* n) const { if (!n) return 0; else { int count = 1; for (int i = 0; i < 4; ++i) { count += count_nodes(n->children_[i]); } return count; } } void count_items(node const* n,int& count) const { if (n) { count += n->cont_.size(); for (int i = 0; i < 4; ++i) { count_items(n->children_[i],count); } } } int subnode_offset(node const* n) const { int offset = 0; for (int i = 0; i < 4; i++) { if (n->children_[i]) { offset +=sizeof(box2d<double>) + (n->children_[i]->cont_.size() * sizeof(value_type)) + 3 * sizeof(int); offset +=subnode_offset(n->children_[i]); } } return offset; } template <typename OutputStream> void write_node(OutputStream & out, node const* n) const { if (n) { int offset=subnode_offset(n); int shape_count=n->cont_.size(); int recsize=sizeof(box2d<double>) + 3 * sizeof(int) + shape_count * sizeof(value_type); std::unique_ptr<char[]> node_record(new char[recsize]); std::memset(node_record.get(), 0, recsize); std::memcpy(node_record.get(), &offset, 4); std::memcpy(node_record.get() + 4, &n->extent_, sizeof(box2d<double>)); std::memcpy(node_record.get() + 36, &shape_count, 4); for (int i=0; i < shape_count; ++i) { memcpy(node_record.get() + 40 + i * sizeof(value_type), &(n->cont_[i]),sizeof(value_type)); } int num_subnodes=0; for (int i = 0; i < 4; ++i) { if (n->children_[i]) { ++num_subnodes; } } std::memcpy(node_record.get() + 40 + shape_count * sizeof(value_type),&num_subnodes,4); out.write(node_record.get(),recsize); for (int i = 0; i < 4; ++i) { write_node(out, n->children_[i]); } } } const unsigned int max_depth_; const double ratio_; result_type query_result_; nodes_type nodes_; node * root_; }; } #endif // MAPNIK_QUAD_TREE_HPP <commit_msg>quad_tree - pass node by *&<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_QUAD_TREE_HPP #define MAPNIK_QUAD_TREE_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/util/noncopyable.hpp> #include <mapnik/make_unique.hpp> // stl #include <algorithm> #include <vector> #include <type_traits> #include <cstring> namespace mapnik { template <typename T> class quad_tree : util::noncopyable { using value_type = T; struct node { using cont_type = std::vector<T>; using iterator = typename cont_type::iterator; using const_iterator = typename cont_type::const_iterator; box2d<double> extent_; cont_type cont_; node * children_[4]; explicit node(box2d<double> const& ext) : extent_(ext) { std::fill(children_, children_ + 4, nullptr); } box2d<double> const& extent() const { return extent_; } iterator begin() { return cont_.begin(); } const_iterator begin() const { return cont_.begin(); } iterator end() { return cont_.end(); } const_iterator end() const { return cont_.end(); } int num_subnodes() const { int count = 0; for (int i = 0; i < 4; ++i) { if (children_[i]) ++count; } return count; } ~node () {} }; using nodes_type = std::vector<std::unique_ptr<node> >; using cont_type = typename node::cont_type; using node_data_iterator = typename cont_type::iterator; public: using iterator = typename nodes_type::iterator; using const_iterator = typename nodes_type::const_iterator; using result_type = typename std::vector<std::reference_wrapper<T> >; using query_iterator = typename result_type::iterator; explicit quad_tree(box2d<double> const& ext, unsigned int max_depth = 8, double ratio = 0.55) : max_depth_(max_depth), ratio_(ratio), query_result_(), nodes_() { nodes_.push_back(std::make_unique<node>(ext)); root_ = nodes_[0].get(); } void insert(T data, box2d<double> const& box) { unsigned int depth=0; do_insert_data(data,box,root_,depth); } query_iterator query_in_box(box2d<double> const& box) { query_result_.clear(); query_node(box, query_result_, root_); return query_result_.begin(); } query_iterator query_end() { return query_result_.end(); } const_iterator begin() const { return nodes_.begin(); } const_iterator end() const { return nodes_.end(); } void clear () { box2d<double> ext = root_->extent_; nodes_.clear(); nodes_.push_back(std::make_unique<node>(ext)); root_ = nodes_[0].get(); } box2d<double> const& extent() const { return root_->extent_; } int count() const { return count_nodes(root_); } int count_items() const { int count = 0; count_items(root_, count); return count; } void trim() { trim_tree(root_); } template <typename OutputStream> void write(OutputStream & out) { static_assert(std::is_standard_layout<value_type>::value, "Values stored in quad-tree must be standard layout types to allow serialisation"); char header[16]; std::memset(header,0,16); header[0]='m'; header[1]='a'; header[2]='p'; header[3]='n'; header[4]='i'; header[5]='k'; out.write(header,16); write_node(out,root_); } private: void query_node(box2d<double> const& box, result_type & result, node * node_) const { if (node_) { box2d<double> const& node_extent = node_->extent(); if (box.intersects(node_extent)) { for (auto & n : *node_) { result.push_back(std::ref(n)); } for (int k = 0; k < 4; ++k) { query_node(box,result,node_->children_[k]); } } } } void do_insert_data(T data, box2d<double> const& box, node * n, unsigned int& depth) { if (++depth >= max_depth_) { n->cont_.push_back(data); } else { box2d<double> const& node_extent = n->extent(); box2d<double> ext[4]; split_box(node_extent,ext); for (int i = 0; i < 4; ++i) { if (ext[i].contains(box)) { if (!n->children_[i]) { nodes_.push_back(std::make_unique<node>(ext[i])); n->children_[i]=nodes_.back().get(); } do_insert_data(data,box,n->children_[i],depth); return; } } n->cont_.push_back(data); } } void split_box(box2d<double> const& node_extent,box2d<double> * ext) { double width=node_extent.width(); double height=node_extent.height(); double lox=node_extent.minx(); double loy=node_extent.miny(); double hix=node_extent.maxx(); double hiy=node_extent.maxy(); ext[0]=box2d<double>(lox,loy,lox + width * ratio_,loy + height * ratio_); ext[1]=box2d<double>(hix - width * ratio_,loy,hix,loy + height * ratio_); ext[2]=box2d<double>(lox,hiy - height*ratio_,lox + width * ratio_,hiy); ext[3]=box2d<double>(hix - width * ratio_,hiy - height*ratio_,hix,hiy); } void trim_tree(node *& n) { if (n) { for (int i = 0; i < 4; ++i) { trim_tree(n->children_[i]); } if (n->num_subnodes() == 1 && n->cont_.size() == 0) { for (int i = 0; i < 4; ++i) { if (n->children_[i]) { n = n->children_[i]; break; } } } } } int count_nodes(node const* n) const { if (!n) return 0; else { int count = 1; for (int i = 0; i < 4; ++i) { count += count_nodes(n->children_[i]); } return count; } } void count_items(node const* n,int& count) const { if (n) { count += n->cont_.size(); for (int i = 0; i < 4; ++i) { count_items(n->children_[i],count); } } } int subnode_offset(node const* n) const { int offset = 0; for (int i = 0; i < 4; i++) { if (n->children_[i]) { offset +=sizeof(box2d<double>) + (n->children_[i]->cont_.size() * sizeof(value_type)) + 3 * sizeof(int); offset +=subnode_offset(n->children_[i]); } } return offset; } template <typename OutputStream> void write_node(OutputStream & out, node const* n) const { if (n) { int offset=subnode_offset(n); int shape_count=n->cont_.size(); int recsize=sizeof(box2d<double>) + 3 * sizeof(int) + shape_count * sizeof(value_type); std::unique_ptr<char[]> node_record(new char[recsize]); std::memset(node_record.get(), 0, recsize); std::memcpy(node_record.get(), &offset, 4); std::memcpy(node_record.get() + 4, &n->extent_, sizeof(box2d<double>)); std::memcpy(node_record.get() + 36, &shape_count, 4); for (int i=0; i < shape_count; ++i) { memcpy(node_record.get() + 40 + i * sizeof(value_type), &(n->cont_[i]),sizeof(value_type)); } int num_subnodes=0; for (int i = 0; i < 4; ++i) { if (n->children_[i]) { ++num_subnodes; } } std::memcpy(node_record.get() + 40 + shape_count * sizeof(value_type),&num_subnodes,4); out.write(node_record.get(),recsize); for (int i = 0; i < 4; ++i) { write_node(out, n->children_[i]); } } } const unsigned int max_depth_; const double ratio_; result_type query_result_; nodes_type nodes_; node * root_; }; } #endif // MAPNIK_QUAD_TREE_HPP <|endoftext|>
<commit_before>// Copyright (C) 2016-2017 Jonathan Müller <[email protected]> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef TYPE_SAFE_CONFIG_HPP_INCLUDED #define TYPE_SAFE_CONFIG_HPP_INCLUDED #include <cstddef> #include <cstdlib> #ifndef TYPE_SAFE_ENABLE_ASSERTIONS /// Controls whether internal assertions are enabled. /// /// It is disabled by default. #define TYPE_SAFE_ENABLE_ASSERTIONS 0 #endif #ifndef TYPE_SAFE_ENABLE_PRECONDITION_CHECKS /// Controls whether preconditions are checked. /// /// It is enabled by default. #define TYPE_SAFE_ENABLE_PRECONDITION_CHECKS 1 #endif #ifndef TYPE_SAFE_ENABLE_WRAPPER /// Controls whether the typedefs in [types.hpp]() use the type safe wrapper types. /// /// It is enabled by default. #define TYPE_SAFE_ENABLE_WRAPPER 1 #endif #ifndef TYPE_SAFE_ARITHMETIC_UB /// Controls whether [ts::arithmetic_policy_default]() is [ts::undefined_behavior_arithmetic]() or [ts::default_arithmetic](). /// /// It is [ts::undefined_behavior_arithmetic]() by default. #define TYPE_SAFE_ARITHMETIC_UB 1 #endif #ifndef TYPE_SAFE_USE_REF_QUALIFIERS #if defined(__cpp_ref_qualifiers) && __cpp_ref_qualifiers >= 200710 /// \exclude #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #elif defined(_MSC_VER) && _MSC_VER >= 1900 #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #else #define TYPE_SAFE_USE_REF_QUALIFIERS 0 #endif #endif #if TYPE_SAFE_USE_REF_QUALIFIERS /// \exclude #define TYPE_SAFE_LVALUE_REF & /// \exclude #define TYPE_SAFE_RVALUE_REF && #else #define TYPE_SAFE_LVALUE_REF #define TYPE_SAFE_RVALUE_REF #endif #ifndef TYPE_SAFE_USE_NOEXCEPT_DEFAULT #if defined(__GNUC__) && __GNUC__ < 5 // GCC before 5.0 doesn't handle noexcept and = default properly /// \exclude #define TYPE_SAFE_USE_NOEXCEPT_DEFAULT 0 #else /// \exclude #define TYPE_SAFE_USE_NOEXCEPT_DEFAULT 1 #endif #endif #if TYPE_SAFE_USE_NOEXCEPT_DEFAULT /// \exclude #define TYPE_SAFE_NOEXCEPT_DEFAULT(Val) noexcept(Val) #else /// \exclude #define TYPE_SAFE_NOEXCEPT_DEFAULT(Val) #endif #ifndef TYPE_SAFE_USE_EXCEPTIONS #if __cpp_exceptions /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(__GNUC__) && defined(__EXCEPTIONS) /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(_MSC_VER) && defined(_CPPUNWIND) /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 1 #else /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 0 #endif #endif #if TYPE_SAFE_USE_EXCEPTIONS /// \exclude #define TYPE_SAFE_THROW(Ex) throw Ex /// \exclude #define TYPE_SAFE_TRY try /// \exclude #define TYPE_SAFE_CATCH_ALL catch (...) /// \exclude #define TYPE_SAFE_RETHROW throw #else #define TYPE_SAFE_THROW(Ex) (Ex, std::abort()) #define TYPE_SAFE_TRY if (true) #define TYPE_SAFE_CATCH_ALL if (false) #define TYPE_SAFE_RETHROW std::abort() #endif /// \entity type_safe /// \unique_name ts #endif // TYPE_SAFE_CONFIG_HPP_INCLUDED <commit_msg>Add TYPE_SAFE_USE_RTTI macro<commit_after>// Copyright (C) 2016-2017 Jonathan Müller <[email protected]> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef TYPE_SAFE_CONFIG_HPP_INCLUDED #define TYPE_SAFE_CONFIG_HPP_INCLUDED #include <cstddef> #include <cstdlib> #ifndef TYPE_SAFE_ENABLE_ASSERTIONS /// Controls whether internal assertions are enabled. /// /// It is disabled by default. #define TYPE_SAFE_ENABLE_ASSERTIONS 0 #endif #ifndef TYPE_SAFE_ENABLE_PRECONDITION_CHECKS /// Controls whether preconditions are checked. /// /// It is enabled by default. #define TYPE_SAFE_ENABLE_PRECONDITION_CHECKS 1 #endif #ifndef TYPE_SAFE_ENABLE_WRAPPER /// Controls whether the typedefs in [types.hpp]() use the type safe wrapper types. /// /// It is enabled by default. #define TYPE_SAFE_ENABLE_WRAPPER 1 #endif #ifndef TYPE_SAFE_ARITHMETIC_UB /// Controls whether [ts::arithmetic_policy_default]() is [ts::undefined_behavior_arithmetic]() or [ts::default_arithmetic](). /// /// It is [ts::undefined_behavior_arithmetic]() by default. #define TYPE_SAFE_ARITHMETIC_UB 1 #endif #ifndef TYPE_SAFE_USE_REF_QUALIFIERS #if defined(__cpp_ref_qualifiers) && __cpp_ref_qualifiers >= 200710 /// \exclude #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #elif defined(_MSC_VER) && _MSC_VER >= 1900 #define TYPE_SAFE_USE_REF_QUALIFIERS 1 #else #define TYPE_SAFE_USE_REF_QUALIFIERS 0 #endif #endif #if TYPE_SAFE_USE_REF_QUALIFIERS /// \exclude #define TYPE_SAFE_LVALUE_REF & /// \exclude #define TYPE_SAFE_RVALUE_REF && #else #define TYPE_SAFE_LVALUE_REF #define TYPE_SAFE_RVALUE_REF #endif #ifndef TYPE_SAFE_USE_NOEXCEPT_DEFAULT #if defined(__GNUC__) && __GNUC__ < 5 // GCC before 5.0 doesn't handle noexcept and = default properly /// \exclude #define TYPE_SAFE_USE_NOEXCEPT_DEFAULT 0 #else /// \exclude #define TYPE_SAFE_USE_NOEXCEPT_DEFAULT 1 #endif #endif #if TYPE_SAFE_USE_NOEXCEPT_DEFAULT /// \exclude #define TYPE_SAFE_NOEXCEPT_DEFAULT(Val) noexcept(Val) #else /// \exclude #define TYPE_SAFE_NOEXCEPT_DEFAULT(Val) #endif #ifndef TYPE_SAFE_USE_EXCEPTIONS #if __cpp_exceptions /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(__GNUC__) && defined(__EXCEPTIONS) /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 1 #elif defined(_MSC_VER) && defined(_CPPUNWIND) /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 1 #else /// \exclude #define TYPE_SAFE_USE_EXCEPTIONS 0 #endif #endif #if TYPE_SAFE_USE_EXCEPTIONS /// \exclude #define TYPE_SAFE_THROW(Ex) throw Ex /// \exclude #define TYPE_SAFE_TRY try /// \exclude #define TYPE_SAFE_CATCH_ALL catch (...) /// \exclude #define TYPE_SAFE_RETHROW throw #else #define TYPE_SAFE_THROW(Ex) (Ex, std::abort()) #define TYPE_SAFE_TRY if (true) #define TYPE_SAFE_CATCH_ALL if (false) #define TYPE_SAFE_RETHROW std::abort() #endif #ifndef TYPE_SAFE_USE_RTTI #ifdef __GXX_RTTI #define TYPE_SAFE_USE_RTTI 1 #elif defined(_CPPRTTI_) #define TYPE_SAFE_USE_RTTI 1 #else #define TYPE_SAFE_USE_RTTI 0 #endif #endif /// \entity type_safe /// \unique_name ts #endif // TYPE_SAFE_CONFIG_HPP_INCLUDED <|endoftext|>
<commit_before>#include <iostream> #include <vector> class BigInteger { public: BigInteger() : digits(1, 0) {} BigInteger(unsigned int x) { do { digits.push_back(x % 10); x /= 10; } while (x > 0); } BigInteger& operator++() { digits[0]++; HandleCarry(); return *this; } BigInteger operator++(int) { BigInteger copy(*this); ++copy; return copy; } BigInteger operator/(const BigInteger& o) { BigInteger res; BigInteger reminder(*this); int power = reminder.digits.size() - o.digits.size(); if (power <= 0) { return 0; } res.digits.resize(power + 1, 0); while (reminder > o) { for (int d = 1; d <= 10; ++d) { BigInteger temp; temp.digits.resize(power, 0); temp.digits.push_back(d); if (temp * o > reminder) { res.digits[power] = d - 1; temp.digits[power] = d - 1; reminder = reminder - temp * o; power--; break; } } } res.RemoveLeadingZeroes(); return res; } BigInteger operator+(const BigInteger& o) { BigInteger res; res.digits.resize(std::max(this->digits.size(), o.digits.size())); for (int i = 0; i < res.digits.size(); ++i) { res.digits[i] = this->GetDigit(i) + o.GetDigit(i); } res.HandleCarry(); return res; } BigInteger operator-(const BigInteger& o) { BigInteger res; res.digits.resize(std::max(this->digits.size(), o.digits.size())); for (int i = 0; i < res.digits.size(); ++i) { res.digits[i] = this->GetDigit(i) - o.GetDigit(i); } res.HandleNegativeCarry(); res.RemoveLeadingZeroes(); return res; } BigInteger operator*(const BigInteger& o) { BigInteger res; res.digits.resize(this->digits.size() + o.digits.size(), 0); for (int i = 0; i < this->digits.size(); ++i) { for (int j = 0; j < o.digits.size(); ++j) { res.digits[i + j] += this->digits[i] * o.digits[j]; } } res.HandleCarry(); res.RemoveLeadingZeroes(); return res; } bool operator==(const BigInteger& o) const{ if (o.digits.size() != this->digits.size()) return false; for (int i = 0; i < this->digits.size(); ++i) { if (o.digits[i] != this->digits[i]) return false; } return true; } bool operator!=(const BigInteger& o) const { return !(*this == o); } bool operator<(const BigInteger& o) const { if (this->digits.size() < o.digits.size()) return true; if (this->digits.size() > o.digits.size()) return false; for (int i = this->digits.size() - 1; i >= 0; --i) { if (this->digits[i] < o.digits[i]) return true; if (this->digits[i] > o.digits[i]) return false; } return false; } bool operator<=(const BigInteger& o) const{ return *this < o || *this == o; } bool operator>(const BigInteger& o) const{ return o < *this; } bool operator>=(const BigInteger& o) const{ return o <= *this; } friend std::ostream& operator<<(std::ostream& out, const BigInteger& num); private: void HandleCarry() { for (int i = 0; i < digits.size(); ++i) { int carry = digits[i] / 10; digits[i] %= 10; if (i == digits.size() - 1 && carry != 0) { digits.push_back(carry); } else { digits[i + 1] += carry; } } } void HandleNegativeCarry() { // TODO: this function doesn't work for negative numbers for (int i = 0; i < digits.size(); ++i) { if (digits[i] < 0) { digits[i] += 10; digits[i + 1]--; } } } void RemoveLeadingZeroes() { while (this->digits.size() > 1 && this->digits[this->digits.size() - 1] == 0) this->digits.pop_back(); } int GetDigit(int idx) const { if (idx < 0) throw std::exception(); // TODO if (idx > digits.size() - 1) return 0; return digits[idx]; } // Digits in base 10 // TODO: It is not very memory/cpu efficient // Little-Endian-ish std::vector<int> digits; }; std::ostream& operator<<(std::ostream& out, const BigInteger& num){ for (int i = num.digits.size() - 1; i >= 0; --i) { out << num.digits[i]; } return out; } int main() { BigInteger x = 1000000000; BigInteger y = 1000000000; std::cout << x << " " << y << std::endl; BigInteger z = x + y; std::cout << z << std::endl; BigInteger a = z + x + y; std::cout << a << std::endl; std::cout << (z == 42) << std::endl; std::cout << "NON-EQ test" << std::endl; std::cout << (z != 42) << std::endl; std::cout << "NON-EQ test ended" << std::endl; std::cout << (z < 42) << std::endl; std::cout << "TEST" << std::endl; std::cout << (z + z + 1 < z + z + 2) << std::endl; std::cout << "SUBTRACTION TEST" << std::endl; BigInteger q = 1700; std::cout << q - 18 << std::endl; std::cout << "DIVISION TEST" << std::endl; BigInteger d = 1280; std::cout << d / 14 << std::endl; } <commit_msg>Remove this-> (I've been writing too much code in python lately)<commit_after>#include <iostream> #include <vector> class BigInteger { public: BigInteger() : digits(1, 0) {} BigInteger(unsigned int x) { do { digits.push_back(x % 10); x /= 10; } while (x > 0); } BigInteger& operator++() { digits[0]++; HandleCarry(); return *this; } BigInteger operator++(int) { BigInteger copy(*this); ++copy; return copy; } BigInteger operator/(const BigInteger& o) { BigInteger res; BigInteger reminder(*this); int power = reminder.digits.size() - o.digits.size(); if (power <= 0) { return 0; } res.digits.resize(power + 1, 0); while (reminder > o) { for (int d = 1; d <= 10; ++d) { BigInteger temp; temp.digits.resize(power, 0); temp.digits.push_back(d); if (temp * o > reminder) { res.digits[power] = d - 1; temp.digits[power] = d - 1; reminder = reminder - temp * o; power--; break; } } } res.RemoveLeadingZeroes(); return res; } BigInteger operator+(const BigInteger& o) { BigInteger res; res.digits.resize(std::max(digits.size(), o.digits.size())); for (int i = 0; i < res.digits.size(); ++i) { res.digits[i] = GetDigit(i) + o.GetDigit(i); } res.HandleCarry(); return res; } BigInteger operator-(const BigInteger& o) { BigInteger res; res.digits.resize(std::max(digits.size(), o.digits.size())); for (int i = 0; i < res.digits.size(); ++i) { res.digits[i] = GetDigit(i) - o.GetDigit(i); } res.HandleNegativeCarry(); res.RemoveLeadingZeroes(); return res; } BigInteger operator*(const BigInteger& o) { BigInteger res; res.digits.resize(digits.size() + o.digits.size(), 0); for (int i = 0; i < digits.size(); ++i) { for (int j = 0; j < o.digits.size(); ++j) { res.digits[i + j] += digits[i] * o.digits[j]; } } res.HandleCarry(); res.RemoveLeadingZeroes(); return res; } bool operator==(const BigInteger& o) const{ if (o.digits.size() != digits.size()) return false; for (int i = 0; i < digits.size(); ++i) { if (o.digits[i] != digits[i]) return false; } return true; } bool operator!=(const BigInteger& o) const { return !(*this == o); } bool operator<(const BigInteger& o) const { if (digits.size() < o.digits.size()) return true; if (digits.size() > o.digits.size()) return false; for (int i = digits.size() - 1; i >= 0; --i) { if (digits[i] < o.digits[i]) return true; if (digits[i] > o.digits[i]) return false; } return false; } bool operator<=(const BigInteger& o) const{ return *this < o || *this == o; } bool operator>(const BigInteger& o) const{ return o < *this; } bool operator>=(const BigInteger& o) const{ return o <= *this; } friend std::ostream& operator<<(std::ostream& out, const BigInteger& num); private: void HandleCarry() { for (int i = 0; i < digits.size(); ++i) { int carry = digits[i] / 10; digits[i] %= 10; if (i == digits.size() - 1 && carry != 0) { digits.push_back(carry); } else { digits[i + 1] += carry; } } } void HandleNegativeCarry() { // TODO: this function doesn't work for negative numbers for (int i = 0; i < digits.size(); ++i) { if (digits[i] < 0) { digits[i] += 10; digits[i + 1]--; } } } void RemoveLeadingZeroes() { while (digits.size() > 1 && digits[digits.size() - 1] == 0) digits.pop_back(); } int GetDigit(int idx) const { if (idx < 0) throw std::exception(); // TODO if (idx > digits.size() - 1) return 0; return digits[idx]; } // Digits in base 10 // TODO: It is not very memory/cpu efficient // Little-Endian-ish std::vector<int> digits; }; std::ostream& operator<<(std::ostream& out, const BigInteger& num){ for (int i = num.digits.size() - 1; i >= 0; --i) { out << num.digits[i]; } return out; } int main() { BigInteger x = 1000000000; BigInteger y = 1000000000; std::cout << x << " " << y << std::endl; BigInteger z = x + y; std::cout << z << std::endl; BigInteger a = z + x + y; std::cout << a << std::endl; std::cout << (z == 42) << std::endl; std::cout << "NON-EQ test" << std::endl; std::cout << (z != 42) << std::endl; std::cout << "NON-EQ test ended" << std::endl; std::cout << (z < 42) << std::endl; std::cout << "TEST" << std::endl; std::cout << (z + z + 1 < z + z + 2) << std::endl; std::cout << "SUBTRACTION TEST" << std::endl; BigInteger q = 1700; std::cout << q - 18 << std::endl; std::cout << "DIVISION TEST" << std::endl; BigInteger d = 1280; std::cout << d / 14 << std::endl; } <|endoftext|>
<commit_before>#ifndef _EULERANGLESYAWPITCHROLL_H_ #define _EULERANGLESYAWPITCHROLL_H_ #include "RotationalKinematics.hpp" namespace sm { namespace kinematics { /** * @class EulerAnglesYawPitchRoll * This is the standard Rotation sequence for aerospace vehicles. * * Passing this the parameters [yaw, pitch, roll] of a vehicle frame, F_v, * with respect to an inertial frame, F_i, returns the rotation matrix, * C_iv, the rotation that takes vectors from F_v, to F_i. * * Similarly passing the rotation matrix C_iv to this class will cause * return the vector [heading, pitch, roll] where these represent the usual * meaning with respect to aerospace vehicles. * * heading: positive is vehicle nose left (counter clockwise). * pitch: positive is vehicle nose down. * roll: positive is left wing up. * */ class EulerAnglesYawPitchRoll : public RotationalKinematics { public: virtual ~EulerAnglesYawPitchRoll(); // Three functions that must be implemented. virtual Eigen::Matrix3d parametersToRotationMatrix(const Eigen::Vector3d & parameters, Eigen::Matrix3d * S = NULL) const; virtual Eigen::Vector3d rotationMatrixToParameters(const Eigen::Matrix3d & rotationMatrix) const; virtual Eigen::Matrix3d parametersToSMatrix(const Eigen::Vector3d & parameters) const; virtual Eigen::Vector3d angularVelocityAndJacobian(const Eigen::Vector3d & p, const Eigen::Vector3d & pdot, Eigen::Matrix<double,3,6> * Jacobian) const; private: // A helper function Eigen::Matrix3d buildSMatrix(double sz, double cz, double sy, double cy) const; }; }} // namespace sm::kinematics #endif /* _EULERANGLESYAWPITCHROLL_H_ */ <commit_msg>Added some comments to the yaw/pitch/roll file<commit_after>#ifndef _EULERANGLESYAWPITCHROLL_H_ #define _EULERANGLESYAWPITCHROLL_H_ #include "RotationalKinematics.hpp" namespace sm { namespace kinematics { /** * @class EulerAnglesYawPitchRoll * This is the standard Rotation sequence for aerospace vehicles. * * Passing this the parameters [yaw, pitch, roll] of a vehicle frame, F_v, * with respect to an inertial frame, F_i, returns the rotation matrix, * C_iv, the rotation that takes vectors from F_v, to F_i. * * Similarly passing the rotation matrix C_iv to this class will cause * return the vector [heading, pitch, roll] where these represent the usual * meaning with respect to aerospace vehicles. * * This assumes that the vehicle frame has: * x-axis pointing to the front. * y-axis pointing to the left. * z-axis pointing up. * * heading: positive is vehicle nose left (counter clockwise). * pitch: positive is vehicle nose down. * roll: positive is left wing up. * */ class EulerAnglesYawPitchRoll : public RotationalKinematics { public: virtual ~EulerAnglesYawPitchRoll(); // Three functions that must be implemented. virtual Eigen::Matrix3d parametersToRotationMatrix(const Eigen::Vector3d & parameters, Eigen::Matrix3d * S = NULL) const; virtual Eigen::Vector3d rotationMatrixToParameters(const Eigen::Matrix3d & rotationMatrix) const; virtual Eigen::Matrix3d parametersToSMatrix(const Eigen::Vector3d & parameters) const; virtual Eigen::Vector3d angularVelocityAndJacobian(const Eigen::Vector3d & p, const Eigen::Vector3d & pdot, Eigen::Matrix<double,3,6> * Jacobian) const; private: // A helper function Eigen::Matrix3d buildSMatrix(double sz, double cz, double sy, double cy) const; }; }} // namespace sm::kinematics #endif /* _EULERANGLESYAWPITCHROLL_H_ */ <|endoftext|>
<commit_before>/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2020 Martin Davis * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geom/Geometry.h> #include <geos/geom/Point.h> #include <geos/geom/LineString.h> #include <geos/geom/LinearRing.h> #include <geos/geom/Polygon.h> #include <geos/geom/GeometryCollection.h> #include <geos/geom/IntersectionMatrix.h> #include <geos/geom/PrecisionModel.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/prep/PreparedGeometry.h> #include <geos/geom/prep/PreparedGeometryFactory.h> #include <geos/operation/relate/RelateOp.h> #include <geos/operation/valid/MakeValid.h> #include <geos/operation/overlayng/OverlayNG.h> #include <geos/operation/polygonize/Polygonizer.h> #include <geos/precision/GeometryPrecisionReducer.h> #include "GeomFunction.h" #include <sstream> using geos::operation::overlayng::OverlayNG; /* static private */ std::map<std::string, GeomFunction*> GeomFunction::registry; static std::unique_ptr<const PreparedGeometry> prepGeomCache; static Geometry *cacheKey; /* static */ void GeomFunction::init() { add("area", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getArea() ); }); add("boundary", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getBoundary() ); }); add("buffer", "cmputes the buffer of geometry A", 1, 1, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->buffer( d ) ); }); add("centroid", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getCentroid() ); }); add("copy", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->clone() ); }); add("convexHull", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->convexHull() ); }); add("contains", "tests if geometry A contains geometry B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->contains( geomB.get() ) ); }); add("covers", "tests if geometry A covers geometry B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->covers( geomB.get() ) ); }); add("envelope", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getCentroid() ); }); add("interiorPoint", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getInteriorPoint() ); }); add("intersects", "tests if geometry A and B intersect", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->intersects( geomB.get() ) ); }); add("isValid", "tests if geometry A is valid", 1, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->isValid() ); }); add("length", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getLength() ); }); add("makeValid", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geos::operation::valid::MakeValid().build( geom.get() ) ); }); add("polygonize", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geos::operation::polygonize::Polygonizer p; p.add(geom.get()); auto polys = p.getPolygons(); std::vector<geom::Geometry*>* geoms = new std::vector<geom::Geometry*>; for(unsigned int i = 0; i < polys.size(); i++) { geoms->push_back(polys[i].release()); } auto factory = geom->getFactory(); Geometry * res = factory->createGeometryCollection(geoms); return new Result( res) ; }); add("containsPrep", "tests if geometry A contains geometry B, using PreparedGeometry", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { if (cacheKey == nullptr || cacheKey != geom.get()) { auto pg = std::unique_ptr<const PreparedGeometry>( PreparedGeometryFactory::prepare( geom.get()) ); prepGeomCache = std::move( pg ); cacheKey = geom.get(); } return new Result( prepGeomCache->contains( geomB.get() ) ); }); add("containsProperlyPrep", "tests if geometry A properly contains geometry B using PreparedGeometry", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { if (cacheKey == nullptr || cacheKey != geom.get()) { auto pg = std::unique_ptr<const PreparedGeometry>( PreparedGeometryFactory::prepare( geom.get()) ); prepGeomCache = std::move( pg ); cacheKey = geom.get(); } return new Result( prepGeomCache->containsProperly( geomB.get() ) ); }); add("coversPrep", "tests if geometry A covers geometry B using PreparedGeometry", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { if (cacheKey == nullptr || cacheKey != geom.get()) { auto pg = std::unique_ptr<const PreparedGeometry>( PreparedGeometryFactory::prepare( geom.get()) ); prepGeomCache = std::move( pg ); cacheKey = geom.get(); } return new Result( prepGeomCache->covers( geomB.get() ) ); }); add("intersectsPrep", "tests if geometry A intersects geometry B using PreparedGeometry", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { if (cacheKey == nullptr || cacheKey != geom.get()) { auto pg = std::unique_ptr<const PreparedGeometry>( PreparedGeometryFactory::prepare( geom.get()) ); prepGeomCache = std::move( pg ); cacheKey = geom.get(); } return new Result( prepGeomCache->intersects( geomB.get() ) ); }); add("reducePrecision", "reduces precision of geometry to a precision scale factor", 1, 1, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { PrecisionModel pm(d); return new Result( geos::precision::GeometryPrecisionReducer::reduce( *geom, pm ) ); }); add("relate", "computes DE-9IM matrix for geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { std::unique_ptr<geom::IntersectionMatrix> im(geom->relate( geomB.get() )); return new Result( im->toString() ); }); add("difference", "computes difference of geometry A from B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->difference( geomB.get() ) ); }); add("intersection", "computes intersection of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->intersection( geomB.get() ) ); }); add("symDifference", "computes symmetric difference of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->symDifference( geomB.get() ) ); }); add("unaryUnion", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->Union() ); }); add("union", "computes union of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->Union( geomB.get() ) ); }); add("differenceSR", "computes difference of geometry A from B rounding to a precision scale factor", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::DIFFERENCE, &pm) ); }); add("intersectionSR", "computes intersection of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::INTERSECTION, &pm) ); }); add("symDifferenceSR", "computes symmetric difference of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::SYMDIFFERENCE, &pm) ); }); add("unionSR", "computes union of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::UNION, &pm) ); }); } /* static */ GeomFunction* GeomFunction::find(std::string name) { if (registry.count(name) == 0) return nullptr; return registry[name]; } /* static */ void GeomFunction::add(std::string name, geomFunSig geomfun) { add(name, "computes " + name + " for geometry A", 1, 0, geomfun); } /* static */ void GeomFunction::add(std::string name, std::string desc, int nGeomParam, int nParam, geomFunSig geomfun) { auto fun = new GeomFunction(); fun->funName = name; fun->description = desc; fun->geomfun = geomfun; fun->numGeomParam = nGeomParam; fun->numParam = nParam; registry.insert( std::pair<std::string, GeomFunction *>(name, fun) ); } std::string GeomFunction::name() { return funName; } bool GeomFunction::isBinary() { return numGeomParam == 2; } std::string GeomFunction::signature() { std::string sig = funName + " A"; if (isBinary()) { sig += " B"; } if (numParam > 0) sig += " N"; return sig; } std::vector<std::string> GeomFunction::list() { std::vector<std::string> list; for (auto itr = registry.begin(); itr != registry.end(); ++itr) { auto fun = itr->second; auto desc = fun->signature() + " - " + fun->description; // TODO: add display of function signature list.push_back( desc ); } return list; } Result * GeomFunction::execute( const std::unique_ptr<Geometry>& geomA, const std::unique_ptr<Geometry>& geomB, double d ) { return geomfun( geomA, geomB, d ); } //=============================================== Result::Result(bool val) { valBool = val; typeCode = typeBool; } Result::Result(int val) { valInt = val; typeCode = typeInt; } Result::Result(double val) { valDouble = val; typeCode = typeDouble; } Result::Result(std::string val) { valStr = val; typeCode = typeString; } Result::Result(std::unique_ptr<geom::Geometry> val) { valGeom = std::move(val); typeCode = typeGeometry; } Result::Result(Geometry * val) { valGeom = std::unique_ptr<Geometry>(val); typeCode = typeGeometry; } Result::~Result() { } bool Result::isGeometry() { return typeCode == typeGeometry; } std::string Result::toString() { std::stringstream converter; switch (typeCode) { case typeBool: converter << std::boolalpha << valBool; return converter.str(); case typeInt: converter << valInt; return converter.str(); case typeDouble: converter << valDouble; return converter.str(); case typeString: return valStr; case typeGeometry: if (valGeom == nullptr) return "null"; return valGeom->toString(); } return "Value for Unknonwn type"; } std::string Result::metadata() { switch (typeCode) { case typeBool: return "bool"; case typeInt: return "int"; case typeDouble: return "double"; case typeString: return "string"; case typeGeometry: if (valGeom == nullptr) return "null"; return valGeom->getGeometryType() + "( " + std::to_string( valGeom->getNumPoints() ) + " )"; } return "Unknonwn type"; } <commit_msg>Add geosop distance and nearestPoints operations<commit_after>/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2020 Martin Davis * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geom/Geometry.h> #include <geos/geom/Point.h> #include <geos/geom/LineString.h> #include <geos/geom/LinearRing.h> #include <geos/geom/Polygon.h> #include <geos/geom/GeometryCollection.h> #include <geos/geom/IntersectionMatrix.h> #include <geos/geom/PrecisionModel.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/prep/PreparedGeometry.h> #include <geos/geom/prep/PreparedGeometryFactory.h> #include <geos/operation/distance/DistanceOp.h> #include <geos/operation/relate/RelateOp.h> #include <geos/operation/valid/MakeValid.h> #include <geos/operation/overlayng/OverlayNG.h> #include <geos/operation/polygonize/Polygonizer.h> #include <geos/precision/GeometryPrecisionReducer.h> #include "GeomFunction.h" #include <sstream> using geos::operation::overlayng::OverlayNG; /* static private */ std::map<std::string, GeomFunction*> GeomFunction::registry; static std::unique_ptr<const PreparedGeometry> prepGeomCache; static Geometry *cacheKey; /* static */ void GeomFunction::init() { add("area", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getArea() ); }); add("boundary", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getBoundary() ); }); add("buffer", "cmputes the buffer of geometry A", 1, 1, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->buffer( d ) ); }); add("centroid", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getCentroid() ); }); add("copy", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->clone() ); }); add("convexHull", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->convexHull() ); }); add("contains", "tests if geometry A contains geometry B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->contains( geomB.get() ) ); }); add("covers", "tests if geometry A covers geometry B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->covers( geomB.get() ) ); }); add("distance", "computes distance between geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->distance( geomB.get() ) ); }); add("envelope", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getCentroid() ); }); add("interiorPoint", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getInteriorPoint() ); }); add("intersects", "tests if geometry A and B intersect", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->intersects( geomB.get() ) ); }); add("isValid", "tests if geometry A is valid", 1, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->isValid() ); }); add("length", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->getLength() ); }); add("makeValid", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geos::operation::valid::MakeValid().build( geom.get() ) ); }); add("nearestPoints", "computes nearest points of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { std::unique_ptr<CoordinateSequence> cs = geos::operation::distance::DistanceOp::nearestPoints(geom.get(), geomB.get()); auto factory = geom->getFactory(); auto res = factory->createLineString( std::move(cs) ); return new Result( std::move(res) ); }); add("polygonize", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geos::operation::polygonize::Polygonizer p; p.add(geom.get()); auto polys = p.getPolygons(); std::vector<geom::Geometry*>* geoms = new std::vector<geom::Geometry*>; for(unsigned int i = 0; i < polys.size(); i++) { geoms->push_back(polys[i].release()); } auto factory = geom->getFactory(); Geometry * res = factory->createGeometryCollection(geoms); return new Result( res) ; }); add("containsPrep", "tests if geometry A contains geometry B, using PreparedGeometry", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { if (cacheKey == nullptr || cacheKey != geom.get()) { auto pg = std::unique_ptr<const PreparedGeometry>( PreparedGeometryFactory::prepare( geom.get()) ); prepGeomCache = std::move( pg ); cacheKey = geom.get(); } return new Result( prepGeomCache->contains( geomB.get() ) ); }); add("containsProperlyPrep", "tests if geometry A properly contains geometry B using PreparedGeometry", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { if (cacheKey == nullptr || cacheKey != geom.get()) { auto pg = std::unique_ptr<const PreparedGeometry>( PreparedGeometryFactory::prepare( geom.get()) ); prepGeomCache = std::move( pg ); cacheKey = geom.get(); } return new Result( prepGeomCache->containsProperly( geomB.get() ) ); }); add("coversPrep", "tests if geometry A covers geometry B using PreparedGeometry", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { if (cacheKey == nullptr || cacheKey != geom.get()) { auto pg = std::unique_ptr<const PreparedGeometry>( PreparedGeometryFactory::prepare( geom.get()) ); prepGeomCache = std::move( pg ); cacheKey = geom.get(); } return new Result( prepGeomCache->covers( geomB.get() ) ); }); add("intersectsPrep", "tests if geometry A intersects B using PreparedGeometry", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { if (cacheKey == nullptr || cacheKey != geom.get()) { auto pg = std::unique_ptr<const PreparedGeometry>( PreparedGeometryFactory::prepare( geom.get()) ); prepGeomCache = std::move( pg ); cacheKey = geom.get(); } return new Result( prepGeomCache->intersects( geomB.get() ) ); }); add("distancePrep", "computes distance between geometry A and B using PreparedGeometry", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { if (cacheKey == nullptr || cacheKey != geom.get()) { auto pg = std::unique_ptr<const PreparedGeometry>( PreparedGeometryFactory::prepare( geom.get()) ); prepGeomCache = std::move( pg ); cacheKey = geom.get(); } return new Result( prepGeomCache->distance( geomB.get() ) ); }); add("nearestPointsPrep", "computes nearest points of geometry A and B using PreparedGeometry", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { if (cacheKey == nullptr || cacheKey != geom.get()) { auto pg = std::unique_ptr<const PreparedGeometry>( PreparedGeometryFactory::prepare( geom.get()) ); prepGeomCache = std::move( pg ); cacheKey = geom.get(); } auto cs = prepGeomCache->nearestPoints( geomB.get() ); auto factory = geom->getFactory(); auto res = factory->createLineString( std::move(cs) ); return new Result( std::move(res) ); }); add("reducePrecision", "reduces precision of geometry to a precision scale factor", 1, 1, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { PrecisionModel pm(d); return new Result( geos::precision::GeometryPrecisionReducer::reduce( *geom, pm ) ); }); add("relate", "computes DE-9IM matrix for geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { std::unique_ptr<geom::IntersectionMatrix> im(geom->relate( geomB.get() )); return new Result( im->toString() ); }); add("difference", "computes difference of geometry A from B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->difference( geomB.get() ) ); }); add("intersection", "computes intersection of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->intersection( geomB.get() ) ); }); add("symDifference", "computes symmetric difference of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->symDifference( geomB.get() ) ); }); add("unaryUnion", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->Union() ); }); add("union", "computes union of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { return new Result( geom->Union( geomB.get() ) ); }); add("differenceSR", "computes difference of geometry A from B rounding to a precision scale factor", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::DIFFERENCE, &pm) ); }); add("intersectionSR", "computes intersection of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::INTERSECTION, &pm) ); }); add("symDifferenceSR", "computes symmetric difference of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::SYMDIFFERENCE, &pm) ); }); add("unionSR", "computes union of geometry A and B", 2, 0, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::UNION, &pm) ); }); } /* static */ GeomFunction* GeomFunction::find(std::string name) { if (registry.count(name) == 0) return nullptr; return registry[name]; } /* static */ void GeomFunction::add(std::string name, geomFunSig geomfun) { add(name, "computes " + name + " for geometry A", 1, 0, geomfun); } /* static */ void GeomFunction::add(std::string name, std::string desc, int nGeomParam, int nParam, geomFunSig geomfun) { auto fun = new GeomFunction(); fun->funName = name; fun->description = desc; fun->geomfun = geomfun; fun->numGeomParam = nGeomParam; fun->numParam = nParam; registry.insert( std::pair<std::string, GeomFunction *>(name, fun) ); } std::string GeomFunction::name() { return funName; } bool GeomFunction::isBinary() { return numGeomParam == 2; } std::string GeomFunction::signature() { std::string sig = funName + " A"; if (isBinary()) { sig += " B"; } if (numParam > 0) sig += " N"; return sig; } std::vector<std::string> GeomFunction::list() { std::vector<std::string> list; for (auto itr = registry.begin(); itr != registry.end(); ++itr) { auto fun = itr->second; auto desc = fun->signature() + " - " + fun->description; // TODO: add display of function signature list.push_back( desc ); } return list; } Result * GeomFunction::execute( const std::unique_ptr<Geometry>& geomA, const std::unique_ptr<Geometry>& geomB, double d ) { return geomfun( geomA, geomB, d ); } //=============================================== Result::Result(bool val) { valBool = val; typeCode = typeBool; } Result::Result(int val) { valInt = val; typeCode = typeInt; } Result::Result(double val) { valDouble = val; typeCode = typeDouble; } Result::Result(std::string val) { valStr = val; typeCode = typeString; } Result::Result(std::unique_ptr<geom::Geometry> val) { valGeom = std::move(val); typeCode = typeGeometry; } Result::Result(Geometry * val) { valGeom = std::unique_ptr<Geometry>(val); typeCode = typeGeometry; } Result::~Result() { } bool Result::isGeometry() { return typeCode == typeGeometry; } std::string Result::toString() { std::stringstream converter; switch (typeCode) { case typeBool: converter << std::boolalpha << valBool; return converter.str(); case typeInt: converter << valInt; return converter.str(); case typeDouble: converter << valDouble; return converter.str(); case typeString: return valStr; case typeGeometry: if (valGeom == nullptr) return "null"; return valGeom->toString(); } return "Value for Unknonwn type"; } std::string Result::metadata() { switch (typeCode) { case typeBool: return "bool"; case typeInt: return "int"; case typeDouble: return "double"; case typeString: return "string"; case typeGeometry: if (valGeom == nullptr) return "null"; return valGeom->getGeometryType() + "( " + std::to_string( valGeom->getNumPoints() ) + " )"; } return "Unknonwn type"; } <|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: timenode.hxx,v $ * $Revision: 1.3 $ * * 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 OOX_DRAWINGML_TIMENODE_HXX #define OOX_DRAWINGML_TIMENODE_HXX #include <boost/shared_ptr.hpp> #include <vector> #include <list> #include <rtl/ustring.hxx> #include <com/sun/star/frame/XModel.hpp> #include <com/sun/star/animations/XAnimationNode.hpp> #include "oox/helper/propertymap.hxx" #include "oox/ppt/slidetransition.hxx" #include "oox/ppt/slidepersist.hxx" #include "oox/ppt/animationspersist.hxx" #include "oox/ppt/timenode.hxx" namespace oox { namespace ppt { class TimeNode; class SlideTransition; typedef boost::shared_ptr< TimeNode > TimeNodePtr; typedef ::std::list< TimeNodePtr > TimeNodePtrList; class TimeNode { public: TimeNode( sal_Int16 nNodeType ); virtual ~TimeNode(); NodePropertyMap & getNodeProperties() { return maNodeProperties; } PropertyMap & getUserData() { return maUserData; } void addChild( const TimeNodePtr & pChildPtr ) { maChilds.push_back( pChildPtr ); } TimeNodePtrList & getChilds() { return maChilds; } void setId( sal_Int32 nId ); const ::rtl::OUString & getId() const { return msId; } void addNode( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > &rxModel, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& rxNode, const SlidePersistPtr & slide); // data setters void setTo( const ::com::sun::star::uno::Any & aTo ); void setFrom( const ::com::sun::star::uno::Any & aFrom ); void setBy( const ::com::sun::star::uno::Any & aBy ); void setTransitionFilter( const SlideTransition & aTransition) { maTransitionFilter = aTransition; } void setNode( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > &rxModel, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode, const SlidePersistPtr & pSlide ); AnimTargetElementPtr getTarget() { if( !mpTarget ) mpTarget.reset( new AnimTargetElement ); return mpTarget; } AnimationConditionList &getStartCondition() { return maStCondList; } AnimationConditionList &getEndCondition() { return maEndCondList; } AnimationConditionList &getNextCondition() { return maNextCondList; } AnimationConditionList &getPrevCondition() { return maPrevCondList; } AnimationCondition & getEndSyncValue() { mbHasEndSyncValue = true; return maEndSyncValue; } protected: static rtl::OUString getServiceName( sal_Int16 nNodeType ); ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > createAndInsert( const rtl::OUString& rServiceName, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > &rxModel, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& rxNode ); private: const sal_Int16 mnNodeType; TimeNodePtrList maChilds; rtl::OUString msId; NodePropertyMap maNodeProperties; PropertyMap maUserData; // a sequence to be stored as "UserData" property SlideTransition maTransitionFilter; AnimTargetElementPtr mpTarget; bool mbHasEndSyncValue; // set to true if we try to get the endSync. AnimationCondition maEndSyncValue; AnimationConditionList maStCondList, maEndCondList; AnimationConditionList maPrevCondList, maNextCondList; }; } } #endif <commit_msg>INTEGRATION: CWS xmlfilter06 (1.3.8); FILE MERGED 2008/06/06 16:27:52 dr 1.3.8.1: chart formatting: builtin line/fill/effect styles, manual line formatting<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: timenode.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef OOX_DRAWINGML_TIMENODE_HXX #define OOX_DRAWINGML_TIMENODE_HXX #include <boost/shared_ptr.hpp> #include <vector> #include <list> #include <rtl/ustring.hxx> #include <com/sun/star/frame/XModel.hpp> #include <com/sun/star/animations/XAnimationNode.hpp> #include "oox/helper/propertymap.hxx" #include "oox/ppt/slidetransition.hxx" #include "oox/ppt/slidepersist.hxx" #include "oox/ppt/animationspersist.hxx" #include "oox/ppt/timenode.hxx" namespace oox { namespace ppt { class TimeNode; class SlideTransition; typedef boost::shared_ptr< TimeNode > TimeNodePtr; typedef ::std::list< TimeNodePtr > TimeNodePtrList; class TimeNode { public: TimeNode( sal_Int16 nNodeType ); virtual ~TimeNode(); NodePropertyMap & getNodeProperties() { return maNodeProperties; } PropertyMap & getUserData() { return maUserData; } void addChild( const TimeNodePtr & pChildPtr ) { maChildren.push_back( pChildPtr ); } TimeNodePtrList & getChildren() { return maChildren; } void setId( sal_Int32 nId ); const ::rtl::OUString & getId() const { return msId; } void addNode( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > &rxModel, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& rxNode, const SlidePersistPtr & slide); // data setters void setTo( const ::com::sun::star::uno::Any & aTo ); void setFrom( const ::com::sun::star::uno::Any & aFrom ); void setBy( const ::com::sun::star::uno::Any & aBy ); void setTransitionFilter( const SlideTransition & aTransition) { maTransitionFilter = aTransition; } void setNode( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > &rxModel, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xNode, const SlidePersistPtr & pSlide ); AnimTargetElementPtr getTarget() { if( !mpTarget ) mpTarget.reset( new AnimTargetElement ); return mpTarget; } AnimationConditionList &getStartCondition() { return maStCondList; } AnimationConditionList &getEndCondition() { return maEndCondList; } AnimationConditionList &getNextCondition() { return maNextCondList; } AnimationConditionList &getPrevCondition() { return maPrevCondList; } AnimationCondition & getEndSyncValue() { mbHasEndSyncValue = true; return maEndSyncValue; } protected: static rtl::OUString getServiceName( sal_Int16 nNodeType ); ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > createAndInsert( const rtl::OUString& rServiceName, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > &rxModel, const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& rxNode ); private: const sal_Int16 mnNodeType; TimeNodePtrList maChildren; rtl::OUString msId; NodePropertyMap maNodeProperties; PropertyMap maUserData; // a sequence to be stored as "UserData" property SlideTransition maTransitionFilter; AnimTargetElementPtr mpTarget; bool mbHasEndSyncValue; // set to true if we try to get the endSync. AnimationCondition maEndSyncValue; AnimationConditionList maStCondList, maEndCondList; AnimationConditionList maPrevCondList, maNextCondList; }; } } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Samsung Electronics Co., 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. */ /* * @file Cynara.cpp * @author Lukasz Wojciechowski <[email protected]> * @version 1.0 * @brief This file implements main class of cynara service */ #include <memory> #include <stddef.h> #include <exceptions/InitException.h> #include <logic/Logic.h> #include <sockets/SocketManager.h> #include <storage/InMemoryStorageBackend.h> #include <storage/Storage.h> #include <storage/StorageBackend.h> #include "Cynara.h" namespace Cynara { Cynara::Cynara() : m_logic(nullptr), m_socketManager(nullptr), m_storage(nullptr), m_storageBackend(nullptr) { } Cynara::~Cynara() { finalize(); } void Cynara::init(void) { m_logic = std::make_shared<Logic>(); m_socketManager = std::make_shared<SocketManager>(); m_storageBackend = std::make_shared<InMemoryStorageBackend>(); m_storage = std::make_shared<Storage>(*m_storageBackend); m_logic->bindStorage(m_storage); m_logic->bindSocketManager(m_socketManager); m_socketManager->bindLogic(m_logic); } void Cynara::run(void) { m_socketManager->run(); } void Cynara::finalize(void) { m_logic->unbindAll(); m_socketManager->unbindAll(); m_logic.reset(); m_socketManager.reset(); m_storageBackend.reset(); m_storage.reset(); } } // namespace Cynara <commit_msg>Fix shared pointers access in Cynara class<commit_after>/* * Copyright (c) 2014 Samsung Electronics Co., 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. */ /* * @file Cynara.cpp * @author Lukasz Wojciechowski <[email protected]> * @version 1.0 * @brief This file implements main class of cynara service */ #include <memory> #include <stddef.h> #include <exceptions/InitException.h> #include <logic/Logic.h> #include <sockets/SocketManager.h> #include <storage/InMemoryStorageBackend.h> #include <storage/Storage.h> #include <storage/StorageBackend.h> #include "Cynara.h" namespace Cynara { Cynara::Cynara() : m_logic(nullptr), m_socketManager(nullptr), m_storage(nullptr), m_storageBackend(nullptr) { } Cynara::~Cynara() { finalize(); } void Cynara::init(void) { m_logic = std::make_shared<Logic>(); m_socketManager = std::make_shared<SocketManager>(); m_storageBackend = std::make_shared<InMemoryStorageBackend>(); m_storage = std::make_shared<Storage>(*m_storageBackend); m_logic->bindStorage(m_storage); m_logic->bindSocketManager(m_socketManager); m_socketManager->bindLogic(m_logic); } void Cynara::run(void) { if (!m_socketManager) { throw InitException(); } m_socketManager->run(); } void Cynara::finalize(void) { if (m_logic) { m_logic->unbindAll(); } if (m_socketManager) { m_socketManager->unbindAll(); } m_logic.reset(); m_socketManager.reset(); m_storageBackend.reset(); m_storage.reset(); } } // namespace Cynara <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details. * Copyright (C) 2013 Rasmus Eskola <[email protected]> * based on sample.cpp sample module code * * 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 <znc/FileUtils.h> #include <znc/Client.h> #include <znc/Chan.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Modules.h> #include <dirent.h> #include <vector> #include <algorithm> class CBacklogMod : public CModule { public: MODCONSTRUCTOR(CBacklogMod) {} virtual bool OnLoad(const CString& sArgs, CString& sMessage); virtual ~CBacklogMod(); virtual void OnModCommand(const CString& sCommand); private: bool inChan(const CString& Chan); }; bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) { CString LogPath = sArgs; if(LogPath.empty()) { LogPath = GetNV("LogPath"); if(LogPath.empty()) { // TODO: guess logpath? PutModule("LogPath is empty, set it with the LogPath command (help for more info)"); } } else { SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); } return true; } CBacklogMod::~CBacklogMod() { } void CBacklogMod::OnModCommand(const CString& sCommand) { CString Arg = sCommand.Token(1); if (sCommand.Token(0).Equals("help")) { // TODO: proper help text, look how AddHelpCommand() does it in other ZNC code PutModule("Usage:"); PutModule("<window-name> [num-lines] (e.g. #foo 42)"); PutModule(""); PutModule("Commands:"); PutModule("Help (print this text)"); PutModule("LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date)"); PutModule("PrintStatusMsgs true/false (print join/part/rename messages)"); return; } else if (sCommand.Token(0).Equals("logpath")) { if(Arg.empty()) { PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date:)"); PutModule("Current LogPath is set to: " + GetNV("LogPath")); return; } CString LogPath = sCommand.Token(1, true); SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); return; } else if (sCommand.Token(0).Equals("PrintStatusMsgs")) { if(Arg.empty() || (!Arg.Equals("true", true) && !Arg.Equals("false", true))) { PutModule("Usage: PrintStatusMsgs true/false"); return; } SetNV("PrintStatusMsgs", Arg); PutModule("PrintStatusMsgs set to: " + Arg); return; } // TODO: handle these differently depending on how the module was loaded CString User = (m_pUser ? m_pUser->GetUserName() : "UNKNOWN"); CString Network = (m_pNetwork ? m_pNetwork->GetName() : "znc"); CString Channel = sCommand.Token(0); int printedLines = 0; int reqLines = sCommand.Token(1).ToInt(); if(reqLines <= 0) { reqLines = 150; } reqLines = std::max(std::min(reqLines, 1000), 1); CString Path = GetNV("LogPath").substr(); // make copy Path.Replace("$NETWORK", Network); Path.Replace("$WINDOW", Channel); Path.Replace("$USER", User); CString DirPath = Path.substr(0, Path.find_last_of("/")); CString FilePath; std::vector<CString> FileList; std::vector<CString> LinesToPrint; // gather list of all log files for requested channel/window DIR *dir; struct dirent *ent; if ((dir = opendir (DirPath.c_str())) != NULL) { while ((ent = readdir (dir)) != NULL) { FilePath = DirPath + "/" + ent->d_name; //PutModule("DEBUG: " + FilePath + " " + Path); if(FilePath.AsLower().StrCmp(Path.AsLower(), Path.find_last_of("*")) == 0) { FileList.push_back(FilePath); } } closedir (dir); } else { PutModule("Could not list directory " + DirPath + ": " + strerror(errno)); return; } std::sort(FileList.begin(), FileList.end()); // loop through list of log files one by one starting from most recent... for (std::vector<CString>::reverse_iterator it = FileList.rbegin(); it != FileList.rend(); ++it) { CFile LogFile(*it); CString Line; std::vector<CString> Lines; if (LogFile.Open()) { while (LogFile.ReadLine(Line)) { try { // is line a part/join/rename etc message (nick ***), do we want to print it? // find nick by finding first whitespace, then moving one char right if(Line.at(Line.find_first_of(' ') + 1) == '*' && !GetNV("PrintStatusMsgs").ToBool()) { continue; } Lines.push_back(Line); } catch (int e) { // malformed log line, ignore PutModule("Malformed log line found in " + *it + ": " + Line); } } } else { PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno)); continue; } LogFile.Close(); // loop through Lines in reverse order, push to LinesToPrint for (std::vector<CString>::reverse_iterator itl = Lines.rbegin(); itl != Lines.rend(); ++itl) { LinesToPrint.push_back(*itl); printedLines++; if(printedLines >= reqLines) { break; } } if(printedLines >= reqLines) { break; } } if(printedLines == 0) { PutModule("No log files found for window " + Channel + " in " + DirPath + "/"); return; } else { m_pNetwork->PutUser(":***[email protected] PRIVMSG " + Channel + " :Backlog playback...", GetClient()); } // now actually print for (std::vector<CString>::reverse_iterator it = LinesToPrint.rbegin(); it != LinesToPrint.rend(); ++it) { CString Line = *it; size_t FirstWS = Line.find_first_of(' '); // position of first whitespace char in line size_t NickLen = 3; CString Nick = "***"; try { // a log line looks like: [HH:MM:SS] <Nick> Message // < and > are illegal characters in nicknames, so we can // search for these if(Line.at(FirstWS + 1) == '<') { // normal message // nicklen includes surrounding < > NickLen = Line.find_first_of('>') - Line.find_first_of('<') + 1; // but we don't want them in Nick so subtract by two Nick = Line.substr(FirstWS + 2, NickLen - 2); } m_pNetwork->PutUser(":" + Nick + "[email protected] PRIVMSG " + Channel + " :" + Line.substr(0, FirstWS) + Line.substr(FirstWS + NickLen + 1, Line.npos), GetClient()); } catch (int e) { PutModule("Malformed log line! " + Line); } } m_pNetwork->PutUser(":***[email protected] PRIVMSG " + Channel + " :" + "Playback Complete.", GetClient()); } bool CBacklogMod::inChan(const CString& Chan) { const std::vector <CChan*>& vChans (m_pNetwork->GetChans()); for (std::vector<CChan*>::const_iterator it = vChans.begin(); it != vChans.end(); ++it) { CChan *curChan = *it; if(Chan.StrCmp(curChan->GetName()) == 0) { return true; } } return false; } template<> void TModInfo<CBacklogMod>(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetWikiPage("backlog"); Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW"); Info.SetHasArgs(true); } NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.") <commit_msg>get rid of unnecessary function<commit_after>/* * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details. * Copyright (C) 2013 Rasmus Eskola <[email protected]> * based on sample.cpp sample module code * * 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 <znc/FileUtils.h> #include <znc/Client.h> #include <znc/Chan.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Modules.h> #include <dirent.h> #include <vector> #include <algorithm> class CBacklogMod : public CModule { public: MODCONSTRUCTOR(CBacklogMod) {} virtual bool OnLoad(const CString& sArgs, CString& sMessage); virtual ~CBacklogMod(); virtual void OnModCommand(const CString& sCommand); }; bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) { CString LogPath = sArgs; if(LogPath.empty()) { LogPath = GetNV("LogPath"); if(LogPath.empty()) { // TODO: guess logpath? PutModule("LogPath is empty, set it with the LogPath command (help for more info)"); } } else { SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); } return true; } CBacklogMod::~CBacklogMod() { } void CBacklogMod::OnModCommand(const CString& sCommand) { CString Arg = sCommand.Token(1); if (sCommand.Token(0).Equals("help")) { // TODO: proper help text, look how AddHelpCommand() does it in other ZNC code PutModule("Usage:"); PutModule("<window-name> [num-lines] (e.g. #foo 42)"); PutModule(""); PutModule("Commands:"); PutModule("Help (print this text)"); PutModule("LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date)"); PutModule("PrintStatusMsgs true/false (print join/part/rename messages)"); return; } else if (sCommand.Token(0).Equals("logpath")) { if(Arg.empty()) { PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date:)"); PutModule("Current LogPath is set to: " + GetNV("LogPath")); return; } CString LogPath = sCommand.Token(1, true); SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); return; } else if (sCommand.Token(0).Equals("PrintStatusMsgs")) { if(Arg.empty() || (!Arg.Equals("true", true) && !Arg.Equals("false", true))) { PutModule("Usage: PrintStatusMsgs true/false"); return; } SetNV("PrintStatusMsgs", Arg); PutModule("PrintStatusMsgs set to: " + Arg); return; } // TODO: handle these differently depending on how the module was loaded CString User = (m_pUser ? m_pUser->GetUserName() : "UNKNOWN"); CString Network = (m_pNetwork ? m_pNetwork->GetName() : "znc"); CString Channel = sCommand.Token(0); int printedLines = 0; int reqLines = sCommand.Token(1).ToInt(); if(reqLines <= 0) { reqLines = 150; } reqLines = std::max(std::min(reqLines, 1000), 1); CString Path = GetNV("LogPath").substr(); // make copy Path.Replace("$NETWORK", Network); Path.Replace("$WINDOW", Channel); Path.Replace("$USER", User); CString DirPath = Path.substr(0, Path.find_last_of("/")); CString FilePath; std::vector<CString> FileList; std::vector<CString> LinesToPrint; // gather list of all log files for requested channel/window DIR *dir; struct dirent *ent; if ((dir = opendir (DirPath.c_str())) != NULL) { while ((ent = readdir (dir)) != NULL) { FilePath = DirPath + "/" + ent->d_name; //PutModule("DEBUG: " + FilePath + " " + Path); if(FilePath.AsLower().StrCmp(Path.AsLower(), Path.find_last_of("*")) == 0) { FileList.push_back(FilePath); } } closedir (dir); } else { PutModule("Could not list directory " + DirPath + ": " + strerror(errno)); return; } std::sort(FileList.begin(), FileList.end()); // loop through list of log files one by one starting from most recent... for (std::vector<CString>::reverse_iterator it = FileList.rbegin(); it != FileList.rend(); ++it) { CFile LogFile(*it); CString Line; std::vector<CString> Lines; if (LogFile.Open()) { while (LogFile.ReadLine(Line)) { try { // is line a part/join/rename etc message (nick ***), do we want to print it? // find nick by finding first whitespace, then moving one char right if(Line.at(Line.find_first_of(' ') + 1) == '*' && !GetNV("PrintStatusMsgs").ToBool()) { continue; } Lines.push_back(Line); } catch (int e) { // malformed log line, ignore PutModule("Malformed log line found in " + *it + ": " + Line); } } } else { PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno)); continue; } LogFile.Close(); // loop through Lines in reverse order, push to LinesToPrint for (std::vector<CString>::reverse_iterator itl = Lines.rbegin(); itl != Lines.rend(); ++itl) { LinesToPrint.push_back(*itl); printedLines++; if(printedLines >= reqLines) { break; } } if(printedLines >= reqLines) { break; } } if(printedLines == 0) { PutModule("No log files found for window " + Channel + " in " + DirPath + "/"); return; } else { m_pNetwork->PutUser(":***[email protected] PRIVMSG " + Channel + " :Backlog playback...", GetClient()); } // now actually print for (std::vector<CString>::reverse_iterator it = LinesToPrint.rbegin(); it != LinesToPrint.rend(); ++it) { CString Line = *it; size_t FirstWS = Line.find_first_of(' '); // position of first whitespace char in line size_t NickLen = 3; CString Nick = "***"; try { // a log line looks like: [HH:MM:SS] <Nick> Message // < and > are illegal characters in nicknames, so we can // search for these if(Line.at(FirstWS + 1) == '<') { // normal message // nicklen includes surrounding < > NickLen = Line.find_first_of('>') - Line.find_first_of('<') + 1; // but we don't want them in Nick so subtract by two Nick = Line.substr(FirstWS + 2, NickLen - 2); } m_pNetwork->PutUser(":" + Nick + "[email protected] PRIVMSG " + Channel + " :" + Line.substr(0, FirstWS) + Line.substr(FirstWS + NickLen + 1, Line.npos), GetClient()); } catch (int e) { PutModule("Malformed log line! " + Line); } } m_pNetwork->PutUser(":***[email protected] PRIVMSG " + Channel + " :" + "Playback Complete.", GetClient()); } template<> void TModInfo<CBacklogMod>(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetWikiPage("backlog"); Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW"); Info.SetHasArgs(true); } NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.") <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // FIXME: This file shall contain the decl of cling::Jupyter in a future // revision! //#include "cling/Interpreter/Jupyter/Kernel.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include "cling/MetaProcessor/MetaProcessor.h" #include "cling/Utils/Output.h" #include "llvm/Support/raw_ostream.h" #include <map> #include <string> #include <cstring> #ifndef LLVM_ON_WIN32 # include <unistd.h> #else # include <io.h> # define write _write #endif // FIXME: should be moved into a Jupyter interp struct that then gets returned // from create. int pipeToJupyterFD = -1; namespace cling { namespace Jupyter { struct MIMEDataRef { const char* m_Data; const long m_Size; MIMEDataRef(const std::string& str): m_Data(str.c_str()), m_Size((long)str.length() + 1) {} MIMEDataRef(const char* str): MIMEDataRef(std::string(str)) {} MIMEDataRef(const char* data, long size): m_Data(data), m_Size(size) {} }; /// Push MIME stuff to Jupyter. To be called from user code. ///\param contentDict - dictionary of MIME type versus content. E.g. /// {{"text/html", {"<div></div>", }} ///\returns `false` if the output could not be sent. bool pushOutput(const std::map<std::string, MIMEDataRef> contentDict) { // Pipe sees (all numbers are longs, except for the first: // - num bytes in a long (sent as a single unsigned char!) // - num elements of the MIME dictionary; Jupyter selects one to display. // For each MIME dictionary element: // - size of MIME type string (including the terminating 0) // - MIME type as 0-terminated string // - size of MIME data buffer (including the terminating 0 for // 0-terminated strings) // - MIME data buffer // Write number of dictionary elements (and the size of that number in a // char) unsigned char sizeLong = sizeof(long); if (write(pipeToJupyterFD, &sizeLong, 1) != 1) return false; long dictSize = contentDict.size(); if (write(pipeToJupyterFD, &dictSize, sizeof(long)) != sizeof(long)) return false; for (auto iContent: contentDict) { const std::string& mimeType = iContent.first; long mimeTypeSize = (long)mimeType.size(); if (write(pipeToJupyterFD, &mimeTypeSize, sizeof(long)) != sizeof(long)) return false; if (write(pipeToJupyterFD, mimeType.c_str(), mimeType.size() + 1) != (long)(mimeType.size() + 1)) return false; const MIMEDataRef& mimeData = iContent.second; if (write(pipeToJupyterFD, &mimeData.m_Size, sizeof(long)) != sizeof(long)) return false; if (write(pipeToJupyterFD, mimeData.m_Data, mimeData.m_Size) != mimeData.m_Size) return false; } return true; } } // namespace Jupyter } // namespace cling extern "C" { ///\{ ///\name Cling4CTypes /// The Python compatible view of cling /// The MetaProcessor cast to void* using TheMetaProcessor = void; /// Create an interpreter object. TheMetaProcessor* cling_create(int argc, const char *argv[], const char* llvmdir, int pipefd) { pipeToJupyterFD = pipefd; auto I = new cling::Interpreter(argc, argv, llvmdir); return new cling::MetaProcessor(*I, cling::errs()); } /// Destroy the interpreter. void cling_destroy(TheMetaProcessor *metaProc) { cling::MetaProcessor *M = (cling::MetaProcessor*)metaProc; cling::Interpreter *I = const_cast<cling::Interpreter*>(&M->getInterpreter()); delete M; delete I; } /// Stringify a cling::Value static std::string ValueToString(const cling::Value& V) { std::string valueString; { llvm::raw_string_ostream os(valueString); V.print(os); } return valueString; } /// Evaluate a string of code. Returns nullptr on failure. /// Returns a string representation of the expression (can be "") on success. char* cling_eval(TheMetaProcessor *metaProc, const char *code) { cling::MetaProcessor *M = (cling::MetaProcessor*)metaProc; cling::Value V; cling::Interpreter::CompilationResult Res; if (M->process(code, Res, &V)) { cling::Jupyter::pushOutput({{"text/html", "Incomplete input! Ignored."}}); M->cancelContinuation(); return nullptr; } if (Res != cling::Interpreter::kSuccess) return nullptr; if (!V.isValid()) return strdup(""); return strdup(ValueToString(V).c_str()); } void cling_eval_free(char* str) { free(str); } /// Code completion interfaces. /// Start completion of code. Returns a handle to be passed to /// cling_complete_next() to iterate over the completion options. Returns nulptr /// if no completions are known. void* cling_complete_start(const char* code) { return new int(42); } /// Grab the next completion of some code. Returns nullptr if none is left. const char* cling_complete_next(void* completionHandle) { int* counter = (int*) completionHandle; if (++(*counter) > 43) { delete counter; return nullptr; } return "COMPLETE!"; } ///\} } // extern "C" <commit_msg>Do not echo expression results; kernel handles it.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // FIXME: This file shall contain the decl of cling::Jupyter in a future // revision! //#include "cling/Interpreter/Jupyter/Kernel.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include "cling/MetaProcessor/MetaProcessor.h" #include "cling/Utils/Output.h" #include "llvm/Support/raw_ostream.h" #include <map> #include <string> #include <cstring> #ifndef LLVM_ON_WIN32 # include <unistd.h> #else # include <io.h> # define write _write #endif // FIXME: should be moved into a Jupyter interp struct that then gets returned // from create. int pipeToJupyterFD = -1; namespace cling { namespace Jupyter { struct MIMEDataRef { const char* m_Data; const long m_Size; MIMEDataRef(const std::string& str): m_Data(str.c_str()), m_Size((long)str.length() + 1) {} MIMEDataRef(const char* str): MIMEDataRef(std::string(str)) {} MIMEDataRef(const char* data, long size): m_Data(data), m_Size(size) {} }; /// Push MIME stuff to Jupyter. To be called from user code. ///\param contentDict - dictionary of MIME type versus content. E.g. /// {{"text/html", {"<div></div>", }} ///\returns `false` if the output could not be sent. bool pushOutput(const std::map<std::string, MIMEDataRef> contentDict) { // Pipe sees (all numbers are longs, except for the first: // - num bytes in a long (sent as a single unsigned char!) // - num elements of the MIME dictionary; Jupyter selects one to display. // For each MIME dictionary element: // - size of MIME type string (including the terminating 0) // - MIME type as 0-terminated string // - size of MIME data buffer (including the terminating 0 for // 0-terminated strings) // - MIME data buffer // Write number of dictionary elements (and the size of that number in a // char) unsigned char sizeLong = sizeof(long); if (write(pipeToJupyterFD, &sizeLong, 1) != 1) return false; long dictSize = contentDict.size(); if (write(pipeToJupyterFD, &dictSize, sizeof(long)) != sizeof(long)) return false; for (auto iContent: contentDict) { const std::string& mimeType = iContent.first; long mimeTypeSize = (long)mimeType.size(); if (write(pipeToJupyterFD, &mimeTypeSize, sizeof(long)) != sizeof(long)) return false; if (write(pipeToJupyterFD, mimeType.c_str(), mimeType.size() + 1) != (long)(mimeType.size() + 1)) return false; const MIMEDataRef& mimeData = iContent.second; if (write(pipeToJupyterFD, &mimeData.m_Size, sizeof(long)) != sizeof(long)) return false; if (write(pipeToJupyterFD, mimeData.m_Data, mimeData.m_Size) != mimeData.m_Size) return false; } return true; } } // namespace Jupyter } // namespace cling extern "C" { ///\{ ///\name Cling4CTypes /// The Python compatible view of cling /// The MetaProcessor cast to void* using TheMetaProcessor = void; /// Create an interpreter object. TheMetaProcessor* cling_create(int argc, const char *argv[], const char* llvmdir, int pipefd) { pipeToJupyterFD = pipefd; auto I = new cling::Interpreter(argc, argv, llvmdir); return new cling::MetaProcessor(*I, cling::errs()); } /// Destroy the interpreter. void cling_destroy(TheMetaProcessor *metaProc) { cling::MetaProcessor *M = (cling::MetaProcessor*)metaProc; cling::Interpreter *I = const_cast<cling::Interpreter*>(&M->getInterpreter()); delete M; delete I; } /// Stringify a cling::Value static std::string ValueToString(const cling::Value& V) { std::string valueString; { llvm::raw_string_ostream os(valueString); V.print(os); } return valueString; } /// Evaluate a string of code. Returns nullptr on failure. /// Returns a string representation of the expression (can be "") on success. char* cling_eval(TheMetaProcessor *metaProc, const char *code) { cling::MetaProcessor *M = (cling::MetaProcessor*)metaProc; cling::Value V; cling::Interpreter::CompilationResult Res; if (M->process(code, Res, &V, /*disableValuePrinting*/ true)) { cling::Jupyter::pushOutput({{"text/html", "Incomplete input! Ignored."}}); M->cancelContinuation(); return nullptr; } if (Res != cling::Interpreter::kSuccess) return nullptr; if (!V.isValid()) return strdup(""); return strdup(ValueToString(V).c_str()); } void cling_eval_free(char* str) { free(str); } /// Code completion interfaces. /// Start completion of code. Returns a handle to be passed to /// cling_complete_next() to iterate over the completion options. Returns nulptr /// if no completions are known. void* cling_complete_start(const char* code) { return new int(42); } /// Grab the next completion of some code. Returns nullptr if none is left. const char* cling_complete_next(void* completionHandle) { int* counter = (int*) completionHandle; if (++(*counter) > 43) { delete counter; return nullptr; } return "COMPLETE!"; } ///\} } // extern "C" <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <chrono> #include <iostream> #include "cuda.h" #include "cuda_runtime.h" #include "cuda_runtime_api.h" #include "egblas.hpp" #define cuda_check(call) \ { \ auto status = call; \ if (status != cudaSuccess) { \ std::cerr << "CUDA error: " << cudaGetErrorString(status) << " from " << #call << std::endl \ << "from " << __FILE__ << ":" << __LINE__ << std::endl; \ exit(1); \ } \ } namespace { using timer = std::chrono::high_resolution_clock; using microseconds = std::chrono::microseconds; float* prepare_cpu(size_t N, float s){ float* x_cpu = new float[N]; for (size_t i = 0; i < N; ++i) { x_cpu[i] = s * (i + 1); } return x_cpu; } float* prepare_gpu(size_t N, float* x_cpu){ float* x_gpu; cuda_check(cudaMalloc((void**)&x_gpu, N * sizeof(float))); cuda_check(cudaMemcpy(x_gpu, x_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); return x_gpu; } void release(float* x_cpu, float* x_gpu){ delete[] x_cpu; cuda_check(cudaFree(x_gpu)); } template<typename T> inline void report(const std::string& name, const T& t0, size_t repeat, size_t N){ auto t1 = timer::now(); auto us = std::chrono::duration_cast<microseconds>(t1 - t0).count(); auto us_avg = us / double(repeat); std::cout << name << "(" << N << "): Tot: " << us << "us Avg: " << us_avg << "us Throughput: " << (1e6 / double(us_avg)) * N << "E/s" << std::endl; } void bench_sum(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.1f); auto* x_gpu = prepare_gpu(N, x_cpu); egblas_ssum(x_gpu, N, 1); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_ssum(x_gpu, N, 1); } report("sum", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); } void bench_sum(){ bench_sum(100); bench_sum(1000); bench_sum(10000); bench_sum(100000); bench_sum(1000000); bench_sum(10000000); bench_sum(100000000); std::cout << std::endl; } void bench_inv_dropout(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.0f); auto* x_gpu = prepare_gpu(N, x_cpu); egblas_sinv_dropout_seed(N, 0.5f, 1.0f, x_gpu, 1, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_sinv_dropout_seed(N, 0.5f, 1.0f, x_gpu, 1, 42); } report("inv_dropout", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); } void bench_inv_dropout(){ bench_inv_dropout(100); bench_inv_dropout(1000); bench_inv_dropout(10000); bench_inv_dropout(100000); bench_inv_dropout(1000000); bench_inv_dropout(10000000); bench_inv_dropout(100000000); std::cout << std::endl; } void bench_saxpy(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.0f); auto* y_cpu = prepare_cpu(N, 3.0f); auto* x_gpu = prepare_gpu(N, x_cpu); auto* y_gpu = prepare_gpu(N, y_cpu); egblas_saxpy(N, 2.1f, x_gpu, 1, y_gpu, 1); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_saxpy(N, 2.1f, x_gpu, 1, y_gpu, 1); } report("saxpy", t0, repeat, N); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); } void bench_saxpy(){ bench_saxpy(100); bench_saxpy(1000); bench_saxpy(10000); bench_saxpy(100000); bench_saxpy(1000000); bench_saxpy(10000000); bench_saxpy(100000000); std::cout << std::endl; } void bench_saxpby(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.2f); auto* y_cpu = prepare_cpu(N, 3.1f); auto* x_gpu = prepare_gpu(N, x_cpu); auto* y_gpu = prepare_gpu(N, y_cpu); egblas_saxpby(N, 2.54f, x_gpu, 1, 3.49f, y_gpu, 1); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_saxpby(N, 2.54f, x_gpu, 1, 3.49f, y_gpu, 1); } report("saxpby", t0, repeat, N); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); } void bench_saxpby(){ bench_saxpby(100); bench_saxpby(1000); bench_saxpby(10000); bench_saxpby(100000); bench_saxpby(1000000); bench_saxpby(10000000); bench_saxpby(100000000); std::cout << std::endl; } void bench_shuffle(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.2f); auto* x_gpu = prepare_gpu(N, x_cpu); egblas_shuffle_seed(N, x_gpu, 4, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_shuffle_seed(N, x_gpu, 4, 42); } report("shuffle", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); } void bench_shuffle(){ bench_shuffle(100); bench_shuffle(1000); bench_shuffle(10000); bench_shuffle(100000); std::cout << std::endl; } void bench_par_shuffle(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.2f); auto* y_cpu = prepare_cpu(N, 3.1f); auto* x_gpu = prepare_gpu(N, x_cpu); auto* y_gpu = prepare_gpu(N, y_cpu); egblas_par_shuffle_seed(N, x_gpu, 4, y_gpu, 4, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_par_shuffle_seed(N, x_gpu, 4, y_gpu, 4, 42); } report("par_shuffle", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); } void bench_par_shuffle(){ bench_par_shuffle(100); bench_par_shuffle(1000); bench_par_shuffle(10000); bench_par_shuffle(100000); std::cout << std::endl; } void bench_big_shuffle(size_t N, size_t repeat = 100) { auto* x_cpu = prepare_cpu(N * 1024, 2.2f); auto* x_gpu = prepare_gpu(N * 1024, x_cpu); egblas_shuffle_seed(N, x_gpu, 4 * 1024, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_shuffle_seed(N, x_gpu, 4 * 1024, 42); } report("big_shuffle", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * 1024 * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); } void bench_big_shuffle(){ bench_big_shuffle(100); bench_big_shuffle(1000); bench_big_shuffle(10000); std::cout << std::endl; } void bench_par_big_shuffle(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N * 1024, 2.2f); auto* y_cpu = prepare_cpu(N * 1024, 3.1f); auto* x_gpu = prepare_gpu(N * 1024, x_cpu); auto* y_gpu = prepare_gpu(N * 1024, y_cpu); egblas_par_shuffle_seed(N, x_gpu, 4 * 1024, y_gpu, 4, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_par_shuffle_seed(N, x_gpu, 4 * 1024, y_gpu, 4, 42); } report("par_big_shuffle", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * 1024 * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * 1024 * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); } void bench_par_big_shuffle(){ bench_par_big_shuffle(100); bench_par_big_shuffle(1000); bench_par_big_shuffle(10000); std::cout << std::endl; } } // End of anonymous namespace int main(int argc, char* argv[]){ std::string sub = "all"; if(argc > 1){ sub = std::string(argv[1]); } if (sub == "sum" || sub == "all") { bench_sum(); } if (sub == "dropout" || sub == "all") { bench_inv_dropout(); } if (sub == "shuffle" || sub == "all") { bench_shuffle(); bench_par_shuffle(); bench_big_shuffle(); bench_par_big_shuffle(); } if (sub == "axpy" || sub == "all") { bench_saxpy(); bench_saxpby(); } } <commit_msg>Benchmark for stddev<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <chrono> #include <iostream> #include "cuda.h" #include "cuda_runtime.h" #include "cuda_runtime_api.h" #include "egblas.hpp" #define cuda_check(call) \ { \ auto status = call; \ if (status != cudaSuccess) { \ std::cerr << "CUDA error: " << cudaGetErrorString(status) << " from " << #call << std::endl \ << "from " << __FILE__ << ":" << __LINE__ << std::endl; \ exit(1); \ } \ } namespace { using timer = std::chrono::high_resolution_clock; using microseconds = std::chrono::microseconds; float* prepare_cpu(size_t N, float s){ float* x_cpu = new float[N]; for (size_t i = 0; i < N; ++i) { x_cpu[i] = s * (i + 1); } return x_cpu; } float* prepare_gpu(size_t N, float* x_cpu){ float* x_gpu; cuda_check(cudaMalloc((void**)&x_gpu, N * sizeof(float))); cuda_check(cudaMemcpy(x_gpu, x_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); return x_gpu; } void release(float* x_cpu, float* x_gpu){ delete[] x_cpu; cuda_check(cudaFree(x_gpu)); } template<typename T> inline void report(const std::string& name, const T& t0, size_t repeat, size_t N){ auto t1 = timer::now(); auto us = std::chrono::duration_cast<microseconds>(t1 - t0).count(); auto us_avg = us / double(repeat); std::cout << name << "(" << N << "): Tot: " << us << "us Avg: " << us_avg << "us Throughput: " << (1e6 / double(us_avg)) * N << "E/s" << std::endl; } void bench_sum(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.1f); auto* x_gpu = prepare_gpu(N, x_cpu); egblas_ssum(x_gpu, N, 1); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_ssum(x_gpu, N, 1); } report("sum", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); } void bench_sum(){ bench_sum(100); bench_sum(1000); bench_sum(10000); bench_sum(100000); bench_sum(1000000); bench_sum(10000000); bench_sum(100000000); std::cout << std::endl; } void bench_stddev(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.1f); auto* x_gpu = prepare_gpu(N, x_cpu); egblas_sstddev(x_gpu, N, 1); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_sstddev(x_gpu, N, 1); } report("stddev", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); } void bench_stddev(){ bench_stddev(100); bench_stddev(1000); bench_stddev(10000); bench_stddev(100000); bench_stddev(1000000); bench_stddev(10000000); bench_stddev(100000000); std::cout << std::endl; } void bench_inv_dropout(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.0f); auto* x_gpu = prepare_gpu(N, x_cpu); egblas_sinv_dropout_seed(N, 0.5f, 1.0f, x_gpu, 1, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_sinv_dropout_seed(N, 0.5f, 1.0f, x_gpu, 1, 42); } report("inv_dropout", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); } void bench_inv_dropout(){ bench_inv_dropout(100); bench_inv_dropout(1000); bench_inv_dropout(10000); bench_inv_dropout(100000); bench_inv_dropout(1000000); bench_inv_dropout(10000000); bench_inv_dropout(100000000); std::cout << std::endl; } void bench_saxpy(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.0f); auto* y_cpu = prepare_cpu(N, 3.0f); auto* x_gpu = prepare_gpu(N, x_cpu); auto* y_gpu = prepare_gpu(N, y_cpu); egblas_saxpy(N, 2.1f, x_gpu, 1, y_gpu, 1); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_saxpy(N, 2.1f, x_gpu, 1, y_gpu, 1); } report("saxpy", t0, repeat, N); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); } void bench_saxpy(){ bench_saxpy(100); bench_saxpy(1000); bench_saxpy(10000); bench_saxpy(100000); bench_saxpy(1000000); bench_saxpy(10000000); bench_saxpy(100000000); std::cout << std::endl; } void bench_saxpby(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.2f); auto* y_cpu = prepare_cpu(N, 3.1f); auto* x_gpu = prepare_gpu(N, x_cpu); auto* y_gpu = prepare_gpu(N, y_cpu); egblas_saxpby(N, 2.54f, x_gpu, 1, 3.49f, y_gpu, 1); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_saxpby(N, 2.54f, x_gpu, 1, 3.49f, y_gpu, 1); } report("saxpby", t0, repeat, N); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); } void bench_saxpby(){ bench_saxpby(100); bench_saxpby(1000); bench_saxpby(10000); bench_saxpby(100000); bench_saxpby(1000000); bench_saxpby(10000000); bench_saxpby(100000000); std::cout << std::endl; } void bench_shuffle(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.2f); auto* x_gpu = prepare_gpu(N, x_cpu); egblas_shuffle_seed(N, x_gpu, 4, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_shuffle_seed(N, x_gpu, 4, 42); } report("shuffle", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); } void bench_shuffle(){ bench_shuffle(100); bench_shuffle(1000); bench_shuffle(10000); bench_shuffle(100000); std::cout << std::endl; } void bench_par_shuffle(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.2f); auto* y_cpu = prepare_cpu(N, 3.1f); auto* x_gpu = prepare_gpu(N, x_cpu); auto* y_gpu = prepare_gpu(N, y_cpu); egblas_par_shuffle_seed(N, x_gpu, 4, y_gpu, 4, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_par_shuffle_seed(N, x_gpu, 4, y_gpu, 4, 42); } report("par_shuffle", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); } void bench_par_shuffle(){ bench_par_shuffle(100); bench_par_shuffle(1000); bench_par_shuffle(10000); bench_par_shuffle(100000); std::cout << std::endl; } void bench_big_shuffle(size_t N, size_t repeat = 100) { auto* x_cpu = prepare_cpu(N * 1024, 2.2f); auto* x_gpu = prepare_gpu(N * 1024, x_cpu); egblas_shuffle_seed(N, x_gpu, 4 * 1024, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_shuffle_seed(N, x_gpu, 4 * 1024, 42); } report("big_shuffle", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * 1024 * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); } void bench_big_shuffle(){ bench_big_shuffle(100); bench_big_shuffle(1000); bench_big_shuffle(10000); std::cout << std::endl; } void bench_par_big_shuffle(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N * 1024, 2.2f); auto* y_cpu = prepare_cpu(N * 1024, 3.1f); auto* x_gpu = prepare_gpu(N * 1024, x_cpu); auto* y_gpu = prepare_gpu(N * 1024, y_cpu); egblas_par_shuffle_seed(N, x_gpu, 4 * 1024, y_gpu, 4, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_par_shuffle_seed(N, x_gpu, 4 * 1024, y_gpu, 4, 42); } report("par_big_shuffle", t0, repeat, N); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * 1024 * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * 1024 * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); } void bench_par_big_shuffle(){ bench_par_big_shuffle(100); bench_par_big_shuffle(1000); bench_par_big_shuffle(10000); std::cout << std::endl; } } // End of anonymous namespace int main(int argc, char* argv[]){ std::string sub = "all"; if(argc > 1){ sub = std::string(argv[1]); } if (sub == "sum" || sub == "all") { bench_sum(); } if (sub == "stddev" || sub == "all") { bench_stddev(); } if (sub == "dropout" || sub == "all") { bench_inv_dropout(); } if (sub == "shuffle" || sub == "all") { bench_shuffle(); bench_par_shuffle(); bench_big_shuffle(); bench_par_big_shuffle(); } if (sub == "axpy" || sub == "all") { bench_saxpy(); bench_saxpby(); } } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "ClientRegister.h" #include "SyncThread.h" #include "ILoginListener.h" #include "common/RhoConf.h" #include "common/RhodesApp.h" #include "System.h" rho::String rho_sysimpl_get_phone_id(); namespace rho{ namespace sync{ using namespace rho::common; using namespace rho::db; static const int THREAD_WAIT_TIMEOUT = 10; IMPLEMENT_LOGCLASS(CClientRegister,"ClientRegister"); CClientRegister* CClientRegister::m_pInstance = 0; bool CClientRegister::s_sslVerifyPeer = true; VectorPtr<ILoginListener*> CClientRegister::s_loginListeners; /*static*/ CClientRegister* CClientRegister::Get() { if (!m_pInstance) { m_pInstance = new CClientRegister(); } return m_pInstance; } /*static*/ CClientRegister* CClientRegister::Create() { LOG(TRACE) + "Starting ClientRegister"; Get()->startUp(); return m_pInstance; } /*static*/ CClientRegister* CClientRegister::Create(const String& devicePin) { Get()->setDevicehPin(devicePin); return m_pInstance; } /*static*/ void CClientRegister::Stop() { if(m_pInstance) { m_pInstance->doStop(); } } /*static*/ void CClientRegister::Destroy() { if ( m_pInstance ) delete m_pInstance; m_pInstance = 0; } /*static*/ void CClientRegister::SetSslVerifyPeer(boolean b) { s_sslVerifyPeer = b; if (m_pInstance) m_pInstance->m_NetRequest.setSslVerifyPeer(b); } bool CClientRegister::GetSslVerifyPeer() { return s_sslVerifyPeer; } /*static*/void CClientRegister::AddLoginListener(ILoginListener* listener) { s_loginListeners.addElement(listener); } CClientRegister::CClientRegister() : m_nPollInterval(POLL_INTERVAL_SECONDS) { m_NetRequest.setSslVerifyPeer(s_sslVerifyPeer); } CClientRegister::~CClientRegister() { doStop(); m_pInstance = null; } void CClientRegister::setRhoconnectCredentials(const String& user, const String& pass, const String& session) { LOG(INFO) + "New Sync credentials - user: " + user + ", sess: " + session; for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I) { (*I)->onLogin(user, pass, session); } startUp(); } void CClientRegister::dropRhoconnectCredentials(const String& session) { for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I) { (*I)->onLogout(session); } } void CClientRegister::setDevicehPin(const String& pin) { m_strDevicePin = pin; if (pin.length() > 0) { startUp(); } else { doStop(); } } void CClientRegister::startUp() { if ( RHOCONF().getString("syncserver").length() > 0 ) { LOG(INFO) + "Starting ClientRegister..."; start(epLow); stopWait(); } } void CClientRegister::run() { unsigned i = 0; LOG(INFO)+"ClientRegister is started"; while(!isStopping()) { i++; LOG(INFO)+"Try to register: " + i; if ( CSyncThread::getInstance() != null ) { if ( doRegister(CSyncThread::getSyncEngine()) ) { LOG(INFO)+"Registered: " + i; break; } } else LOG(INFO)+"SyncThread is not ready"; LOG(INFO)+"Waiting for "+ m_nPollInterval+ " sec to try again to register client"; wait(m_nPollInterval*1000); } LOG(INFO)+"ClientRegister thread shutdown"; } String CClientRegister::getRegisterBody(const String& strClientID) { IRhoPushClient* pushClient = RHODESAPP().getDefaultPushClient(); int port = RHOCONF().getInt("push_port"); String body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, m_strDevicePin, port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho::System::getPhoneId(), /*device_push_type*/ (0 != pushClient) ? pushClient->getType() : "" /*it means native push type*/); LOG(INFO)+"getRegisterBody() BODY is: " + body; return body; /* if(m_isAns) body = CSyncThread::getSyncEngine().getProtocol().getClientAnsRegisterBody( strClientID, m_strDevicePin, port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho_sysimpl_get_phone_id() ); else body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, m_strDevicePin, port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho_sysimpl_get_phone_id() ); */ } boolean CClientRegister::doRegister(CSyncEngine& oSync) { String session = oSync.loadSession(); if ( session.length() == 0 ) { m_nPollInterval = POLL_INTERVAL_INFINITE; LOG(INFO)+"Session is empty, do register later"; return false; } Get()->setRhoconnectCredentials("", "", session); if ( m_strDevicePin.length() == 0 ) { m_nPollInterval = POLL_INTERVAL_INFINITE; LOG(INFO)+"Device PUSH pin is empty, do register later"; return false; } m_nPollInterval = POLL_INTERVAL_SECONDS; String client_id = oSync.loadClientID(); if ( client_id.length() == 0 ) { LOG(WARNING)+"Sync client_id is empty, do register later"; return false; } IDBResult res = CDBAdapter::getUserDB().executeSQL("SELECT token,token_sent from client_info"); if ( !res.isEnd() ) { String token = res.getStringByIdx(0); int token_sent = res.getIntByIdx(1) && !RHOCONF().getBool("register_push_at_startup"); if ( m_strDevicePin.compare(token) == 0 && token_sent > 0 ) { //token in db same as new one and it was already send to the server //so we do nothing return true; } } String strBody = getRegisterBody(client_id); NetResponse resp = getNet().pushData( oSync.getProtocol().getClientRegisterUrl(client_id), strBody, &oSync ); if( resp.isOK() ) { // try { CDBAdapter::getUserDB().executeSQL("UPDATE client_info SET token_sent=?, token=?", 1, m_strDevicePin ); // } catch(Exception ex) { // LOG.ERROR("Error saving token_sent to the DB..."); // } LOG(INFO)+"Registered client sucessfully..."; return true; } LOG(WARNING)+"Network error: "+ resp.getRespCode(); return false; } void CClientRegister::doStop() { LOG(INFO) + "Stopping ClientRegister..."; m_NetRequest.cancel(); stop(WAIT_BEFOREKILL_SECONDS); } } } <commit_msg>fixed ClientRegister infinite thread resume<commit_after>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "ClientRegister.h" #include "SyncThread.h" #include "ILoginListener.h" #include "common/RhoConf.h" #include "common/RhodesApp.h" #include "System.h" rho::String rho_sysimpl_get_phone_id(); namespace rho{ namespace sync{ using namespace rho::common; using namespace rho::db; static const int THREAD_WAIT_TIMEOUT = 10; IMPLEMENT_LOGCLASS(CClientRegister,"ClientRegister"); CClientRegister* CClientRegister::m_pInstance = 0; bool CClientRegister::s_sslVerifyPeer = true; VectorPtr<ILoginListener*> CClientRegister::s_loginListeners; /*static*/ CClientRegister* CClientRegister::Get() { if (!m_pInstance) { m_pInstance = new CClientRegister(); } return m_pInstance; } /*static*/ CClientRegister* CClientRegister::Create() { LOG(TRACE) + "Starting ClientRegister"; Get()->startUp(); return m_pInstance; } /*static*/ CClientRegister* CClientRegister::Create(const String& devicePin) { Get()->setDevicehPin(devicePin); return m_pInstance; } /*static*/ void CClientRegister::Stop() { if(m_pInstance) { m_pInstance->doStop(); } } /*static*/ void CClientRegister::Destroy() { if ( m_pInstance ) delete m_pInstance; m_pInstance = 0; } /*static*/ void CClientRegister::SetSslVerifyPeer(boolean b) { s_sslVerifyPeer = b; if (m_pInstance) m_pInstance->m_NetRequest.setSslVerifyPeer(b); } bool CClientRegister::GetSslVerifyPeer() { return s_sslVerifyPeer; } /*static*/void CClientRegister::AddLoginListener(ILoginListener* listener) { s_loginListeners.addElement(listener); } CClientRegister::CClientRegister() : m_nPollInterval(POLL_INTERVAL_SECONDS) { m_NetRequest.setSslVerifyPeer(s_sslVerifyPeer); } CClientRegister::~CClientRegister() { doStop(); m_pInstance = null; } void CClientRegister::setRhoconnectCredentials(const String& user, const String& pass, const String& session) { LOG(INFO) + "New Sync credentials - user: " + user + ", sess: " + session; for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I) { (*I)->onLogin(user, pass, session); } if (!isAlive()) { startUp(); } } void CClientRegister::dropRhoconnectCredentials(const String& session) { for(VectorPtr<ILoginListener*>::iterator I = s_loginListeners.begin(); I != s_loginListeners.end(); ++I) { (*I)->onLogout(session); } } void CClientRegister::setDevicehPin(const String& pin) { m_strDevicePin = pin; if (pin.length() > 0) { startUp(); } else { doStop(); } } void CClientRegister::startUp() { if ( RHOCONF().getString("syncserver").length() > 0 ) { LOG(INFO) + "Starting ClientRegister..."; start(epLow); stopWait(); } } void CClientRegister::run() { unsigned i = 0; LOG(INFO)+"ClientRegister is started"; while(!isStopping()) { i++; LOG(INFO)+"Try to register: " + i; if ( CSyncThread::getInstance() != null ) { if ( doRegister(CSyncThread::getSyncEngine()) ) { LOG(INFO)+"Registered: " + i; break; } } else LOG(INFO)+"SyncThread is not ready"; LOG(INFO)+"Waiting for "+ m_nPollInterval+ " sec to try again to register client"; wait(m_nPollInterval*1000); } LOG(INFO)+"ClientRegister thread shutdown"; } String CClientRegister::getRegisterBody(const String& strClientID) { IRhoPushClient* pushClient = RHODESAPP().getDefaultPushClient(); int port = RHOCONF().getInt("push_port"); String body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, m_strDevicePin, port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho::System::getPhoneId(), /*device_push_type*/ (0 != pushClient) ? pushClient->getType() : "" /*it means native push type*/); LOG(INFO)+"getRegisterBody() BODY is: " + body; return body; /* if(m_isAns) body = CSyncThread::getSyncEngine().getProtocol().getClientAnsRegisterBody( strClientID, m_strDevicePin, port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho_sysimpl_get_phone_id() ); else body = CSyncThread::getSyncEngine().getProtocol().getClientRegisterBody( strClientID, m_strDevicePin, port > 0 ? port : DEFAULT_PUSH_PORT, rho_rhodesapp_getplatform(), rho_sysimpl_get_phone_id() ); */ } boolean CClientRegister::doRegister(CSyncEngine& oSync) { String session = oSync.loadSession(); if ( session.length() == 0 ) { m_nPollInterval = POLL_INTERVAL_INFINITE; LOG(INFO)+"Session is empty, do register later"; return false; } if ( m_strDevicePin.length() == 0 ) { m_nPollInterval = POLL_INTERVAL_INFINITE; LOG(INFO)+"Device PUSH pin is empty, do register later"; return false; } m_nPollInterval = POLL_INTERVAL_SECONDS; String client_id = oSync.loadClientID(); if ( client_id.length() == 0 ) { LOG(WARNING)+"Sync client_id is empty, do register later"; return false; } IDBResult res = CDBAdapter::getUserDB().executeSQL("SELECT token,token_sent from client_info"); if ( !res.isEnd() ) { String token = res.getStringByIdx(0); int token_sent = res.getIntByIdx(1) && !RHOCONF().getBool("register_push_at_startup"); if ( m_strDevicePin.compare(token) == 0 && token_sent > 0 ) { //token in db same as new one and it was already send to the server //so we do nothing setRhoconnectCredentials("","",session); return true; } } String strBody = getRegisterBody(client_id); NetResponse resp = getNet().pushData( oSync.getProtocol().getClientRegisterUrl(client_id), strBody, &oSync ); if( resp.isOK() ) { // try { CDBAdapter::getUserDB().executeSQL("UPDATE client_info SET token_sent=?, token=?", 1, m_strDevicePin ); // } catch(Exception ex) { // LOG.ERROR("Error saving token_sent to the DB..."); // } LOG(INFO)+"Registered client sucessfully..."; setRhoconnectCredentials("","",session); return true; } LOG(WARNING)+"Network error: "+ resp.getRespCode(); return false; } void CClientRegister::doStop() { LOG(INFO) + "Stopping ClientRegister..."; m_NetRequest.cancel(); stop(WAIT_BEFOREKILL_SECONDS); } } } <|endoftext|>
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include "driver.hh" #include "bsemain.hh" #include "internal.hh" #include "bsesequencer.hh" #define DDEBUG(...) Bse::debug ("driver", __VA_ARGS__) namespace Bse { // == Driver == Driver::Driver (const String &devid) : devid_ (devid) {} Driver::~Driver () {} // == RegisteredDriver == template<typename DriverP> struct RegisteredDriver { const String driver_id_; std::function<DriverP (const String&)> create_; std::function<void (Driver::EntryVec&)> list_; using RegisteredDriverVector = std::vector<RegisteredDriver>; static RegisteredDriverVector& registered_driver_vector() { static RegisteredDriverVector registered_driver_vector_; return registered_driver_vector_; } static DriverP open (const String &devid, Driver::IODir iodir, Error *ep, const std::function<Error (DriverP, Driver::IODir)> &opener) { std::function<DriverP (const String&)> create; const String driverid = kvpair_key (devid); for (const auto &driver : registered_driver_vector()) if (driver.driver_id_ == driverid) { create = driver.create_; break; } Error error = Error::DEVICE_NOT_AVAILABLE; DriverP driver = create ? create (kvpair_value (devid)) : NULL; if (driver) { error = opener (driver, iodir); if (ep) *ep = error; if (error == Error::NONE) { assert_return (driver->opened() == true, nullptr); assert_return (!(iodir & Driver::READONLY) || driver->readable(), nullptr); assert_return (!(iodir & Driver::WRITEONLY) || driver->writable(), nullptr); } else driver = nullptr; } else if (ep) *ep = error; return driver; } static String register_driver (const String &driverid, const std::function<DriverP (const String&)> &create, const std::function<void (Driver::EntryVec&)> &list) { auto &vec = registered_driver_vector(); RegisteredDriver rd = { driverid, create, list, }; vec.push_back (rd); return driverid; } static Driver::EntryVec list_drivers (const Driver::EntryVec &pseudos) { Driver::EntryVec entries; std::copy (pseudos.begin(), pseudos.end(), std::back_inserter (entries)); auto &vec = registered_driver_vector(); for (const auto &rd : vec) { Driver::EntryVec dentries; rd.list_ (dentries); for (auto &entry : dentries) entry.devid = entry.devid.empty() ? rd.driver_id_ : rd.driver_id_ + "=" + entry.devid; entries.insert (entries.end(), std::make_move_iterator (dentries.begin()), std::make_move_iterator (dentries.end())); } std::sort (entries.begin(), entries.end(), [] (const Driver::Entry &a, const Driver::Entry &b) { return a.priority < b.priority; }); return entries; } }; // == PcmDriver == PcmDriver::PcmDriver (const String &devid) : Driver (devid) {} PcmDriverP PcmDriver::open (const String &devid, IODir desired, IODir required, const PcmDriverConfig &config, Error *ep) { auto opener = [&config] (PcmDriverP d, IODir iodir) { return d->open (iodir, config); }; if (devid == "auto") { for (const auto &entry : list_drivers()) if (entry.priority < PSEUDO && // ignore pseudo devices during auto-selection !(entry.priority & 0x0000ffff)) // ignore secondary devices during auto-selection { PcmDriverP pcm_driver = RegisteredDriver<PcmDriverP>::open (entry.devid, desired, ep, opener); if (!pcm_driver && required && desired != required) pcm_driver = RegisteredDriver<PcmDriverP>::open (entry.devid, required, ep, opener); if (pcm_driver) return pcm_driver; } } else { PcmDriverP pcm_driver = RegisteredDriver<PcmDriverP>::open (devid, desired, ep, opener); if (!pcm_driver && required && desired != required) pcm_driver = RegisteredDriver<PcmDriverP>::open (devid, required, ep, opener); if (pcm_driver) return pcm_driver; } return nullptr; } String PcmDriver::register_driver (const String &driverid, const std::function<PcmDriverP (const String&)> &create, const std::function<void (EntryVec&)> &list) { return RegisteredDriver<PcmDriverP>::register_driver (driverid, create, list); } Driver::EntryVec PcmDriver::list_drivers () { Driver::Entry entry; entry.devid = "auto"; entry.device_name = _("Automatic driver selection"); entry.device_info = _("Select the first available PCM card or server"); entry.readonly = false; entry.writeonly = false; entry.priority = Driver::PAUTO; Driver::EntryVec pseudos; pseudos.push_back (entry); return RegisteredDriver<PcmDriverP>::list_drivers (pseudos); } // == MidiDriver == MidiDriver::MidiDriver (const String &devid) : Driver (devid) {} MidiDriverP MidiDriver::open (const String &devid, IODir iodir, Error *ep) { auto opener = [] (MidiDriverP d, IODir iodir) { return d->open (iodir); }; if (devid == "auto") { for (const auto &entry : list_drivers()) if (entry.priority < PSEUDO) // ignore pseudo devices during auto-selection { MidiDriverP midi_driver = RegisteredDriver<MidiDriverP>::open (entry.devid, iodir, ep, opener); if (midi_driver) return midi_driver; } } else { MidiDriverP midi_driver = RegisteredDriver<MidiDriverP>::open (devid, iodir, ep, opener); if (midi_driver) return midi_driver; } return nullptr; } String MidiDriver::register_driver (const String &driverid, const std::function<MidiDriverP (const String&)> &create, const std::function<void (EntryVec&)> &list) { return RegisteredDriver<MidiDriverP>::register_driver (driverid, create, list); } Driver::EntryVec MidiDriver::list_drivers () { Driver::Entry entry; entry.devid = "auto"; entry.device_name = _("Automatic MIDI driver selection"); entry.device_info = _("Select the first available MIDI device"); entry.readonly = false; entry.writeonly = false; entry.priority = Driver::PAUTO; Driver::EntryVec pseudos; pseudos.push_back (entry); return RegisteredDriver<MidiDriverP>::list_drivers (pseudos); } // == NullPcmDriver == class NullPcmDriver : public PcmDriver { uint n_channels_ = 0; uint mix_freq_ = 0; uint busy_us_ = 0; uint sleep_us_ = 0; public: explicit NullPcmDriver (const String &devid) : PcmDriver (devid) {} static PcmDriverP create (const String &devid) { auto pdriverp = std::make_shared<NullPcmDriver> (devid); return pdriverp; } virtual float pcm_frequency () const override { return mix_freq_; } virtual void close () override { assert_return (opened()); flags_ &= ~size_t (Flags::OPENED | Flags::READABLE | Flags::WRITABLE); } virtual Error open (IODir iodir, const PcmDriverConfig &config) override { assert_return (!opened(), Error::INTERNAL); // setup request const bool nosleep = true; const bool require_readable = iodir == READONLY || iodir == READWRITE; const bool require_writable = iodir == WRITEONLY || iodir == READWRITE; flags_ |= Flags::READABLE * require_readable; flags_ |= Flags::WRITABLE * require_writable; n_channels_ = config.n_channels; mix_freq_ = config.mix_freq; busy_us_ = 0; sleep_us_ = nosleep ? 0 : 10 * 1000; flags_ |= Flags::OPENED; DDEBUG ("NULL-PCM: opening with freq=%f channels=%d: %s", mix_freq_, n_channels_, bse_error_blurb (Error::NONE)); return Error::NONE; } virtual bool pcm_check_io (long *timeoutp) override { // keep the sequencer busy or we will constantly timeout Sequencer::instance().wakeup(); *timeoutp = 1; // ensure sequencer fairness return !Sequencer::instance().thread_lagging (2); } virtual void pcm_latency (uint *rlatency, uint *wlatency) const override { *rlatency = mix_freq_ / 10; *wlatency = mix_freq_ / 10; } virtual size_t pcm_read (size_t n, float *values) override { memset (values, 0, sizeof (values[0]) * n); return n; } virtual void pcm_write (size_t n, const float *values) override { busy_us_ += n * 1000000 / mix_freq_; if (busy_us_ >= 100 * 1000) { busy_us_ = 0; // give cpu to other applications (we might run at nice level -20) if (sleep_us_) g_usleep (sleep_us_); } } static void list_drivers (Driver::EntryVec &entries) { Driver::Entry entry; entry.devid = ""; // "null" entry.device_name = "Null PCM Driver"; entry.device_info = _("Discard all PCM output and provide zeros as PCM input"); entry.readonly = false; entry.writeonly = false; entry.priority = Driver::PNULL; entries.push_back (entry); } }; static const String null_pcm_driverid = PcmDriver::register_driver ("null", NullPcmDriver::create, NullPcmDriver::list_drivers); // == NullMidiDriver == class NullMidiDriver : public MidiDriver { public: explicit NullMidiDriver (const String &devid) : MidiDriver (devid) {} static MidiDriverP create (const String &devid) { auto pdriverp = std::make_shared<NullMidiDriver> (devid); return pdriverp; } virtual void close () override { assert_return (opened()); flags_ &= ~size_t (Flags::OPENED | Flags::READABLE | Flags::WRITABLE); } virtual Error open (IODir iodir) override { assert_return (!opened(), Error::INTERNAL); // setup request const bool require_readable = iodir == READONLY || iodir == READWRITE; const bool require_writable = iodir == WRITEONLY || iodir == READWRITE; flags_ |= Flags::READABLE * require_readable; flags_ |= Flags::WRITABLE * require_writable; flags_ |= Flags::OPENED; DDEBUG ("NULL-MIDI: opening: %s", bse_error_blurb (Error::NONE)); return Error::NONE; } static void list_drivers (Driver::EntryVec &entries) { Driver::Entry entry; entry.devid = ""; // "null" entry.device_name = "Null MIDI Driver"; entry.device_info = _("Discard all MIDI events"); entry.readonly = false; entry.writeonly = false; entry.priority = Driver::PNULL; entries.push_back (entry); } }; static const String null_midi_driverid = MidiDriver::register_driver ("null", NullMidiDriver::create, NullMidiDriver::list_drivers); } // Bse // == libbsejack.so == #include <gmodule.h> static Bse::Error try_load_libbsejack () { using namespace Bse; const std::string libbsejack = string_format ("%s/lib/libbse-jack-%u.%u.%u.so", runpath (RPath::INSTALLDIR), BSE_MAJOR_VERSION, BSE_MINOR_VERSION, BSE_MICRO_VERSION); Error error = Error::FILE_NOT_FOUND; String errmsg; if (Path::check (libbsejack, "fr")) { GModule *gmodule = g_module_open (libbsejack.c_str(), G_MODULE_BIND_LOCAL); // no API import if (gmodule) error = Error::NONE; else { errmsg = g_module_error(); error = Error::FILE_OPEN_FAILED; } } DDEBUG ("loading \"%s\": %s%s", libbsejack, bse_error_blurb (error), errmsg.empty() ? "" : ": " + errmsg); return error; } static bool *bsejack_loaded = Bse::register_driver_loader ("bsejack", try_load_libbsejack); <commit_msg>BSE: driver.cc: be silent about libbse-jack loading errors<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0 #include "driver.hh" #include "bsemain.hh" #include "internal.hh" #include "bsesequencer.hh" #define DDEBUG(...) Bse::debug ("driver", __VA_ARGS__) namespace Bse { // == Driver == Driver::Driver (const String &devid) : devid_ (devid) {} Driver::~Driver () {} // == RegisteredDriver == template<typename DriverP> struct RegisteredDriver { const String driver_id_; std::function<DriverP (const String&)> create_; std::function<void (Driver::EntryVec&)> list_; using RegisteredDriverVector = std::vector<RegisteredDriver>; static RegisteredDriverVector& registered_driver_vector() { static RegisteredDriverVector registered_driver_vector_; return registered_driver_vector_; } static DriverP open (const String &devid, Driver::IODir iodir, Error *ep, const std::function<Error (DriverP, Driver::IODir)> &opener) { std::function<DriverP (const String&)> create; const String driverid = kvpair_key (devid); for (const auto &driver : registered_driver_vector()) if (driver.driver_id_ == driverid) { create = driver.create_; break; } Error error = Error::DEVICE_NOT_AVAILABLE; DriverP driver = create ? create (kvpair_value (devid)) : NULL; if (driver) { error = opener (driver, iodir); if (ep) *ep = error; if (error == Error::NONE) { assert_return (driver->opened() == true, nullptr); assert_return (!(iodir & Driver::READONLY) || driver->readable(), nullptr); assert_return (!(iodir & Driver::WRITEONLY) || driver->writable(), nullptr); } else driver = nullptr; } else if (ep) *ep = error; return driver; } static String register_driver (const String &driverid, const std::function<DriverP (const String&)> &create, const std::function<void (Driver::EntryVec&)> &list) { auto &vec = registered_driver_vector(); RegisteredDriver rd = { driverid, create, list, }; vec.push_back (rd); return driverid; } static Driver::EntryVec list_drivers (const Driver::EntryVec &pseudos) { Driver::EntryVec entries; std::copy (pseudos.begin(), pseudos.end(), std::back_inserter (entries)); auto &vec = registered_driver_vector(); for (const auto &rd : vec) { Driver::EntryVec dentries; rd.list_ (dentries); for (auto &entry : dentries) entry.devid = entry.devid.empty() ? rd.driver_id_ : rd.driver_id_ + "=" + entry.devid; entries.insert (entries.end(), std::make_move_iterator (dentries.begin()), std::make_move_iterator (dentries.end())); } std::sort (entries.begin(), entries.end(), [] (const Driver::Entry &a, const Driver::Entry &b) { return a.priority < b.priority; }); return entries; } }; // == PcmDriver == PcmDriver::PcmDriver (const String &devid) : Driver (devid) {} PcmDriverP PcmDriver::open (const String &devid, IODir desired, IODir required, const PcmDriverConfig &config, Error *ep) { auto opener = [&config] (PcmDriverP d, IODir iodir) { return d->open (iodir, config); }; if (devid == "auto") { for (const auto &entry : list_drivers()) if (entry.priority < PSEUDO && // ignore pseudo devices during auto-selection !(entry.priority & 0x0000ffff)) // ignore secondary devices during auto-selection { PcmDriverP pcm_driver = RegisteredDriver<PcmDriverP>::open (entry.devid, desired, ep, opener); if (!pcm_driver && required && desired != required) pcm_driver = RegisteredDriver<PcmDriverP>::open (entry.devid, required, ep, opener); if (pcm_driver) return pcm_driver; } } else { PcmDriverP pcm_driver = RegisteredDriver<PcmDriverP>::open (devid, desired, ep, opener); if (!pcm_driver && required && desired != required) pcm_driver = RegisteredDriver<PcmDriverP>::open (devid, required, ep, opener); if (pcm_driver) return pcm_driver; } return nullptr; } String PcmDriver::register_driver (const String &driverid, const std::function<PcmDriverP (const String&)> &create, const std::function<void (EntryVec&)> &list) { return RegisteredDriver<PcmDriverP>::register_driver (driverid, create, list); } Driver::EntryVec PcmDriver::list_drivers () { Driver::Entry entry; entry.devid = "auto"; entry.device_name = _("Automatic driver selection"); entry.device_info = _("Select the first available PCM card or server"); entry.readonly = false; entry.writeonly = false; entry.priority = Driver::PAUTO; Driver::EntryVec pseudos; pseudos.push_back (entry); return RegisteredDriver<PcmDriverP>::list_drivers (pseudos); } // == MidiDriver == MidiDriver::MidiDriver (const String &devid) : Driver (devid) {} MidiDriverP MidiDriver::open (const String &devid, IODir iodir, Error *ep) { auto opener = [] (MidiDriverP d, IODir iodir) { return d->open (iodir); }; if (devid == "auto") { for (const auto &entry : list_drivers()) if (entry.priority < PSEUDO) // ignore pseudo devices during auto-selection { MidiDriverP midi_driver = RegisteredDriver<MidiDriverP>::open (entry.devid, iodir, ep, opener); if (midi_driver) return midi_driver; } } else { MidiDriverP midi_driver = RegisteredDriver<MidiDriverP>::open (devid, iodir, ep, opener); if (midi_driver) return midi_driver; } return nullptr; } String MidiDriver::register_driver (const String &driverid, const std::function<MidiDriverP (const String&)> &create, const std::function<void (EntryVec&)> &list) { return RegisteredDriver<MidiDriverP>::register_driver (driverid, create, list); } Driver::EntryVec MidiDriver::list_drivers () { Driver::Entry entry; entry.devid = "auto"; entry.device_name = _("Automatic MIDI driver selection"); entry.device_info = _("Select the first available MIDI device"); entry.readonly = false; entry.writeonly = false; entry.priority = Driver::PAUTO; Driver::EntryVec pseudos; pseudos.push_back (entry); return RegisteredDriver<MidiDriverP>::list_drivers (pseudos); } // == NullPcmDriver == class NullPcmDriver : public PcmDriver { uint n_channels_ = 0; uint mix_freq_ = 0; uint busy_us_ = 0; uint sleep_us_ = 0; public: explicit NullPcmDriver (const String &devid) : PcmDriver (devid) {} static PcmDriverP create (const String &devid) { auto pdriverp = std::make_shared<NullPcmDriver> (devid); return pdriverp; } virtual float pcm_frequency () const override { return mix_freq_; } virtual void close () override { assert_return (opened()); flags_ &= ~size_t (Flags::OPENED | Flags::READABLE | Flags::WRITABLE); } virtual Error open (IODir iodir, const PcmDriverConfig &config) override { assert_return (!opened(), Error::INTERNAL); // setup request const bool nosleep = true; const bool require_readable = iodir == READONLY || iodir == READWRITE; const bool require_writable = iodir == WRITEONLY || iodir == READWRITE; flags_ |= Flags::READABLE * require_readable; flags_ |= Flags::WRITABLE * require_writable; n_channels_ = config.n_channels; mix_freq_ = config.mix_freq; busy_us_ = 0; sleep_us_ = nosleep ? 0 : 10 * 1000; flags_ |= Flags::OPENED; DDEBUG ("NULL-PCM: opening with freq=%f channels=%d: %s", mix_freq_, n_channels_, bse_error_blurb (Error::NONE)); return Error::NONE; } virtual bool pcm_check_io (long *timeoutp) override { // keep the sequencer busy or we will constantly timeout Sequencer::instance().wakeup(); *timeoutp = 1; // ensure sequencer fairness return !Sequencer::instance().thread_lagging (2); } virtual void pcm_latency (uint *rlatency, uint *wlatency) const override { *rlatency = mix_freq_ / 10; *wlatency = mix_freq_ / 10; } virtual size_t pcm_read (size_t n, float *values) override { memset (values, 0, sizeof (values[0]) * n); return n; } virtual void pcm_write (size_t n, const float *values) override { busy_us_ += n * 1000000 / mix_freq_; if (busy_us_ >= 100 * 1000) { busy_us_ = 0; // give cpu to other applications (we might run at nice level -20) if (sleep_us_) g_usleep (sleep_us_); } } static void list_drivers (Driver::EntryVec &entries) { Driver::Entry entry; entry.devid = ""; // "null" entry.device_name = "Null PCM Driver"; entry.device_info = _("Discard all PCM output and provide zeros as PCM input"); entry.readonly = false; entry.writeonly = false; entry.priority = Driver::PNULL; entries.push_back (entry); } }; static const String null_pcm_driverid = PcmDriver::register_driver ("null", NullPcmDriver::create, NullPcmDriver::list_drivers); // == NullMidiDriver == class NullMidiDriver : public MidiDriver { public: explicit NullMidiDriver (const String &devid) : MidiDriver (devid) {} static MidiDriverP create (const String &devid) { auto pdriverp = std::make_shared<NullMidiDriver> (devid); return pdriverp; } virtual void close () override { assert_return (opened()); flags_ &= ~size_t (Flags::OPENED | Flags::READABLE | Flags::WRITABLE); } virtual Error open (IODir iodir) override { assert_return (!opened(), Error::INTERNAL); // setup request const bool require_readable = iodir == READONLY || iodir == READWRITE; const bool require_writable = iodir == WRITEONLY || iodir == READWRITE; flags_ |= Flags::READABLE * require_readable; flags_ |= Flags::WRITABLE * require_writable; flags_ |= Flags::OPENED; DDEBUG ("NULL-MIDI: opening: %s", bse_error_blurb (Error::NONE)); return Error::NONE; } static void list_drivers (Driver::EntryVec &entries) { Driver::Entry entry; entry.devid = ""; // "null" entry.device_name = "Null MIDI Driver"; entry.device_info = _("Discard all MIDI events"); entry.readonly = false; entry.writeonly = false; entry.priority = Driver::PNULL; entries.push_back (entry); } }; static const String null_midi_driverid = MidiDriver::register_driver ("null", NullMidiDriver::create, NullMidiDriver::list_drivers); } // Bse // == libbsejack.so == #include <gmodule.h> static Bse::Error try_load_libbsejack () { using namespace Bse; const std::string libbsejack = string_format ("%s/lib/libbse-jack-%u.%u.%u.so", runpath (RPath::INSTALLDIR), BSE_MAJOR_VERSION, BSE_MINOR_VERSION, BSE_MICRO_VERSION); if (Path::check (libbsejack, "fr")) { GModule *gmodule = g_module_open (libbsejack.c_str(), G_MODULE_BIND_LOCAL); // no API import if (!gmodule) DDEBUG ("loading \"%s\" failed: %s", libbsejack, g_module_error()); } return Error::NONE; } static bool *bsejack_loaded = Bse::register_driver_loader ("bsejack", try_load_libbsejack); <|endoftext|>
<commit_before> // -*- mode: c++; c-basic-offset:4 -*- // This file is part of libdap, A C++ implementation of the OPeNDAP Data // Access Protocol. // Copyright (c) 2002,2003 OPeNDAP, Inc. // Author: James Gallagher <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. // (c) COPRIGHT URI/MIT 1996,1998,1999 // Please first read the full copyright statement in the file COPYRIGHT_URI. // // Authors: // jhrg,jimg James Gallagher <[email protected]> // Implementation for the CE Clause class. #include "config.h" #include <assert.h> #include <algorithm> #include "expr.h" #include "DDS.h" #include "Clause.h" using std::cerr; using std::endl; Clause::Clause(const int oper, rvalue *a1, rvalue_list *rv) : _op(oper), _b_func(0), _bt_func(0), _arg1(a1), _args(rv) { assert(OK()); } Clause::Clause(bool_func func, rvalue_list *rv) : _op(0), _b_func(func), _bt_func(0), _arg1(0), _args(rv) { assert(OK()); if (_args) // account for null arg list _argc = _args->size(); else _argc = 0; } Clause::Clause(btp_func func, rvalue_list *rv) : _op(0), _b_func(0), _bt_func(func), _arg1(0), _args(rv) { assert(OK()); if (_args) _argc = _args->size(); else _argc = 0; } Clause::Clause() : _op(0), _b_func(0), _bt_func(0), _arg1(0), _args(0) { } static inline void delete_rvalue(rvalue *rv) { delete rv; rv = 0; } Clause::~Clause() { if (_arg1) { delete _arg1; _arg1 = 0; } if (_args) { // _args is a pointer to a vector<rvalue*> and we must must delete // each rvalue pointer here explicitly. 02/03/04 jhrg for_each(_args->begin(), _args->end(), delete_rvalue); delete _args; _args = 0; } } /** @brief Checks the "representation invariant" of a clause. */ bool Clause::OK() { // Each clause object can contain one of: a relational clause, a boolean // function clause or a BaseType pointer function clause. It must have a // valid argument list. // // But, a valid arg list might contain zero arguments! 10/16/98 jhrg bool relational = (_op && !_b_func && !_bt_func); bool boolean = (!_op && _b_func && !_bt_func); bool basetype = (!_op && !_b_func && _bt_func); if (relational) return _arg1 && _args; else if (boolean || basetype) return true; // Until we check arguments...10/16/98 jhrg else return false; } /** @brief Return true if the clause returns a boolean value. */ bool Clause::boolean_clause() { assert(OK()); return _op || _b_func; } /** @brief Return true if the clause returns a value in a BaseType pointer. */ bool Clause::value_clause() { assert(OK()); return (_bt_func != 0); } /** @brief Evaluate a clause which returns a boolean value This method must only be evaluated for clauses with relational expressions or boolean functions. @param dataset This is passed to the rvalue::bvalue() method. @param dds Use variables from this DDS when evaluating the expression @return True if the clause is true, false otherwise. @exception InternalErr if called for a clause that returns a BaseType pointer. */ bool Clause::value(const string &dataset, DDS &dds) { assert(OK()); assert(_op || _b_func); if (_op) { // Is it a relational clause? // rvalue::bvalue(...) returns the rvalue encapsulated in a // BaseType *. BaseType *btp = _arg1->bvalue(dataset, dds); // The list of rvalues is an implicit logical OR, so assume // FALSE and return TRUE for the first TRUE subclause. bool result = false; for (rvalue_list_iter i = _args->begin(); i != _args->end() && !result; i++) { result = result || btp->ops((*i)->bvalue(dataset, dds), _op, dataset); } return result; } else if (_b_func) { // ...A bool function? BaseType **argv = build_btp_args(_args, dds, dataset); bool result = (*_b_func)(_argc, argv, dds); delete[] argv; // Cache me! argv = 0; return result; } else { throw InternalErr(__FILE__, __LINE__, "A selection expression must contain only boolean clauses."); } } /** @brief Evaluate a clause that returns a value via a BaseType pointer. This method must only be evaluated for clauses with relational expressions or boolean functions. @param dataset This is passed to the function. @param dds Use variables from this DDS when evaluating the expression @param value A value-result parameter @return True if the the BaseType pointer is not null, false otherwise. @exception InternalErr if called for a clause that returns a boolean value. Not that this method itself \e does return a boolean value. */ bool Clause::value(const string &dataset, DDS &dds, BaseType **value) { assert(OK()); assert(_bt_func); if (_bt_func) { // build_btp_args() is a function defined in RValue.cc. It no longer // reads the values as it builds the arguments, that is now left up // to the functions themselves. 9/25/06 jhrg BaseType **argv = build_btp_args(_args, dds, dataset); *value = (*_bt_func)(_argc, argv, dds, dataset); delete[] argv; // Cache me! argv = 0; if (*value) { (*value)->set_send_p(true); return true; } else { return false; } } else { throw InternalErr(__FILE__, __LINE__, "Claue::value() was called in a context expecting a BaseType pointer return, but the Clause was boolean-valued instead."); } } <commit_msg>Clause.cc: Added a call to set_read_p(true) in Clause::value so that handlers' read() methods will not try to 'read over' the values inserted to the variables by a CE function.<commit_after> // -*- mode: c++; c-basic-offset:4 -*- // This file is part of libdap, A C++ implementation of the OPeNDAP Data // Access Protocol. // Copyright (c) 2002,2003 OPeNDAP, Inc. // Author: James Gallagher <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. // (c) COPRIGHT URI/MIT 1996,1998,1999 // Please first read the full copyright statement in the file COPYRIGHT_URI. // // Authors: // jhrg,jimg James Gallagher <[email protected]> // Implementation for the CE Clause class. #include "config.h" #include <assert.h> #include <algorithm> #include "expr.h" #include "DDS.h" #include "Clause.h" using std::cerr; using std::endl; Clause::Clause(const int oper, rvalue *a1, rvalue_list *rv) : _op(oper), _b_func(0), _bt_func(0), _arg1(a1), _args(rv) { assert(OK()); } Clause::Clause(bool_func func, rvalue_list *rv) : _op(0), _b_func(func), _bt_func(0), _arg1(0), _args(rv) { assert(OK()); if (_args) // account for null arg list _argc = _args->size(); else _argc = 0; } Clause::Clause(btp_func func, rvalue_list *rv) : _op(0), _b_func(0), _bt_func(func), _arg1(0), _args(rv) { assert(OK()); if (_args) _argc = _args->size(); else _argc = 0; } Clause::Clause() : _op(0), _b_func(0), _bt_func(0), _arg1(0), _args(0) { } static inline void delete_rvalue(rvalue *rv) { delete rv; rv = 0; } Clause::~Clause() { if (_arg1) { delete _arg1; _arg1 = 0; } if (_args) { // _args is a pointer to a vector<rvalue*> and we must must delete // each rvalue pointer here explicitly. 02/03/04 jhrg for_each(_args->begin(), _args->end(), delete_rvalue); delete _args; _args = 0; } } /** @brief Checks the "representation invariant" of a clause. */ bool Clause::OK() { // Each clause object can contain one of: a relational clause, a boolean // function clause or a BaseType pointer function clause. It must have a // valid argument list. // // But, a valid arg list might contain zero arguments! 10/16/98 jhrg bool relational = (_op && !_b_func && !_bt_func); bool boolean = (!_op && _b_func && !_bt_func); bool basetype = (!_op && !_b_func && _bt_func); if (relational) return _arg1 && _args; else if (boolean || basetype) return true; // Until we check arguments...10/16/98 jhrg else return false; } /** @brief Return true if the clause returns a boolean value. */ bool Clause::boolean_clause() { assert(OK()); return _op || _b_func; } /** @brief Return true if the clause returns a value in a BaseType pointer. */ bool Clause::value_clause() { assert(OK()); return (_bt_func != 0); } /** @brief Evaluate a clause which returns a boolean value This method must only be evaluated for clauses with relational expressions or boolean functions. @param dataset This is passed to the rvalue::bvalue() method. @param dds Use variables from this DDS when evaluating the expression @return True if the clause is true, false otherwise. @exception InternalErr if called for a clause that returns a BaseType pointer. */ bool Clause::value(const string &dataset, DDS &dds) { assert(OK()); assert(_op || _b_func); if (_op) { // Is it a relational clause? // rvalue::bvalue(...) returns the rvalue encapsulated in a // BaseType *. BaseType *btp = _arg1->bvalue(dataset, dds); // The list of rvalues is an implicit logical OR, so assume // FALSE and return TRUE for the first TRUE subclause. bool result = false; for (rvalue_list_iter i = _args->begin(); i != _args->end() && !result; i++) { result = result || btp->ops((*i)->bvalue(dataset, dds), _op, dataset); } return result; } else if (_b_func) { // ...A bool function? BaseType **argv = build_btp_args(_args, dds, dataset); bool result = (*_b_func)(_argc, argv, dds); delete[] argv; // Cache me! argv = 0; return result; } else { throw InternalErr(__FILE__, __LINE__, "A selection expression must contain only boolean clauses."); } } /** @brief Evaluate a clause that returns a value via a BaseType pointer. This method must only be evaluated for clauses with relational expressions or boolean functions. @param dataset This is passed to the function. @param dds Use variables from this DDS when evaluating the expression @param value A value-result parameter @return True if the the BaseType pointer is not null, false otherwise. @exception InternalErr if called for a clause that returns a boolean value. Not that this method itself \e does return a boolean value. */ bool Clause::value(const string &dataset, DDS &dds, BaseType **value) { assert(OK()); assert(_bt_func); if (_bt_func) { // build_btp_args() is a function defined in RValue.cc. It no longer // reads the values as it builds the arguments, that is now left up // to the functions themselves. 9/25/06 jhrg BaseType **argv = build_btp_args(_args, dds, dataset); *value = (*_bt_func)(_argc, argv, dds, dataset); delete[] argv; // Cache me! argv = 0; if (*value) { (*value)->set_send_p(true); (*value)->set_read_p(true); return true; } else { return false; } } else { throw InternalErr(__FILE__, __LINE__, "Claue::value() was called in a context expecting a BaseType pointer return, but the Clause was boolean-valued instead."); } } <|endoftext|>
<commit_before>/** @file @brief Implementation of the "multiserver" plugin that offers the stock VRPN devices. @date 2014 @author Ryan Pavlik <[email protected]> <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include "VRPNMultiserver.h" #include "DevicesWithParameters.h" #include <osvr/PluginKit/PluginKit.h> #include <osvr/Util/UniquePtr.h> #include <osvr/VRPNServer/VRPNDeviceRegistration.h> // Library/third-party includes #include "hidapi/hidapi.h" #include "vrpn_Connection.h" #include "vrpn_Tracker_RazerHydra.h" #include "vrpn_Tracker_Filter.h" #include <boost/noncopyable.hpp> // Standard includes #include <iostream> #include <map> #include <string> #include <sstream> class VRPNHardwareDetect : boost::noncopyable { public: VRPNHardwareDetect(VRPNMultiserverData &data) : m_data(data) {} OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) { struct hid_device_info *enumData = hid_enumerate(0, 0); for (struct hid_device_info *dev = enumData; dev != nullptr; dev = dev->next) { if (dev->vendor_id == 0x1532 && dev->product_id == 0x0300) { /// Decorated name for Hydra std::string name; { // Razer Hydra osvr::vrpnserver::VRPNDeviceRegistration reg(ctx); name = reg.useDecoratedName(m_data.getName("RazerHydra")); reg.registerDevice(new vrpn_Tracker_RazerHydra( name.c_str(), reg.getVRPNConnection())); } std::string localName = "*" + name; { // Corresponding filter osvr::vrpnserver::VRPNDeviceRegistration reg(ctx); reg.registerDevice(new vrpn_Tracker_FilterOneEuro( reg.useDecoratedName(m_data.getName("OneEuroFilter")) .c_str(), reg.getVRPNConnection(), localName.c_str(), 2, 1.15, 1.0, 1.2, 1.5, 5.0, 1.2)); } break; } } hid_free_enumeration(enumData); return OSVR_RETURN_SUCCESS; } private: VRPNMultiserverData &m_data; }; OSVR_PLUGIN(org_opengoggles_bundled_Multiserver) { osvr::pluginkit::PluginContext context(ctx); VRPNMultiserverData &data = *context.registerObjectForDeletion(new VRPNMultiserverData); context.registerHardwareDetectCallback(new VRPNHardwareDetect(data)); osvrRegisterDriverInstantiationCallback( ctx, "YEI_3Space_Sensor", &wrappedConstructor<&createYEI>, &data); return OSVR_RETURN_SUCCESS; } <commit_msg>Avoid trying to connect to the same hydra more than once.<commit_after>/** @file @brief Implementation of the "multiserver" plugin that offers the stock VRPN devices. @date 2014 @author Ryan Pavlik <[email protected]> <http://sensics.com> */ // Copyright 2014 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include "VRPNMultiserver.h" #include "DevicesWithParameters.h" #include <osvr/PluginKit/PluginKit.h> #include <osvr/Util/UniquePtr.h> #include <osvr/VRPNServer/VRPNDeviceRegistration.h> // Library/third-party includes #include "hidapi/hidapi.h" #include "vrpn_Connection.h" #include "vrpn_Tracker_RazerHydra.h" #include "vrpn_Tracker_Filter.h" #include <boost/noncopyable.hpp> // Standard includes #include <iostream> #include <map> #include <string> #include <sstream> #include <vector> class VRPNHardwareDetect : boost::noncopyable { public: VRPNHardwareDetect(VRPNMultiserverData &data) : m_data(data) {} OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) { struct hid_device_info *enumData = hid_enumerate(0, 0); for (struct hid_device_info *dev = enumData; dev != nullptr; dev = dev->next) { if (dev->vendor_id == 0x1532 && dev->product_id == 0x0300 && !m_isPathHandled(dev->path)) { m_handlePath(dev->path); /// Decorated name for Hydra std::string name; { // Razer Hydra osvr::vrpnserver::VRPNDeviceRegistration reg(ctx); name = reg.useDecoratedName(m_data.getName("RazerHydra")); reg.registerDevice(new vrpn_Tracker_RazerHydra( name.c_str(), reg.getVRPNConnection())); } std::string localName = "*" + name; { // Corresponding filter osvr::vrpnserver::VRPNDeviceRegistration reg(ctx); reg.registerDevice(new vrpn_Tracker_FilterOneEuro( reg.useDecoratedName(m_data.getName("OneEuroFilter")) .c_str(), reg.getVRPNConnection(), localName.c_str(), 2, 1.15, 1.0, 1.2, 1.5, 5.0, 1.2)); } break; } } hid_free_enumeration(enumData); return OSVR_RETURN_SUCCESS; } private: bool m_isPathHandled(const char *path) { return std::find(begin(m_handledPaths), end(m_handledPaths), std::string(path)) != end(m_handledPaths); } void m_handlePath(const char *path) { m_handledPaths.push_back(std::string(path)); } VRPNMultiserverData &m_data; std::vector<std::string> m_handledPaths; }; OSVR_PLUGIN(org_opengoggles_bundled_Multiserver) { osvr::pluginkit::PluginContext context(ctx); VRPNMultiserverData &data = *context.registerObjectForDeletion(new VRPNMultiserverData); context.registerHardwareDetectCallback(new VRPNHardwareDetect(data)); osvrRegisterDriverInstantiationCallback( ctx, "YEI_3Space_Sensor", &wrappedConstructor<&createYEI>, &data); return OSVR_RETURN_SUCCESS; } <|endoftext|>
<commit_before>template <typename T> inline double evaluatePartitions(data_t* data, struct Density* density, struct Splitter<T>* splitter, size_t k) { size_t i = splitter->feature_id; size_t n_features = splitter->n_features; data_t data_point; target_t target_value; size_t id = splitter->node->id; memset((void*) density->counters_left, 0x00, splitter->n_classes * sizeof(size_t)); memset((void*) density->counters_right, 0x00, splitter->n_classes * sizeof(size_t)); memset((void*) density->counters_nan, 0x00, splitter->n_classes * sizeof(size_t)); density->split_value = splitter->partition_values[k]; for (uint j = 0; j < splitter->n_instances; j++) { if (splitter->belongs_to[j] == id) { target_value = splitter->targets[j]; data_point = data[j * n_features + i]; if (data_point == splitter->nan_value) { density->counters_nan[target_value]++; } else if (data_point >= density->split_value) { density->counters_right[target_value]++; } else { density->counters_left[target_value]++; } } } return getFeatureCost(density, splitter->n_classes); } template <typename T> inline double evaluatePartitionsWithRegression(data_t* data, struct Density* density, struct Splitter<T>* splitter, size_t k) { size_t i = splitter->feature_id; size_t n_features = splitter->n_features; data_t data_point; T y; size_t id = splitter->node->id; size_t n_left = 0, n_right = 0; density->split_value = splitter->partition_values[k]; data_t split_value = density->split_value; T mean_left = 0, mean_right = 0; double cost = 0.0; for (uint j = 0; j < splitter->n_instances; j++) { if (splitter->belongs_to[j] == id) { data_point = data[j * n_features + i]; y = splitter->targets[j]; if (data_point == splitter->nan_value) {} else if (data_point >= split_value) { mean_right += y; n_right++; } else { mean_left += y; n_left++; } } } if ((n_left == 0) or (n_right == 0)) { return INFINITY; } mean_left /= n_left; mean_right /= n_right; for (uint j = 0; j < splitter->n_instances; j++) { if (splitter->belongs_to[j] == id) { data_point = data[j * n_features + i]; y = splitter->targets[j]; if (data_point == splitter->nan_value) {} else if (data_point >= split_value) { cost += std::abs(mean_right - y); // TODO : use squared error ? } else { cost += std::abs(mean_right - y); // TODO : use squared error ? } } } return cost; } template <typename T> double evaluateByThreshold(struct Splitter<T>* splitter, struct Density* density, data_t* const data, int partition_value_type) { size_t best_split_id = 0; double lowest_cost = INFINITY; double cost; size_t n_partition_values; switch(partition_value_type) { case gbdf_part::QUARTILE_PARTITIONING: splitter->partition_values = density->quartiles; n_partition_values = 4; break; case gbdf_part::DECILE_PARTITIONING: splitter->partition_values = density->deciles; n_partition_values = 10; break; case gbdf_part::PERCENTILE_PARTITIONING: splitter->partition_values = density->percentiles; n_partition_values = 100; break; default: splitter->partition_values = density->percentiles; n_partition_values = 100; } for (uint k = 1; k < n_partition_values - 1; k++) { if (splitter->task == gbdf_task::CLASSIFICATION_TASK) { cost = evaluatePartitions(data, density, splitter, k); } else { cost = evaluatePartitionsWithRegression(data, density, splitter, k); } if (cost < lowest_cost) { lowest_cost = cost; best_split_id = k; } } if (splitter->task == gbdf_task::CLASSIFICATION_TASK) { evaluatePartitions(data, density, splitter, best_split_id); } else { evaluatePartitionsWithRegression(data, density, splitter, best_split_id); } return lowest_cost; } <commit_msg>Use static_cast rather than C-style cast<commit_after>template <typename T> inline double evaluatePartitions(data_t* data, struct Density* density, struct Splitter<T>* splitter, size_t k) { size_t i = splitter->feature_id; size_t n_features = splitter->n_features; data_t data_point; target_t target_value; size_t id = splitter->node->id; memset(static_cast<void*>(density->counters_left), 0x00, splitter->n_classes * sizeof(size_t)); memset(static_cast<void*>(density->counters_right), 0x00, splitter->n_classes * sizeof(size_t)); memset(static_cast<void*>(density->counters_nan), 0x00, splitter->n_classes * sizeof(size_t)); density->split_value = splitter->partition_values[k]; for (uint j = 0; j < splitter->n_instances; j++) { if (splitter->belongs_to[j] == id) { target_value = splitter->targets[j]; data_point = data[j * n_features + i]; if (data_point == splitter->nan_value) { density->counters_nan[target_value]++; } else if (data_point >= density->split_value) { density->counters_right[target_value]++; } else { density->counters_left[target_value]++; } } } return getFeatureCost(density, splitter->n_classes); } template <typename T> inline double evaluatePartitionsWithRegression(data_t* data, struct Density* density, struct Splitter<T>* splitter, size_t k) { size_t i = splitter->feature_id; size_t n_features = splitter->n_features; data_t data_point; T y; size_t id = splitter->node->id; size_t n_left = 0, n_right = 0; density->split_value = splitter->partition_values[k]; data_t split_value = density->split_value; T mean_left = 0, mean_right = 0; double cost = 0.0; for (uint j = 0; j < splitter->n_instances; j++) { if (splitter->belongs_to[j] == id) { data_point = data[j * n_features + i]; y = splitter->targets[j]; if (data_point == splitter->nan_value) {} else if (data_point >= split_value) { mean_right += y; n_right++; } else { mean_left += y; n_left++; } } } if ((n_left == 0) or (n_right == 0)) { return INFINITY; } mean_left /= n_left; mean_right /= n_right; for (uint j = 0; j < splitter->n_instances; j++) { if (splitter->belongs_to[j] == id) { data_point = data[j * n_features + i]; y = splitter->targets[j]; if (data_point == splitter->nan_value) {} else if (data_point >= split_value) { cost += std::abs(mean_right - y); // TODO : use squared error ? } else { cost += std::abs(mean_right - y); // TODO : use squared error ? } } } return cost; } template <typename T> double evaluateByThreshold(struct Splitter<T>* splitter, struct Density* density, data_t* const data, int partition_value_type) { size_t best_split_id = 0; double lowest_cost = INFINITY; double cost; size_t n_partition_values; switch(partition_value_type) { case gbdf_part::QUARTILE_PARTITIONING: splitter->partition_values = density->quartiles; n_partition_values = 4; break; case gbdf_part::DECILE_PARTITIONING: splitter->partition_values = density->deciles; n_partition_values = 10; break; case gbdf_part::PERCENTILE_PARTITIONING: splitter->partition_values = density->percentiles; n_partition_values = 100; break; default: splitter->partition_values = density->percentiles; n_partition_values = 100; } for (uint k = 1; k < n_partition_values - 1; k++) { if (splitter->task == gbdf_task::CLASSIFICATION_TASK) { cost = evaluatePartitions(data, density, splitter, k); } else { cost = evaluatePartitionsWithRegression(data, density, splitter, k); } if (cost < lowest_cost) { lowest_cost = cost; best_split_id = k; } } if (splitter->task == gbdf_task::CLASSIFICATION_TASK) { evaluatePartitions(data, density, splitter, best_split_id); } else { evaluatePartitionsWithRegression(data, density, splitter, best_split_id); } return lowest_cost; } <|endoftext|>
<commit_before>#include "bspzipgui.h" #include <iostream> #include <QFile> #include <qfiledialog> #include <QMessageBox> #include <QProcess> #include <QSettings> #include <QTextStream> BspZipGui::BspZipGui(QWidget *parent, Qt::WindowFlags flags) : QDialog(parent, flags), bspzip_process_(NULL) //progress_dialog_(NULL) { ui.setupUi(this); bspzip_process_ = new QProcess(this); bool b = connect(bspzip_process_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onBspZipProcessFinished(int, QProcess::ExitStatus))); Q_ASSERT(b); //progress_dialog_ = new QProgressDialog(tr("Performing operation"), // tr("Cancel"), 0, 100, this); //progress_dialog_->setMinimumDuration(0); QSettings settings("settings.ini", QSettings::IniFormat, this); QString bzip = tr("E:\\Games\\Steam\\SteamApps\\common\\nuclear dawn\\bin\\bspzip.exe"); QString bsp = tr("E:\\Games\\Steam\\SteamApps\\common\\nuclear dawn\\nucleardawn\\maps\\sk_sandbrick.bsp"); QString data_folder = tr("D:\\Programming\\AlienSwarmMaps\\nucleardawn\\sk_sandbrick"); ui.bspzip_path->setText(settings.value("BSPZIP_PATH", bzip).toString()); ui.bspfile_path->setText(settings.value("BSP_FILE_PATH", bsp).toString()); ui.data_folder_path->setText(settings.value("DATA_FOLDER_PATH", data_folder).toString()); this->resize(settings.value("SIZE", QSize(this->width(), this->height())).toSize()); } BspZipGui::~BspZipGui() { QSettings settings("settings.ini", QSettings::IniFormat, this); settings.setValue("BSPZIP_PATH", ui.bspzip_path->text()); settings.setValue("BSP_FILE_PATH", ui.bspfile_path->text()); settings.setValue("DATA_FOLDER_PATH", ui.data_folder_path->text()); settings.setValue("SIZE", this->size()); } void BspZipGui::on_browse_bspzip_clicked() { QString default_dir_path;; QFileInfo fi(ui.bspzip_path->text()); if (fi.exists()) { default_dir_path = fi.absolutePath(); } else { default_dir_path = QDir::homePath(); } QFileDialog d; QString path = d.getOpenFileName(this, tr("Select bspzip.exe file"), default_dir_path); if (!path.isEmpty()) ui.bspzip_path->setText(QDir::toNativeSeparators(path)); } void BspZipGui::on_browse_bsp_file_clicked() { QString default_dir_path;; QFileInfo fi(ui.bspfile_path->text()); if (fi.exists()) { default_dir_path = fi.absolutePath(); } else { default_dir_path = QDir::homePath(); } QFileDialog d; QString path = d.getOpenFileName(this, tr("Select BSP file"), default_dir_path); if (!path.isEmpty()) ui.bspfile_path->setText(QDir::toNativeSeparators(path)); } void BspZipGui::on_browse_data_folder_clicked() { QString default_dir_path;; QFileInfo fi(ui.data_folder_path->text()); if (fi.exists()) { if (fi.isDir()) default_dir_path = fi.absoluteFilePath(); else default_dir_path = fi.absolutePath(); } else { default_dir_path = QDir::homePath(); } QFileDialog d; QString path = d.getExistingDirectory(this, tr("Select folder where to extract BSP or which to embed in BSP"), default_dir_path); if (!path.isEmpty()) ui.data_folder_path->setText(QDir::toNativeSeparators(path)); } void BspZipGui::on_embed_clicked() { disableAllButtons(); QStringList check_list; check_list << ui.bspzip_path->text() << ui.bspfile_path->text() << ui.data_folder_path->text(); if (!filesExist(check_list)) { enableAllButtons(); return; } QFile bspzip_filelist_file(QDir::homePath() + "/bspzip_filelist.txt"); log(tr("Opening file for writing: %1").arg( bspzip_filelist_file.fileName() )); if (!bspzip_filelist_file.open(QIODevice::WriteOnly | QIODevice::Text)) { log(tr("Failed to open file for writing: %1").arg(bspzip_filelist_file.fileName())); enableAllButtons(); return; } QDir data_dir( ui.data_folder_path->text(), "", QDir::Name | QDir::IgnoreCase, QDir::AllDirs | QDir::Files| QDir::NoDotAndDotDot ); getDataFolderFiles(data_dir, &data_folder_files_); if (data_folder_files_.isEmpty()) { log(tr("No files found for embedding in directory: %1 Aborting...").arg(data_dir.absolutePath())); enableAllButtons(); return; } log("Adding file list into filelist.txt..."); QTextStream out(&bspzip_filelist_file); QString absolute_file_path; Q_FOREACH(absolute_file_path, data_folder_files_) { absolute_file_path = QDir::toNativeSeparators(absolute_file_path); QString relative_file_path = absolute_file_path.mid(ui.data_folder_path->text().size() + 1); log(relative_file_path); log(absolute_file_path); // no quotes here as BSPZIP doesn't handle them out << relative_file_path << "\n"; out << absolute_file_path << "\n"; } data_folder_files_.clear(); // must be cleared! or we get bugs bspzip_filelist_file.close(); log(tr("File bspzip_filelist.txt was successfully created")); QString bsp_file_path = QDir::toNativeSeparators(ui.bspfile_path->text()); QString filelist_path = QDir::toNativeSeparators(bspzip_filelist_file.fileName()); QStringList process_arguments; process_arguments << "-addorupdatelist"; process_arguments << bsp_file_path; process_arguments << filelist_path; process_arguments << bsp_file_path; // if (bspzip_process_) // { // delete bspzip_process_; // } log(tr("Starting BSPZIP.EXE with following arguments")); Q_FOREACH(QString argument, process_arguments) { log(argument); } bspzip_process_->start(ui.bspzip_path->text(), process_arguments); } void BspZipGui::on_extract_clicked() { QString bsp_file_path = QDir::toNativeSeparators(ui.bspfile_path->text()); QString data_folder = QDir::toNativeSeparators(ui.data_folder_path->text()); QStringList check_list; check_list << ui.bspzip_path->text() << bsp_file_path << data_folder; if (!filesExist(check_list)) { return; } QStringList process_arguments; process_arguments << "-extractfiles"; process_arguments << bsp_file_path; process_arguments << data_folder; // if (bspzip_process_) // { // delete bspzip_process_; // } // bspzip_process_ = new QProcess(this); // bool b = connect(bspzip_process_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onBspZipProcessFinished(int, QProcess::ExitStatus))); // Q_ASSERT(b); bspzip_process_->start(ui.bspzip_path->text(), process_arguments); } void BspZipGui::getDataFolderFiles(const QDir &dir, QStringList *file_list) { QFileInfoList files = dir.entryInfoList(); //log(tr("In directory: %1 parsing...").arg(dir.absolutePath())); Q_FOREACH(QFileInfo file, files) { if (file.isDir()) { QDir d( file.absoluteFilePath(), "", QDir::Name | QDir::IgnoreCase, QDir::AllDirs | QDir::Files| QDir::NoDotAndDotDot ); //QString logstr = tr("Found directory: %1 parsing...").arg(d.absolutePath()); //log(logstr); getDataFolderFiles(d, file_list); } else { (*file_list) << file.absoluteFilePath(); //log(tr("Found file: %1").arg(file.absoluteFilePath())); } } } void BspZipGui::log(const QString &logstr) { ui.console->appendPlainText(logstr); //std::cout << logstr.toLatin1().constData() << std::endl; } void BspZipGui::onBspZipProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { Q_ASSERT(bspzip_process_); QByteArray standard_output = bspzip_process_->readAllStandardOutput(); QByteArray error_output = bspzip_process_->readAllStandardError(); QString status = exitStatus == QProcess::NormalExit ? "Normal" : "Crashed"; log(tr("BSPZIP.exe finished with status: %1, exit code: %2").arg(status).arg(exitCode)); log(tr("BSPZIP.exe output: ")); log(standard_output); if (error_output.size() > 0) { log(tr("BSPZIP.exe error output: ")); log(error_output); } enableAllButtons(); QMessageBox::information( this, tr("Operation Completed"), tr("Operation completed. See output window for details"), QMessageBox::Ok); } bool BspZipGui::filesExist(const QStringList &files) { Q_FOREACH(QString file_path, files) { QFileInfo fi(file_path); if (!fi.exists()) { QMessageBox::warning(this, tr("File Not Found"), tr("The file doesn't exist: %1. Aborting ").arg(file_path)); return false; } } return true; } void BspZipGui::disableAllButtons() { ui.embed->setDisabled(true); ui.extract->setDisabled(true); } void BspZipGui::enableAllButtons() { ui.embed->setEnabled(true); ui.extract->setEnabled(true); } <commit_msg>Add minimize, maximize buttons to the main window<commit_after>#include "bspzipgui.h" #include <iostream> #include <QFile> #include <qfiledialog> #include <QMessageBox> #include <QProcess> #include <QSettings> #include <QTextStream> BspZipGui::BspZipGui(QWidget *parent, Qt::WindowFlags flags) : QDialog(parent, flags), bspzip_process_(NULL) //progress_dialog_(NULL) { ui.setupUi(this); this->setWindowFlags(Qt::Window); bspzip_process_ = new QProcess(this); bool b = connect(bspzip_process_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onBspZipProcessFinished(int, QProcess::ExitStatus))); Q_ASSERT(b); //progress_dialog_ = new QProgressDialog(tr("Performing operation"), // tr("Cancel"), 0, 100, this); //progress_dialog_->setMinimumDuration(0); QSettings settings("settings.ini", QSettings::IniFormat, this); QString bzip = tr("E:\\Games\\Steam\\SteamApps\\common\\nuclear dawn\\bin\\bspzip.exe"); QString bsp = tr("E:\\Games\\Steam\\SteamApps\\common\\nuclear dawn\\nucleardawn\\maps\\sk_sandbrick.bsp"); QString data_folder = tr("D:\\Programming\\AlienSwarmMaps\\nucleardawn\\sk_sandbrick"); ui.bspzip_path->setText(settings.value("BSPZIP_PATH", bzip).toString()); ui.bspfile_path->setText(settings.value("BSP_FILE_PATH", bsp).toString()); ui.data_folder_path->setText(settings.value("DATA_FOLDER_PATH", data_folder).toString()); this->resize(settings.value("SIZE", QSize(this->width(), this->height())).toSize()); } BspZipGui::~BspZipGui() { QSettings settings("settings.ini", QSettings::IniFormat, this); settings.setValue("BSPZIP_PATH", ui.bspzip_path->text()); settings.setValue("BSP_FILE_PATH", ui.bspfile_path->text()); settings.setValue("DATA_FOLDER_PATH", ui.data_folder_path->text()); settings.setValue("SIZE", this->size()); } void BspZipGui::on_browse_bspzip_clicked() { QString default_dir_path;; QFileInfo fi(ui.bspzip_path->text()); if (fi.exists()) { default_dir_path = fi.absolutePath(); } else { default_dir_path = QDir::homePath(); } QFileDialog d; QString path = d.getOpenFileName(this, tr("Select bspzip.exe file"), default_dir_path); if (!path.isEmpty()) ui.bspzip_path->setText(QDir::toNativeSeparators(path)); } void BspZipGui::on_browse_bsp_file_clicked() { QString default_dir_path;; QFileInfo fi(ui.bspfile_path->text()); if (fi.exists()) { default_dir_path = fi.absolutePath(); } else { default_dir_path = QDir::homePath(); } QFileDialog d; QString path = d.getOpenFileName(this, tr("Select BSP file"), default_dir_path); if (!path.isEmpty()) ui.bspfile_path->setText(QDir::toNativeSeparators(path)); } void BspZipGui::on_browse_data_folder_clicked() { QString default_dir_path;; QFileInfo fi(ui.data_folder_path->text()); if (fi.exists()) { if (fi.isDir()) default_dir_path = fi.absoluteFilePath(); else default_dir_path = fi.absolutePath(); } else { default_dir_path = QDir::homePath(); } QFileDialog d; QString path = d.getExistingDirectory(this, tr("Select folder where to extract BSP or which to embed in BSP"), default_dir_path); if (!path.isEmpty()) ui.data_folder_path->setText(QDir::toNativeSeparators(path)); } void BspZipGui::on_embed_clicked() { disableAllButtons(); QStringList check_list; check_list << ui.bspzip_path->text() << ui.bspfile_path->text() << ui.data_folder_path->text(); if (!filesExist(check_list)) { enableAllButtons(); return; } QFile bspzip_filelist_file(QDir::homePath() + "/bspzip_filelist.txt"); log(tr("Opening file for writing: %1").arg( bspzip_filelist_file.fileName() )); if (!bspzip_filelist_file.open(QIODevice::WriteOnly | QIODevice::Text)) { log(tr("Failed to open file for writing: %1").arg(bspzip_filelist_file.fileName())); enableAllButtons(); return; } QDir data_dir( ui.data_folder_path->text(), "", QDir::Name | QDir::IgnoreCase, QDir::AllDirs | QDir::Files| QDir::NoDotAndDotDot ); getDataFolderFiles(data_dir, &data_folder_files_); if (data_folder_files_.isEmpty()) { log(tr("No files found for embedding in directory: %1 Aborting...").arg(data_dir.absolutePath())); enableAllButtons(); return; } log("Adding file list into filelist.txt..."); QTextStream out(&bspzip_filelist_file); QString absolute_file_path; Q_FOREACH(absolute_file_path, data_folder_files_) { absolute_file_path = QDir::toNativeSeparators(absolute_file_path); QString relative_file_path = absolute_file_path.mid(ui.data_folder_path->text().size() + 1); log(relative_file_path); log(absolute_file_path); // no quotes here as BSPZIP doesn't handle them out << relative_file_path << "\n"; out << absolute_file_path << "\n"; } data_folder_files_.clear(); // must be cleared! or we get bugs bspzip_filelist_file.close(); log(tr("File bspzip_filelist.txt was successfully created")); QString bsp_file_path = QDir::toNativeSeparators(ui.bspfile_path->text()); QString filelist_path = QDir::toNativeSeparators(bspzip_filelist_file.fileName()); QStringList process_arguments; process_arguments << "-addorupdatelist"; process_arguments << bsp_file_path; process_arguments << filelist_path; process_arguments << bsp_file_path; // if (bspzip_process_) // { // delete bspzip_process_; // } log(tr("Starting BSPZIP.EXE with following arguments")); Q_FOREACH(QString argument, process_arguments) { log(argument); } bspzip_process_->start(ui.bspzip_path->text(), process_arguments); } void BspZipGui::on_extract_clicked() { QString bsp_file_path = QDir::toNativeSeparators(ui.bspfile_path->text()); QString data_folder = QDir::toNativeSeparators(ui.data_folder_path->text()); QStringList check_list; check_list << ui.bspzip_path->text() << bsp_file_path << data_folder; if (!filesExist(check_list)) { return; } QStringList process_arguments; process_arguments << "-extractfiles"; process_arguments << bsp_file_path; process_arguments << data_folder; // if (bspzip_process_) // { // delete bspzip_process_; // } // bspzip_process_ = new QProcess(this); // bool b = connect(bspzip_process_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onBspZipProcessFinished(int, QProcess::ExitStatus))); // Q_ASSERT(b); bspzip_process_->start(ui.bspzip_path->text(), process_arguments); } void BspZipGui::getDataFolderFiles(const QDir &dir, QStringList *file_list) { QFileInfoList files = dir.entryInfoList(); //log(tr("In directory: %1 parsing...").arg(dir.absolutePath())); Q_FOREACH(QFileInfo file, files) { if (file.isDir()) { QDir d( file.absoluteFilePath(), "", QDir::Name | QDir::IgnoreCase, QDir::AllDirs | QDir::Files| QDir::NoDotAndDotDot ); //QString logstr = tr("Found directory: %1 parsing...").arg(d.absolutePath()); //log(logstr); getDataFolderFiles(d, file_list); } else { (*file_list) << file.absoluteFilePath(); //log(tr("Found file: %1").arg(file.absoluteFilePath())); } } } void BspZipGui::log(const QString &logstr) { ui.console->appendPlainText(logstr); //std::cout << logstr.toLatin1().constData() << std::endl; } void BspZipGui::onBspZipProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { Q_ASSERT(bspzip_process_); QByteArray standard_output = bspzip_process_->readAllStandardOutput(); QByteArray error_output = bspzip_process_->readAllStandardError(); QString status = exitStatus == QProcess::NormalExit ? "Normal" : "Crashed"; log(tr("BSPZIP.exe finished with status: %1, exit code: %2").arg(status).arg(exitCode)); log(tr("BSPZIP.exe output: ")); log(standard_output); if (error_output.size() > 0) { log(tr("BSPZIP.exe error output: ")); log(error_output); } enableAllButtons(); QMessageBox::information( this, tr("Operation Completed"), tr("Operation completed. See output window for details"), QMessageBox::Ok); } bool BspZipGui::filesExist(const QStringList &files) { Q_FOREACH(QString file_path, files) { QFileInfo fi(file_path); if (!fi.exists()) { QMessageBox::warning(this, tr("File Not Found"), tr("The file doesn't exist: %1. Aborting ").arg(file_path)); return false; } } return true; } void BspZipGui::disableAllButtons() { ui.embed->setDisabled(true); ui.extract->setDisabled(true); } void BspZipGui::enableAllButtons() { ui.embed->setEnabled(true); ui.extract->setEnabled(true); } <|endoftext|>
<commit_before>/** @file @brief Main file for a video-based HMD tracker. @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "VideoBasedTracker.h" #include "HDKLedIdentifierFactory.h" #include "CameraParameters.h" #include "ImageSource.h" #include "ImageSourceFactories.h" #include <osvr/PluginKit/PluginKit.h> #include <osvr/PluginKit/TrackerInterfaceC.h> #include "GetOptionalParameter.h" // Generated JSON header file #include "com_osvr_VideoBasedHMDTracker_json.h" // Library/third-party includes #include <opencv2/core/core.hpp> // for basic OpenCV types #include <opencv2/core/operations.hpp> #include <opencv2/highgui/highgui.hpp> // for image capture #include <opencv2/imgproc/imgproc.hpp> // for image scaling #include <json/value.h> #include <json/reader.h> #include <boost/noncopyable.hpp> // Standard includes #include <iostream> #include <iomanip> #include <sstream> #include <memory> // Define the constant below to print timing information (how many updates // per second we are getting). //#define VBHMD_TIMING // Define the constant below to set a directory to save the video frames that // are acquired with files in a format that can later be read by // VBHMD_FAKE_IMAGES //#define VBHMD_SAVE_IMAGES "./Frames" // Anonymous namespace to avoid symbol collision namespace { class VideoBasedHMDTracker : boost::noncopyable { public: VideoBasedHMDTracker(OSVR_PluginRegContext ctx, osvr::vbtracker::ImageSourcePtr &&source, int devNumber = 0, osvr::vbtracker::ConfigParams const &params = osvr::vbtracker::ConfigParams{}) : m_source(std::move(source)), m_vbtracker(params), m_params(params) { // Set the number of threads for OpenCV to use. cv::setNumThreads(params.numThreads); /// Create the initialization options OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx); // Configure the tracker interface. osvrDeviceTrackerConfigure(opts, &m_tracker); /// Come up with a device name std::ostringstream os; os << "TrackedCamera" << devNumber << "_" << 0; /// Create an asynchronous (threaded) device m_dev.initAsync(ctx, os.str(), opts); /// Send JSON descriptor m_dev.sendJsonDescriptor(com_osvr_VideoBasedHMDTracker_json); /// Register update callback m_dev.registerUpdateCallback(this); } OSVR_ReturnCode update(); /// Should be called immediately after construction for specifying the /// particulars of tracking. void addSensor(osvr::vbtracker::LedIdentifierPtr &&identifier, osvr::vbtracker::CameraParameters const &params, osvr::vbtracker::Point3Vector const &locations, size_t requiredInliers = 4, size_t permittedOutliers = 2) { m_vbtracker.addSensor(std::move(identifier), params.cameraMatrix, params.distortionParameters, locations, requiredInliers, permittedOutliers); } void addSensor(osvr::vbtracker::LedIdentifierPtr &&identifier, osvr::vbtracker::CameraParameters const &params, osvr::vbtracker::Point3Vector const &locations, std::vector<double> const &variance, size_t requiredInliers = 4, size_t permittedOutliers = 2) { m_vbtracker.addSensor(std::move(identifier), params.cameraMatrix, params.distortionParameters, locations, variance, requiredInliers, permittedOutliers); } private: osvr::pluginkit::DeviceToken m_dev; OSVR_TrackerDeviceInterface m_tracker; osvr::vbtracker::ImageSourcePtr m_source; osvr::vbtracker::ConfigParams const m_params; #ifdef VBHMD_SAVE_IMAGES int m_imageNum = 1; #endif cv::Mat m_frame; cv::Mat m_imageGray; osvr::vbtracker::VideoBasedTracker m_vbtracker; }; inline OSVR_ReturnCode VideoBasedHMDTracker::update() { if (!m_source->ok()) { // Couldn't open the camera. Failing silently for now. Maybe the // camera will be plugged back in later. return OSVR_RETURN_SUCCESS; } //================================================================== // Trigger a camera grab. if (!m_source->grab()) { // Couldn't open the camera. Failing silently for now. Maybe the // camera will be plugged back in later. return OSVR_RETURN_SUCCESS; } //================================================================== // Keep track of when we got the image, since that is our // best estimate for when the tracker was at the specified // pose. // TODO: Back-date the aquisition time by the expected image // transfer time and perhaps by half the exposure time to say // when the photons actually arrived. OSVR_TimeValue timestamp; osvrTimeValueGetNow(&timestamp); // Pull the image into an OpenCV matrix named m_frame. m_source->retrieve(m_frame, m_imageGray); #ifdef VBHMD_SAVE_IMAGES // If we're supposed to save images, make file names that match the // format we need to read them back in again and save the images. std::ostringstream fileName; fileName << VBHMD_SAVE_IMAGES << "/"; fileName << std::setfill('0') << std::setw(4) << m_imageNum++; fileName << ".tif"; if (!cv::imwrite(fileName.str(), m_frame)) { std::cerr << "Could not write image to " << fileName.str() << std::endl; } #endif #ifdef VBHMD_TIMING //================================================================== // Time our performance static struct timeval last = {0, 0}; if (last.tv_sec == 0) { vrpn_gettimeofday(&last, NULL); } static unsigned count = 0; if (++count == 100) { struct timeval now; vrpn_gettimeofday(&now, NULL); double duration = vrpn_TimevalDurationSeconds(now, last); std::cout << "Video-based tracker: update rate " << count / duration << " hz" << std::endl; count = 0; last = now; } #endif m_vbtracker.processImage( m_frame, m_imageGray, timestamp, [&](OSVR_ChannelCount sensor, OSVR_Pose3 const &pose) { //================================================================== // Report the new pose, time-stamped with the time we // received the image from the camera. osvrDeviceTrackerSendPoseTimestamped(m_dev, m_tracker, &pose, sensor, &timestamp); }); return OSVR_RETURN_SUCCESS; } class HardwareDetection { public: using CameraFactoryType = std::function<osvr::vbtracker::ImageSourcePtr()>; using SensorSetupType = std::function<void(VideoBasedHMDTracker &)>; HardwareDetection(CameraFactoryType camFactory, SensorSetupType setup, int cameraID = 0, osvr::vbtracker::ConfigParams const &params = osvr::vbtracker::ConfigParams{}) : m_found(false), m_cameraFactory(camFactory), m_sensorSetup(setup), m_cameraID(cameraID), m_params(params) {} OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) { if (m_found) { return OSVR_RETURN_SUCCESS; } auto src = m_cameraFactory(); if (!src || !src->ok()) { return OSVR_RETURN_FAILURE; } m_found = true; /// Create our device object, passing the context and moving the camera. std::cout << "Opening camera " << m_cameraID << std::endl; auto newTracker = osvr::pluginkit::registerObjectForDeletion( ctx, new VideoBasedHMDTracker(ctx, std::move(src), m_cameraID, m_params)); m_sensorSetup(*newTracker); return OSVR_RETURN_SUCCESS; } private: /// @brief Have we found our device yet? (this limits the plugin to one /// instance, so that only one tracker will use this camera.) bool m_found = false; CameraFactoryType m_cameraFactory; SensorSetupType m_sensorSetup; int m_cameraID; //< Which OpenCV camera should we open? osvr::vbtracker::ConfigParams const m_params; }; class ConfiguredDeviceConstructor { public: /// @brief This is the required signature for a device instantiation /// callback. OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx, const char *params) { // Read the JSON data from parameters. Json::Value root; if (params) { Json::Reader r; if (!r.parse(params, root)) { std::cerr << "Could not parse parameters!" << std::endl; } } // Read these parameters from a "params" field in the device Json // configuration file. // Using `get` here instead of `[]` lets us provide a default value. int cameraID = root.get("cameraID", 0).asInt(); bool showDebug = root.get("showDebug", false).asBool(); osvr::vbtracker::ConfigParams config; config.debug = showDebug; using osvr::vbtracker::getOptionalParameter; getOptionalParameter(config.additionalPrediction, root, "additionalPrediction"); getOptionalParameter(config.maxResidual, root, "maxResidual"); getOptionalParameter(config.initialBeaconError, root, "initialBeaconError"); getOptionalParameter(config.blobMoveThreshold, root, "blobMoveThreshold"); getOptionalParameter(config.numThreads, root, "numThreads"); Json::Value const &processNoise = root["processNoiseAutocorrelation"]; if (processNoise.isArray()) { if (processNoise.size() != 6) { std::cout << "Got a processNoiseAutocorrelation array, but it " "needs exactly 6 elements, and instead contains " << processNoise.size() << " so will be ignored." << std::endl; } else { for (Json::Value::ArrayIndex i = 0; i < 6; ++i) { config.processNoiseAutocorrelation[i] = processNoise[i].asDouble(); } } } getOptionalParameter(config.linearVelocityDecayCoefficient, root, "linearVelocityDecayCoefficient"); getOptionalParameter(config.angularVelocityDecayCoefficient, root, "angularVelocityDecayCoefficient"); getOptionalParameter(config.measurementVarianceScaleFactor, root, "measurementVarianceScaleFactor"); if (root.isMember("blobParams")) { Json::Value const &blob = root["blobParams"]; getOptionalParameter(config.blobParams.absoluteMinThreshold, blob, "absoluteMinThreshold"); getOptionalParameter(config.blobParams.minDistBetweenBlobs, blob, "minDistBetweenBlobs"); getOptionalParameter(config.blobParams.minArea, blob, "minArea"); getOptionalParameter(config.blobParams.minCircularity, blob, "minCircularity"); getOptionalParameter(config.blobParams.minThresholdAlpha, blob, "minThresholdAlpha"); getOptionalParameter(config.blobParams.maxThresholdAlpha, blob, "maxThresholdAlpha"); getOptionalParameter(config.blobParams.thresholdSteps, blob, "thresholdSteps"); } /// @todo get this (and the path) from the config file bool fakeImages = false; if (fakeImages) { /// Immediately create a "fake images" tracker. auto path = std::string{}; // fake images auto src = osvr::vbtracker::openImageFileSequence(path); if (!src) { return OSVR_RETURN_FAILURE; } auto newTracker = osvr::pluginkit::registerObjectForDeletion( ctx, new VideoBasedHMDTracker(ctx, std::move(src), cameraID, config)); auto camParams = osvr::vbtracker::getSimulatedHDKCameraParameters(); newTracker->addSensor( osvr::vbtracker::createHDKLedIdentifierSimulated(0), camParams, osvr::vbtracker::OsvrHdkLedLocations_SENSOR0, 4, 2); // There are sometimes only four beacons on the back unit (two of // the LEDs are disabled), so we let things work with just those. newTracker->addSensor( osvr::vbtracker::createHDKLedIdentifierSimulated(1), camParams, osvr::vbtracker::OsvrHdkLedLocations_SENSOR1, 4, 0); return OSVR_RETURN_SUCCESS; } #if 0 bool isOculusCamera = (width == 376) && (height == 480); #endif #ifdef _WIN32 /// @todo speed of a function pointer here vs a lambda? auto cameraFactory = &osvr::vbtracker::openHDKCameraDirectShow; #else // !_WIN32 /// @todo This is rather crude, as we can't select the exact camera we /// want, nor set the "50Hz" high-gain mode (and only works with HDK /// camera firmware v7 and up). Presumably eventually use libuvc on /// other platforms instead, at least for the HDK IR camera. auto cameraFactory = [=] { return osvr::vbtracker::openOpenCVCamera(cameraID); }; #endif /// Function to execute after the device is created, to add the sensors. auto setupHDKParamsAndSensors = [](VideoBasedHMDTracker &newTracker) { auto camParams = osvr::vbtracker::getHDKCameraParameters(); newTracker.addSensor( osvr::vbtracker::createHDKLedIdentifier(0), camParams, osvr::vbtracker::OsvrHdkLedLocations_SENSOR0, osvr::vbtracker::OsvrHdkLedVariances_SENSOR0, 6, 0); newTracker.addSensor( osvr::vbtracker::createHDKLedIdentifier(1), camParams, osvr::vbtracker::OsvrHdkLedLocations_SENSOR1, 4, 0); }; // OK, now that we have our parameters, create the device. osvr::pluginkit::PluginContext context(ctx); context.registerHardwareDetectCallback(new HardwareDetection( cameraFactory, setupHDKParamsAndSensors, cameraID, config)); return OSVR_RETURN_SUCCESS; } }; } // namespace OSVR_PLUGIN(com_osvr_VideoBasedHMDTracker) { osvr::pluginkit::PluginContext context(ctx); /// Tell the core we're available to create a device object. osvr::pluginkit::registerDriverInstantiationCallback( ctx, "VideoBasedHMDTracker", new ConfiguredDeviceConstructor); return OSVR_RETURN_SUCCESS; } <commit_msg>Use the new overload to read the noise params<commit_after>/** @file @brief Main file for a video-based HMD tracker. @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "VideoBasedTracker.h" #include "HDKLedIdentifierFactory.h" #include "CameraParameters.h" #include "ImageSource.h" #include "ImageSourceFactories.h" #include <osvr/PluginKit/PluginKit.h> #include <osvr/PluginKit/TrackerInterfaceC.h> #include "GetOptionalParameter.h" // Generated JSON header file #include "com_osvr_VideoBasedHMDTracker_json.h" // Library/third-party includes #include <opencv2/core/core.hpp> // for basic OpenCV types #include <opencv2/core/operations.hpp> #include <opencv2/highgui/highgui.hpp> // for image capture #include <opencv2/imgproc/imgproc.hpp> // for image scaling #include <json/value.h> #include <json/reader.h> #include <boost/noncopyable.hpp> // Standard includes #include <iostream> #include <iomanip> #include <sstream> #include <memory> // Define the constant below to print timing information (how many updates // per second we are getting). //#define VBHMD_TIMING // Define the constant below to set a directory to save the video frames that // are acquired with files in a format that can later be read by // VBHMD_FAKE_IMAGES //#define VBHMD_SAVE_IMAGES "./Frames" // Anonymous namespace to avoid symbol collision namespace { class VideoBasedHMDTracker : boost::noncopyable { public: VideoBasedHMDTracker(OSVR_PluginRegContext ctx, osvr::vbtracker::ImageSourcePtr &&source, int devNumber = 0, osvr::vbtracker::ConfigParams const &params = osvr::vbtracker::ConfigParams{}) : m_source(std::move(source)), m_vbtracker(params), m_params(params) { // Set the number of threads for OpenCV to use. cv::setNumThreads(params.numThreads); /// Create the initialization options OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx); // Configure the tracker interface. osvrDeviceTrackerConfigure(opts, &m_tracker); /// Come up with a device name std::ostringstream os; os << "TrackedCamera" << devNumber << "_" << 0; /// Create an asynchronous (threaded) device m_dev.initAsync(ctx, os.str(), opts); /// Send JSON descriptor m_dev.sendJsonDescriptor(com_osvr_VideoBasedHMDTracker_json); /// Register update callback m_dev.registerUpdateCallback(this); } OSVR_ReturnCode update(); /// Should be called immediately after construction for specifying the /// particulars of tracking. void addSensor(osvr::vbtracker::LedIdentifierPtr &&identifier, osvr::vbtracker::CameraParameters const &params, osvr::vbtracker::Point3Vector const &locations, size_t requiredInliers = 4, size_t permittedOutliers = 2) { m_vbtracker.addSensor(std::move(identifier), params.cameraMatrix, params.distortionParameters, locations, requiredInliers, permittedOutliers); } void addSensor(osvr::vbtracker::LedIdentifierPtr &&identifier, osvr::vbtracker::CameraParameters const &params, osvr::vbtracker::Point3Vector const &locations, std::vector<double> const &variance, size_t requiredInliers = 4, size_t permittedOutliers = 2) { m_vbtracker.addSensor(std::move(identifier), params.cameraMatrix, params.distortionParameters, locations, variance, requiredInliers, permittedOutliers); } private: osvr::pluginkit::DeviceToken m_dev; OSVR_TrackerDeviceInterface m_tracker; osvr::vbtracker::ImageSourcePtr m_source; osvr::vbtracker::ConfigParams const m_params; #ifdef VBHMD_SAVE_IMAGES int m_imageNum = 1; #endif cv::Mat m_frame; cv::Mat m_imageGray; osvr::vbtracker::VideoBasedTracker m_vbtracker; }; inline OSVR_ReturnCode VideoBasedHMDTracker::update() { if (!m_source->ok()) { // Couldn't open the camera. Failing silently for now. Maybe the // camera will be plugged back in later. return OSVR_RETURN_SUCCESS; } //================================================================== // Trigger a camera grab. if (!m_source->grab()) { // Couldn't open the camera. Failing silently for now. Maybe the // camera will be plugged back in later. return OSVR_RETURN_SUCCESS; } //================================================================== // Keep track of when we got the image, since that is our // best estimate for when the tracker was at the specified // pose. // TODO: Back-date the aquisition time by the expected image // transfer time and perhaps by half the exposure time to say // when the photons actually arrived. OSVR_TimeValue timestamp; osvrTimeValueGetNow(&timestamp); // Pull the image into an OpenCV matrix named m_frame. m_source->retrieve(m_frame, m_imageGray); #ifdef VBHMD_SAVE_IMAGES // If we're supposed to save images, make file names that match the // format we need to read them back in again and save the images. std::ostringstream fileName; fileName << VBHMD_SAVE_IMAGES << "/"; fileName << std::setfill('0') << std::setw(4) << m_imageNum++; fileName << ".tif"; if (!cv::imwrite(fileName.str(), m_frame)) { std::cerr << "Could not write image to " << fileName.str() << std::endl; } #endif #ifdef VBHMD_TIMING //================================================================== // Time our performance static struct timeval last = {0, 0}; if (last.tv_sec == 0) { vrpn_gettimeofday(&last, NULL); } static unsigned count = 0; if (++count == 100) { struct timeval now; vrpn_gettimeofday(&now, NULL); double duration = vrpn_TimevalDurationSeconds(now, last); std::cout << "Video-based tracker: update rate " << count / duration << " hz" << std::endl; count = 0; last = now; } #endif m_vbtracker.processImage( m_frame, m_imageGray, timestamp, [&](OSVR_ChannelCount sensor, OSVR_Pose3 const &pose) { //================================================================== // Report the new pose, time-stamped with the time we // received the image from the camera. osvrDeviceTrackerSendPoseTimestamped(m_dev, m_tracker, &pose, sensor, &timestamp); }); return OSVR_RETURN_SUCCESS; } class HardwareDetection { public: using CameraFactoryType = std::function<osvr::vbtracker::ImageSourcePtr()>; using SensorSetupType = std::function<void(VideoBasedHMDTracker &)>; HardwareDetection(CameraFactoryType camFactory, SensorSetupType setup, int cameraID = 0, osvr::vbtracker::ConfigParams const &params = osvr::vbtracker::ConfigParams{}) : m_found(false), m_cameraFactory(camFactory), m_sensorSetup(setup), m_cameraID(cameraID), m_params(params) {} OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) { if (m_found) { return OSVR_RETURN_SUCCESS; } auto src = m_cameraFactory(); if (!src || !src->ok()) { return OSVR_RETURN_FAILURE; } m_found = true; /// Create our device object, passing the context and moving the camera. std::cout << "Opening camera " << m_cameraID << std::endl; auto newTracker = osvr::pluginkit::registerObjectForDeletion( ctx, new VideoBasedHMDTracker(ctx, std::move(src), m_cameraID, m_params)); m_sensorSetup(*newTracker); return OSVR_RETURN_SUCCESS; } private: /// @brief Have we found our device yet? (this limits the plugin to one /// instance, so that only one tracker will use this camera.) bool m_found = false; CameraFactoryType m_cameraFactory; SensorSetupType m_sensorSetup; int m_cameraID; //< Which OpenCV camera should we open? osvr::vbtracker::ConfigParams const m_params; }; class ConfiguredDeviceConstructor { public: /// @brief This is the required signature for a device instantiation /// callback. OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx, const char *params) { // Read the JSON data from parameters. Json::Value root; if (params) { Json::Reader r; if (!r.parse(params, root)) { std::cerr << "Could not parse parameters!" << std::endl; } } // Read these parameters from a "params" field in the device Json // configuration file. // Using `get` here instead of `[]` lets us provide a default value. int cameraID = root.get("cameraID", 0).asInt(); bool showDebug = root.get("showDebug", false).asBool(); osvr::vbtracker::ConfigParams config; config.debug = showDebug; using osvr::vbtracker::getOptionalParameter; getOptionalParameter(config.additionalPrediction, root, "additionalPrediction"); getOptionalParameter(config.maxResidual, root, "maxResidual"); getOptionalParameter(config.initialBeaconError, root, "initialBeaconError"); getOptionalParameter(config.blobMoveThreshold, root, "blobMoveThreshold"); getOptionalParameter(config.numThreads, root, "numThreads"); getOptionalParameter(config.processNoiseAutocorrelation, root, "processNoiseAutocorrelation"); getOptionalParameter(config.linearVelocityDecayCoefficient, root, "linearVelocityDecayCoefficient"); getOptionalParameter(config.angularVelocityDecayCoefficient, root, "angularVelocityDecayCoefficient"); getOptionalParameter(config.measurementVarianceScaleFactor, root, "measurementVarianceScaleFactor"); if (root.isMember("blobParams")) { Json::Value const &blob = root["blobParams"]; getOptionalParameter(config.blobParams.absoluteMinThreshold, blob, "absoluteMinThreshold"); getOptionalParameter(config.blobParams.minDistBetweenBlobs, blob, "minDistBetweenBlobs"); getOptionalParameter(config.blobParams.minArea, blob, "minArea"); getOptionalParameter(config.blobParams.minCircularity, blob, "minCircularity"); getOptionalParameter(config.blobParams.minThresholdAlpha, blob, "minThresholdAlpha"); getOptionalParameter(config.blobParams.maxThresholdAlpha, blob, "maxThresholdAlpha"); getOptionalParameter(config.blobParams.thresholdSteps, blob, "thresholdSteps"); } /// @todo get this (and the path) from the config file bool fakeImages = false; if (fakeImages) { /// Immediately create a "fake images" tracker. auto path = std::string{}; // fake images auto src = osvr::vbtracker::openImageFileSequence(path); if (!src) { return OSVR_RETURN_FAILURE; } auto newTracker = osvr::pluginkit::registerObjectForDeletion( ctx, new VideoBasedHMDTracker(ctx, std::move(src), cameraID, config)); auto camParams = osvr::vbtracker::getSimulatedHDKCameraParameters(); newTracker->addSensor( osvr::vbtracker::createHDKLedIdentifierSimulated(0), camParams, osvr::vbtracker::OsvrHdkLedLocations_SENSOR0, 4, 2); // There are sometimes only four beacons on the back unit (two of // the LEDs are disabled), so we let things work with just those. newTracker->addSensor( osvr::vbtracker::createHDKLedIdentifierSimulated(1), camParams, osvr::vbtracker::OsvrHdkLedLocations_SENSOR1, 4, 0); return OSVR_RETURN_SUCCESS; } #if 0 bool isOculusCamera = (width == 376) && (height == 480); #endif #ifdef _WIN32 /// @todo speed of a function pointer here vs a lambda? auto cameraFactory = &osvr::vbtracker::openHDKCameraDirectShow; #else // !_WIN32 /// @todo This is rather crude, as we can't select the exact camera we /// want, nor set the "50Hz" high-gain mode (and only works with HDK /// camera firmware v7 and up). Presumably eventually use libuvc on /// other platforms instead, at least for the HDK IR camera. auto cameraFactory = [=] { return osvr::vbtracker::openOpenCVCamera(cameraID); }; #endif /// Function to execute after the device is created, to add the sensors. auto setupHDKParamsAndSensors = [](VideoBasedHMDTracker &newTracker) { auto camParams = osvr::vbtracker::getHDKCameraParameters(); newTracker.addSensor( osvr::vbtracker::createHDKLedIdentifier(0), camParams, osvr::vbtracker::OsvrHdkLedLocations_SENSOR0, osvr::vbtracker::OsvrHdkLedVariances_SENSOR0, 6, 0); newTracker.addSensor( osvr::vbtracker::createHDKLedIdentifier(1), camParams, osvr::vbtracker::OsvrHdkLedLocations_SENSOR1, 4, 0); }; // OK, now that we have our parameters, create the device. osvr::pluginkit::PluginContext context(ctx); context.registerHardwareDetectCallback(new HardwareDetection( cameraFactory, setupHDKParamsAndSensors, cameraID, config)); return OSVR_RETURN_SUCCESS; } }; } // namespace OSVR_PLUGIN(com_osvr_VideoBasedHMDTracker) { osvr::pluginkit::PluginContext context(ctx); /// Tell the core we're available to create a device object. osvr::pluginkit::registerDriverInstantiationCallback( ctx, "VideoBasedHMDTracker", new ConfiguredDeviceConstructor); return OSVR_RETURN_SUCCESS; } <|endoftext|>
<commit_before>// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include <hal.h> #include <cmsis_os.h> #include "nanoCLR_Types.h" #if (__CORTEX_M == 0) #error "ITM port is not available on Cortex-M0(+) cores. Need to set CMake option SWO_OUTPUT to OFF." #else // number of attempts to write to the ITM port before quit #define ITM_WRITE_ATTEMPTS 10 extern "C" void SwoInit() { // set SWO pin (PB3) to alternate mode (0 == the status after RESET) // in case it's being set to a different function in board config palSetPadMode(GPIOB, 0x03, PAL_MODE_ALTERNATE(0) ); // enable trace in core debug register CoreDebug->DEMCR = CoreDebug_DEMCR_TRCENA_Msk; // enable trace pins with async trace DBGMCU->CR |= DBGMCU_CR_TRACE_IOEN | ~DBGMCU_CR_TRACE_MODE; // default speed for ST-Link is 2000kHz uint32_t swoSpeed = 2000000; uint32_t swoPrescaler = (STM32_SYSCLK / swoSpeed) + 1; // Write the TPIU Current Port Size Register to the desired value (default is 0x1 for a 1-bit port size) TPI->CSPSR = 1; // Write TPIU Formatter and Flush Control Register TPI->FFCR = 0x100; // Write the TPIU Select Pin Protocol to select the sync or async mode. Example: 0x2 for async NRZ mode (UART like) TPI->SPPR = 2; // Write clock prescaler TPI->ACPR = swoPrescaler; // unlock Write Access to the ITM registers ITM->LAR = 0xC5ACCE55; // core debug: // Trace bus ID for TPIU // enable events // enable sync packets // time stamp enable // trace main enable ITM->TCR = ITM_TCR_TraceBusID_Msk | ITM_TCR_SWOENA_Msk | ITM_TCR_SYNCENA_Msk | ITM_TCR_ITMENA_Msk; /* ITM Trace Control Register */ // enable stimulus port 0 // we are not using any other port right now ITM->TER |= 1; ITM->TPR = ITM_TPR_PRIVMASK_Msk; } extern "C" void SwoPrintChar(char c) { ASSERT((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL); ASSERT((ITM->TER & 1UL ) != 0UL); uint32_t retryCounter = ITM_WRITE_ATTEMPTS; bool okToTx = ITM->PORT[0U].u32 == 0UL; // wait (with timeout) until ITM port TX buffer is available while( !okToTx && (retryCounter > 0) ) { // do... nothing __NOP(); // decrease retry counter retryCounter--; // check again okToTx = (ITM->PORT[0U].u32 == 0UL); } if(okToTx) { ITM->PORT[0U].u8 = (uint8_t)c; } } extern "C" void SwoPrintString(const char *s) { // print char until terminator is found while(*s) { SwoPrintChar(*s++); } } // this function is heavily based in the CMSIS ITM_SendChar // but with small performance improvements as we are sending a string not individual chars __STATIC_INLINE uint32_t GenericPort_Write_CMSIS(int portNum, const char* data, size_t size) { (void)portNum; ASSERT((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL); ASSERT((ITM->TER & 1UL ) != 0UL); char* p = (char*)data; uint32_t counter = 0; uint32_t retryCounter; bool okToTx = ITM->PORT[0U].u32 == 0UL; while( *p != '\0' && counter < size ) { retryCounter = ITM_WRITE_ATTEMPTS; // wait (with timeout) until ITM port TX buffer is available while( !okToTx && (retryCounter > 0) ) { // do... nothing __NOP(); // decrease retry counter retryCounter--; // check again okToTx = (ITM->PORT[0U].u32 == 0UL); } if(okToTx) { ITM->PORT[0U].u8 = (uint8_t)*p++; } counter++; } return counter; } uint32_t GenericPort_Write(int portNum, const char* data, size_t size) { return GenericPort_Write_CMSIS(portNum, data, size); } #endif // (__CORTEX_M == 0) <commit_msg>Fix SWO output (#1535)<commit_after>// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include <hal.h> #include <cmsis_os.h> #include "nanoCLR_Types.h" #if (__CORTEX_M == 0) #error "ITM port is not available on Cortex-M0(+) cores. Need to set CMake option SWO_OUTPUT to OFF." #else // number of attempts to write to the ITM port before quitting // developer note: this is an arbitrary value from trial & error attempts to get a satisfactory output on ST-Link SWO viewer #define ITM_WRITE_ATTEMPTS 20000 extern "C" void SwoInit() { // set SWO pin (PB3) to alternate mode (0 == the status after RESET) // in case it's being set to a different function in board config palSetPadMode(GPIOB, 0x03, PAL_MODE_ALTERNATE(0) ); // enable trace in core debug register CoreDebug->DEMCR = CoreDebug_DEMCR_TRCENA_Msk; // enable trace pins with async trace DBGMCU->CR |= DBGMCU_CR_TRACE_IOEN | ~DBGMCU_CR_TRACE_MODE; // default speed for ST-Link is 2000kHz uint32_t swoSpeed = 2000000; uint32_t swoPrescaler = (STM32_SYSCLK / swoSpeed) + 1; // Write the TPIU Current Port Size Register to the desired value (default is 0x1 for a 1-bit port size) TPI->CSPSR = 1; // Write TPIU Formatter and Flush Control Register TPI->FFCR = 0x100; // Write the TPIU Select Pin Protocol to select the sync or async mode. Example: 0x2 for async NRZ mode (UART like) TPI->SPPR = 2; // Write clock prescaler TPI->ACPR = swoPrescaler; // unlock Write Access to the ITM registers ITM->LAR = 0xC5ACCE55; // core debug: // Trace bus ID for TPIU // enable events // enable sync packets // time stamp enable // trace main enable ITM->TCR = ITM_TCR_TraceBusID_Msk | ITM_TCR_SWOENA_Msk | ITM_TCR_SYNCENA_Msk | ITM_TCR_ITMENA_Msk; /* ITM Trace Control Register */ // enable stimulus port 0 // we are not using any other port right now ITM->TER |= 1; ITM->TPR = ITM_TPR_PRIVMASK_Msk; } extern "C" void SwoPrintChar(char c) { ASSERT((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL); ASSERT((ITM->TER & 1UL ) != 0UL); uint32_t retryCounter = ITM_WRITE_ATTEMPTS; bool okToTx = (ITM->PORT[0U].u32 == 1UL); // wait (with timeout) until ITM port TX buffer is available while( !okToTx && (retryCounter > 0) ) { // do... nothing __NOP(); // decrease retry counter retryCounter--; // check again okToTx = (ITM->PORT[0U].u32 == 1UL); } if(okToTx) { ITM->PORT[0U].u8 = (uint8_t)c; } } extern "C" void SwoPrintString(const char *s) { // print char until terminator is found while(*s) { SwoPrintChar(*s++); } } // this function is heavily based in the CMSIS ITM_SendChar // but with small performance improvements as we are sending a string not individual chars __STATIC_INLINE uint32_t GenericPort_Write_CMSIS(int portNum, const char* data, size_t size) { (void)portNum; ASSERT((ITM->TCR & ITM_TCR_ITMENA_Msk) != 0UL); ASSERT((ITM->TER & 1UL ) != 0UL); char* p = (char*)data; uint32_t counter = 0; uint32_t retryCounter; bool okToTx; while( *p != '\0' && counter < size ) { retryCounter = ITM_WRITE_ATTEMPTS; okToTx = (ITM->PORT[0U].u32 == 1UL); // wait (with timeout) until ITM port TX buffer is available while( !okToTx && (retryCounter > 0) ) { // do... nothing __NOP(); // decrease retry counter retryCounter--; // check again okToTx = (ITM->PORT[0U].u32 == 1UL); } if(okToTx) { ITM->PORT[0U].u8 = (uint8_t)*p++; } counter++; } return counter; } uint32_t GenericPort_Write(int portNum, const char* data, size_t size) { return GenericPort_Write_CMSIS(portNum, data, size); } #endif // (__CORTEX_M == 0) <|endoftext|>
<commit_before>#ifndef _SDD_DD_NODE_HH_ #define _SDD_DD_NODE_HH_ #include <algorithm> // equal, for_each #include <functional> // hash #include <iosfwd> #include "sdd/dd/alpha.hh" #include "sdd/dd/definition.hh" #include "sdd/internal/util/hash.hh" #include "sdd/internal/util/packed.hh" namespace sdd { /*-------------------------------------------------------------------------------------------*/ /// @brief A non-terminal node in an SDD. /// \tparam Valuation If a set of values, define a flat node; if an SDD, define a hierarchical /// node. /// /// For the sake of canonicity, a node shall not exist in several locations, thus we prevent /// its copy. Also, to enforce this canonicity, we need that nodes have always the same /// address, thus they can't be moved to an other memory location once created. template <typename C, typename Valuation> class _LIBSDD_ATTRIBUTE_PACKED node { // Can't copy a node. node& operator=(const node&) = delete; node(const node&) = delete; // Can't move a node. node& operator=(node&&) = delete; node(node&&) = delete; public: /// @brief The type of the variable of this node. typedef typename C::Variable variable_type; /// @brief The type of the valuation of this node. typedef Valuation valuation_type; /// @brief The type used to store the number of arcs of this node. typedef typename C::alpha_size_type alpha_size_type; /// @brief A (const) iterator on the arcs of this node. typedef const arc<C, Valuation>* const_iterator; private: /// @brief The variable of this node. const variable_type variable_; /// @brief The number of arcs of this node. const alpha_size_type size_; public: /// @brief Constructor. /// /// O(n) where n is the number of arcs in the builder. /// It can't throw as the memory for the alpha has already been allocated. node(const variable_type& var, alpha_builder<C, Valuation>& builder) noexcept : variable_(var) , size_(static_cast<alpha_size_type>(builder.size())) { // Instruct the alpha builder to place it right after the node. builder.consolidate(alpha_addr()); } /// @brief Destructor. /// /// O(n) where n is the number of arcs in the node. ~node() { for (auto& arc : *this) { arc.~arc<C, Valuation>(); } } /// @brief Get the variable of this node. /// /// O(1). const variable_type& variable() const noexcept { return variable_; } /// @brief Get the beginning of arcs. /// /// O(1). const_iterator begin() const noexcept { return reinterpret_cast<const arc<C, Valuation>*>(alpha_addr()); } /// @brief Get the end of arcs. /// /// O(1). const_iterator end() const noexcept { return reinterpret_cast<const arc<C, Valuation>*>(alpha_addr()) + size_; } /// @brief Get the number of arcs. /// /// O(1). alpha_size_type size() const noexcept { return size_; } private: /// @brief Return the address of the alpha function. /// /// O(1). /// The alpha function is located right after the current node, so to compute its address, /// we just have to add the size of a node to the address of the current node. char* alpha_addr() const noexcept { return reinterpret_cast<char*>(const_cast<node*>(this)) + sizeof(node); } }; /*-------------------------------------------------------------------------------------------*/ /// @brief Equality of two nodes. /// @related node /// /// O(1) if nodes don't have the same number of arcs; otherwise O(n) where n is the number of /// arcs. template <typename C, typename Valuation> inline bool operator==(const node<C, Valuation>& lhs, const node<C, Valuation>& rhs) noexcept { return lhs.size() == rhs.size() and lhs.variable() == rhs.variable() and std::equal(lhs.begin(), lhs.end(), rhs.begin()); } /// @brief Export a node to a stream. /// @related node template <typename C, typename Valuation> std::ostream& operator<<(std::ostream& os, const node<C, Valuation>& n) { os << n.variable() << "["; std::for_each( n.begin(), n.end() - 1 , [&](const arc<C, Valuation>& a) {os << a.valuation() << " --> " << a.successor() << " || ";}); return os << (n.end() - 1)->valuation() << " --> " << (n.end() - 1)->successor() << "]"; } /*-------------------------------------------------------------------------------------------*/ } // namespace sdd /// @cond INTERNAL_DOC namespace std { /*-------------------------------------------------------------------------------------------*/ /// @brief Hash specialization for sdd::node template <typename C, typename Valuation> struct hash<sdd::node<C, Valuation>> { std::size_t operator()(const sdd::node<C, Valuation>& n) const noexcept { std::size_t seed = 0; sdd::internal::util::hash_combine(seed, n.variable()); for (auto& arc : n) { sdd::internal::util::hash_combine(seed, arc.valuation()); sdd::internal::util::hash_combine(seed, arc.successor()); } return seed; } }; /*-------------------------------------------------------------------------------------------*/ } // namespace std /// @endcond #endif // _SDD_DD_NODE_HH_ <commit_msg>Renaming for gcc.<commit_after>#ifndef _SDD_DD_NODE_HH_ #define _SDD_DD_NODE_HH_ #include <algorithm> // equal, for_each #include <functional> // hash #include <iosfwd> #include "sdd/dd/alpha.hh" #include "sdd/dd/definition.hh" #include "sdd/internal/util/hash.hh" #include "sdd/internal/util/packed.hh" namespace sdd { /*-------------------------------------------------------------------------------------------*/ /// @brief A non-terminal node in an SDD. /// \tparam Valuation If a set of values, define a flat node; if an SDD, define a hierarchical /// node. /// /// For the sake of canonicity, a node shall not exist in several locations, thus we prevent /// its copy. Also, to enforce this canonicity, we need that nodes have always the same /// address, thus they can't be moved to an other memory location once created. template <typename C, typename Valuation> class _LIBSDD_ATTRIBUTE_PACKED node { // Can't copy a node. node& operator=(const node&) = delete; node(const node&) = delete; // Can't move a node. node& operator=(node&&) = delete; node(node&&) = delete; public: /// @brief The type of the variable of this node. typedef typename C::Variable variable_type; /// @brief The type of the valuation of this node. typedef Valuation valuation_type; /// @brief The type used to store the number of arcs of this node. typedef typename C::alpha_size_type alpha_size_type; /// @brief A (const) iterator on the arcs of this node. typedef const arc<C, Valuation>* const_iterator; private: /// @brief The variable of this node. const variable_type variable_; /// @brief The number of arcs of this node. const alpha_size_type size_; public: /// @brief Constructor. /// /// O(n) where n is the number of arcs in the builder. /// It can't throw as the memory for the alpha has already been allocated. node(const variable_type& var, alpha_builder<C, Valuation>& builder) noexcept : variable_(var) , size_(static_cast<alpha_size_type>(builder.size())) { // Instruct the alpha builder to place it right after the node. builder.consolidate(alpha_addr()); } /// @brief Destructor. /// /// O(n) where n is the number of arcs in the node. ~node() { for (auto& a : *this) { a.~arc<C, Valuation>(); } } /// @brief Get the variable of this node. /// /// O(1). const variable_type& variable() const noexcept { return variable_; } /// @brief Get the beginning of arcs. /// /// O(1). const_iterator begin() const noexcept { return reinterpret_cast<const arc<C, Valuation>*>(alpha_addr()); } /// @brief Get the end of arcs. /// /// O(1). const_iterator end() const noexcept { return reinterpret_cast<const arc<C, Valuation>*>(alpha_addr()) + size_; } /// @brief Get the number of arcs. /// /// O(1). alpha_size_type size() const noexcept { return size_; } private: /// @brief Return the address of the alpha function. /// /// O(1). /// The alpha function is located right after the current node, so to compute its address, /// we just have to add the size of a node to the address of the current node. char* alpha_addr() const noexcept { return reinterpret_cast<char*>(const_cast<node*>(this)) + sizeof(node); } }; /*-------------------------------------------------------------------------------------------*/ /// @brief Equality of two nodes. /// @related node /// /// O(1) if nodes don't have the same number of arcs; otherwise O(n) where n is the number of /// arcs. template <typename C, typename Valuation> inline bool operator==(const node<C, Valuation>& lhs, const node<C, Valuation>& rhs) noexcept { return lhs.size() == rhs.size() and lhs.variable() == rhs.variable() and std::equal(lhs.begin(), lhs.end(), rhs.begin()); } /// @brief Export a node to a stream. /// @related node template <typename C, typename Valuation> std::ostream& operator<<(std::ostream& os, const node<C, Valuation>& n) { os << n.variable() << "["; std::for_each( n.begin(), n.end() - 1 , [&](const arc<C, Valuation>& a) {os << a.valuation() << " --> " << a.successor() << " || ";}); return os << (n.end() - 1)->valuation() << " --> " << (n.end() - 1)->successor() << "]"; } /*-------------------------------------------------------------------------------------------*/ } // namespace sdd /// @cond INTERNAL_DOC namespace std { /*-------------------------------------------------------------------------------------------*/ /// @brief Hash specialization for sdd::node template <typename C, typename Valuation> struct hash<sdd::node<C, Valuation>> { std::size_t operator()(const sdd::node<C, Valuation>& n) const noexcept { std::size_t seed = 0; sdd::internal::util::hash_combine(seed, n.variable()); for (auto& arc : n) { sdd::internal::util::hash_combine(seed, arc.valuation()); sdd::internal::util::hash_combine(seed, arc.successor()); } return seed; } }; /*-------------------------------------------------------------------------------------------*/ } // namespace std /// @endcond #endif // _SDD_DD_NODE_HH_ <|endoftext|>
<commit_before>#ifndef RING_BUFFER_HPP #define RING_BUFFER_HPP #include <boost/assert.hpp> static const size_t RING_SIZE=1048576; template<class T> class Sample { public: Sample() : mpSample(0), mLength(0) {} Sample(const Sample &copy) : mpSample(copy.mpSample), mLength(copy.mLength) { } ~Sample() { mpSample = 0; mLength = 0; } Sample& operator=(const Sample& other) { mpSample = other.mpSample; mLength = other.mLength; return *this; } void configure(T* pSample, int length) { mpSample = pSample; mLength = length; } T* sample() { return mpSample; } size_t length() { return mLength; } private: T* mpSample; int mLength; }; template<class T> class SampleBuffer { public: SampleBuffer() : mpBuffer(0), mPosition(0) { mpBuffer = new T[RING_SIZE]; } SampleBuffer(const SampleBuffer& copy) :mpBuffer(copy.mpBuffer), mPosition(copy.mPosition) { } SampleBuffer& operator=(const SampleBuffer& other) { mpBuffer = other.mpBuffer; mPosition = other.mPosition; } ~SampleBuffer() { BOOST_VERIFY(mpBuffer != 0); delete[] mpBuffer; } size_t maximum_reservation() { return RING_SIZE-1; } T* reserve(size_t samples) { BOOST_VERIFY(mpBuffer != 0 && samples < RING_SIZE); if (samples >= RING_SIZE) { return 0; } if ((mPosition + samples) > RING_SIZE) { mPosition = 0; } T* ret = mpBuffer+mPosition; mPosition += samples; return ret; } private: T* mpBuffer; size_t mPosition; }; #endif <commit_msg>More refactoring<commit_after>#ifndef SAMPLE_HPP #define SAMPLE_HPP #include <cstddef> template<class T> class Sample { public: Sample() : mpSample(0), mLength(0) {} Sample(const Sample &copy) : mpSample(copy.mpSample), mLength(copy.mLength) { } ~Sample() { mpSample = 0; mLength = 0; } Sample& operator=(const Sample& other) { mpSample = other.mpSample; mLength = other.mLength; return *this; } void configure(T* pSample, int length) { mpSample = pSample; mLength = length; } T* sample() { return mpSample; } size_t length() { return mLength; } private: T* mpSample; size_t mLength; }; #endif<|endoftext|>
<commit_before>/* * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * * 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 <onnx/onnx_pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <sstream> #include <iostream> #include <fstream> using std::cerr; using std::endl; #pragma once namespace { // Helper function to convert ONNX dims to TRT dims template<typename OnnxDims> inline bool convert_dims(OnnxDims const& onnx_dims, nvinfer1::Dims& trt_dims) { std::vector<int> onnx_dims_vector; std::vector<nvinfer1::DimensionType> onnx_type_vector; for( auto const& onnx_dim : onnx_dims ) { int val = (onnx_dim.dim_param() != "" || onnx_dim.dim_value() == 0) ? -1 : onnx_dim.dim_value(); onnx_dims_vector.push_back(val); onnx_type_vector.push_back(static_cast<nvinfer1::DimensionType>(0)); } trt_dims.nbDims = onnx_dims_vector.size(); if (trt_dims.nbDims > nvinfer1::Dims::MAX_DIMS){ return false; } std::copy(onnx_dims_vector.begin(), onnx_dims_vector.end(), trt_dims.d); std::copy(onnx_type_vector.begin(), onnx_type_vector.end(), trt_dims.type); return true; } // Removes raw data from the text representation of an ONNX model inline void remove_raw_data_strings(std::string& s) { std::string::size_type beg = 0; const std::string key = "raw_data: \""; const std::string sub = "..."; while( (beg = s.find(key, beg)) != std::string::npos ) { beg += key.length(); std::string::size_type end = beg - 1; // Note: Must skip over escaped end-quotes while( s[(end = s.find("\"", ++end)) - 1] == '\\' ) {} if( end - beg > 128 ) { // Only remove large data strings s.replace(beg, end - beg, "..."); } beg += sub.length(); } } // Removes float_data, int32_data etc. from the text representation of an ONNX model inline std::string remove_repeated_data_strings(std::string& s) { std::istringstream iss(s); std::ostringstream oss; bool is_repeat = false; for( std::string line; std::getline(iss, line); ) { if( line.find("float_data:") != std::string::npos || line.find("int32_data:") != std::string::npos || line.find("int64_data:") != std::string::npos ) { if( !is_repeat ) { is_repeat = true; oss << line.substr(0, line.find(":") + 1) << " ...\n"; } } else { is_repeat = false; oss << line << "\n"; } } return oss.str(); } } // anonymous namespace inline std::string pretty_print_onnx_to_string(::google::protobuf::Message const& message) { std::string s; ::google::protobuf::TextFormat::PrintToString(message, &s); remove_raw_data_strings(s); s = remove_repeated_data_strings(s); return s; } inline std::ostream& operator<<(std::ostream& stream, ::ONNX_NAMESPACE::ModelProto const& message) { stream << pretty_print_onnx_to_string(message); return stream; } inline std::ostream& operator<<(std::ostream& stream, ::ONNX_NAMESPACE::NodeProto const& message) { stream << pretty_print_onnx_to_string(message); return stream; } //... //...Consider moving all of the below functions into a stand alone //... inline bool ParseFromFile_WAR(google::protobuf::Message* msg, const char* filename) { std::ifstream stream(filename, std::ios::in | std::ios::binary); if (!stream) { cerr << "Could not open file " << std::string(filename) <<endl; return false; } google::protobuf::io::IstreamInputStream rawInput(&stream); google::protobuf::io::CodedInputStream coded_input(&rawInput); // Note: This WARs the very low default size limit (64MB) coded_input.SetTotalBytesLimit(std::numeric_limits<int>::max(), std::numeric_limits<int>::max()/4); return msg->ParseFromCodedStream(&coded_input); } inline bool ParseFromTextFile(google::protobuf::Message* msg, const char* filename) { std::ifstream stream(filename, std::ios::in ); if (!stream) { cerr << "Could not open file " << std::string(filename) <<endl; return false; } google::protobuf::io::IstreamInputStream rawInput(&stream); return google::protobuf::TextFormat::Parse(&rawInput, msg); } inline std::string onnx_ir_version_string(int64_t ir_version=::ONNX_NAMESPACE::IR_VERSION) { int onnx_ir_major = ir_version / 1000000; int onnx_ir_minor = ir_version % 1000000 / 10000; int onnx_ir_patch = ir_version % 10000; return (std::to_string(onnx_ir_major) + "." + std::to_string(onnx_ir_minor) + "." + std::to_string(onnx_ir_patch)); } <commit_msg>fix error:numeric_limits (#268)<commit_after>/* * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * * 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 <onnx/onnx_pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <sstream> #include <iostream> #include <fstream> #include <limits> using std::cerr; using std::endl; #pragma once namespace { // Helper function to convert ONNX dims to TRT dims template<typename OnnxDims> inline bool convert_dims(OnnxDims const& onnx_dims, nvinfer1::Dims& trt_dims) { std::vector<int> onnx_dims_vector; std::vector<nvinfer1::DimensionType> onnx_type_vector; for( auto const& onnx_dim : onnx_dims ) { int val = (onnx_dim.dim_param() != "" || onnx_dim.dim_value() == 0) ? -1 : onnx_dim.dim_value(); onnx_dims_vector.push_back(val); onnx_type_vector.push_back(static_cast<nvinfer1::DimensionType>(0)); } trt_dims.nbDims = onnx_dims_vector.size(); if (trt_dims.nbDims > nvinfer1::Dims::MAX_DIMS){ return false; } std::copy(onnx_dims_vector.begin(), onnx_dims_vector.end(), trt_dims.d); std::copy(onnx_type_vector.begin(), onnx_type_vector.end(), trt_dims.type); return true; } // Removes raw data from the text representation of an ONNX model inline void remove_raw_data_strings(std::string& s) { std::string::size_type beg = 0; const std::string key = "raw_data: \""; const std::string sub = "..."; while( (beg = s.find(key, beg)) != std::string::npos ) { beg += key.length(); std::string::size_type end = beg - 1; // Note: Must skip over escaped end-quotes while( s[(end = s.find("\"", ++end)) - 1] == '\\' ) {} if( end - beg > 128 ) { // Only remove large data strings s.replace(beg, end - beg, "..."); } beg += sub.length(); } } // Removes float_data, int32_data etc. from the text representation of an ONNX model inline std::string remove_repeated_data_strings(std::string& s) { std::istringstream iss(s); std::ostringstream oss; bool is_repeat = false; for( std::string line; std::getline(iss, line); ) { if( line.find("float_data:") != std::string::npos || line.find("int32_data:") != std::string::npos || line.find("int64_data:") != std::string::npos ) { if( !is_repeat ) { is_repeat = true; oss << line.substr(0, line.find(":") + 1) << " ...\n"; } } else { is_repeat = false; oss << line << "\n"; } } return oss.str(); } } // anonymous namespace inline std::string pretty_print_onnx_to_string(::google::protobuf::Message const& message) { std::string s; ::google::protobuf::TextFormat::PrintToString(message, &s); remove_raw_data_strings(s); s = remove_repeated_data_strings(s); return s; } inline std::ostream& operator<<(std::ostream& stream, ::ONNX_NAMESPACE::ModelProto const& message) { stream << pretty_print_onnx_to_string(message); return stream; } inline std::ostream& operator<<(std::ostream& stream, ::ONNX_NAMESPACE::NodeProto const& message) { stream << pretty_print_onnx_to_string(message); return stream; } //... //...Consider moving all of the below functions into a stand alone //... inline bool ParseFromFile_WAR(google::protobuf::Message* msg, const char* filename) { std::ifstream stream(filename, std::ios::in | std::ios::binary); if (!stream) { cerr << "Could not open file " << std::string(filename) <<endl; return false; } google::protobuf::io::IstreamInputStream rawInput(&stream); google::protobuf::io::CodedInputStream coded_input(&rawInput); // Note: This WARs the very low default size limit (64MB) coded_input.SetTotalBytesLimit(std::numeric_limits<int>::max(), std::numeric_limits<int>::max()/4); return msg->ParseFromCodedStream(&coded_input); } inline bool ParseFromTextFile(google::protobuf::Message* msg, const char* filename) { std::ifstream stream(filename, std::ios::in ); if (!stream) { cerr << "Could not open file " << std::string(filename) <<endl; return false; } google::protobuf::io::IstreamInputStream rawInput(&stream); return google::protobuf::TextFormat::Parse(&rawInput, msg); } inline std::string onnx_ir_version_string(int64_t ir_version=::ONNX_NAMESPACE::IR_VERSION) { int onnx_ir_major = ir_version / 1000000; int onnx_ir_minor = ir_version % 1000000 / 10000; int onnx_ir_patch = ir_version % 10000; return (std::to_string(onnx_ir_major) + "." + std::to_string(onnx_ir_minor) + "." + std::to_string(onnx_ir_patch)); } <|endoftext|>
<commit_before>#include "parser.h" #include <iostream> #include <string> #include <memory> namespace kaleidoscope { std::unique_ptr<ExprAST> Parser::log_error(const char* str) { std::cerr << "Error: " << str << "\n"; return nullptr; } std::unique_ptr<PrototypeAST> Parser::log_error_p(const char* str) { log_error(str); return nullptr; } std::unique_ptr<PrototypeAST> Parser::parse_proto() { // parse function name if (_cur_token != Lexer::tok_identifier) return log_error_p("Expected function name in prototype"); auto fn_name = _lexer.token_value().identifier_str; //parse arg list get_next_token(); if (_cur_token != '(') return log_error_p("Expected \"(\" after function name in prototype"); std::vector<std::string> args; do { get_next_token(); if (_cur_token != Lexer::tok_identifier) return log_error_p("Expected argument name in argument list in prototype"); args.push_back(_lexer.token_value().identifier_str); get_next_token(); if (_cur_token != ',' || _cur_token != ')') return log_error_p("Expected \",\" or \")\" in argument list in prototype"); } while (_cur_token != ')'); return std::make_unique<PrototypeAST>(fn_name, args); } std::unique_ptr<FunctionAST> Parser::parse_def() { get_next_token(); auto proto = parse_proto(); return nullptr; } void Parser::parse() { while (true) { switch(_cur_token) { case Lexer::tok_eof: return; case ';': get_next_token(); break; case Lexer::tok_def: if (parse_def()) { std::cout << "Parsed function definition.\n"; } else { get_next_token(); } break; default: std::cout << "Default hit!\n"; get_next_token(); break; } } } } <commit_msg>Fix incorrect error checking in parsing function prototype<commit_after>#include "parser.h" #include <iostream> #include <string> #include <memory> namespace kaleidoscope { std::unique_ptr<ExprAST> Parser::log_error(const char* str) { std::cerr << "Error: " << str << "\n"; return nullptr; } std::unique_ptr<PrototypeAST> Parser::log_error_p(const char* str) { log_error(str); return nullptr; } std::unique_ptr<PrototypeAST> Parser::parse_proto() { // parse function name if (_cur_token != Lexer::tok_identifier) return log_error_p("Expected function name in prototype"); auto fn_name = _lexer.token_value().identifier_str; //parse arg list get_next_token(); if (_cur_token != '(') return log_error_p("Expected \"(\" after function name in prototype"); std::vector<std::string> args; do { get_next_token(); if (_cur_token != Lexer::tok_identifier) return log_error_p("Expected argument name in argument list in prototype"); args.push_back(_lexer.token_value().identifier_str); get_next_token(); if (_cur_token != ',' && _cur_token != ')') return log_error_p("Expected \",\" or \")\" in argument list in prototype"); } while (_cur_token != ')'); return std::make_unique<PrototypeAST>(fn_name, args); } std::unique_ptr<FunctionAST> Parser::parse_def() { get_next_token(); auto proto = parse_proto(); return nullptr; } void Parser::parse() { while (true) { switch(_cur_token) { case Lexer::tok_eof: return; case ';': get_next_token(); break; case Lexer::tok_def: if (parse_def()) { std::cout << "Parsed function definition.\n"; } else { get_next_token(); } break; default: std::cout << "Default hit!\n"; get_next_token(); break; } } } } <|endoftext|>
<commit_before>/** * @file */ #pragma once #include "libbirch/Any.hpp" #include "libbirch/Atomic.hpp" #include "libbirch/type.hpp" #include "libbirch/memory.hpp" namespace libbirch { /** * Shared object. * * @ingroup libbirch * * @tparam T Type, must derive from Any. * * Supports reference counted garbage collection. Cycles are collected by * periodically calling collect(); currently this must be done manually at * opportune times. * * @attention While Shared maintains a pointer to a referent object, it likes * to pretend it's not a pointer. This behavior differs from * [`std::shared_ptr`](https://en.cppreference.com/w/cpp/memory/shared_ptr). * In particular, its default constructor does not initialize the pointer to * `nullptr`, but rather default-constructs an object of type `T` and sets the * pointer to that. Consider using a [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional/optional) * with a Shared value instead of `nullptr`. */ template<class T> class Shared { template<class U> friend class Shared; friend class Marker; friend class Scanner; friend class Reacher; friend class Collector; friend class Spanner; friend class Bridger; friend class Copier; friend class BiconnectedCopier; public: using value_type = T; /** * Default constructor. Constructs a new referent using the default * constructor. */ Shared() : Shared(new T(), false) { // } /** * Constructor. Constructs a new referent with the given arguments. The * first is a placeholder (pass [`std::in_place`](https://en.cppreference.com/w/cpp/utility/in_place)) * to distinguish this constructor from copy and move constructors. * * @note [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional/) * behaves similarly with regard to [`std::in_place`](https://en.cppreference.com/w/cpp/utility/in_place). */ template<class... Args> Shared(std::in_place_t, Args&&... args) : Shared(new T(std::forward<Args>(args)...), false) { // } /** * Constructor. * * @param ptr Raw pointer. * @param b Is this a bridge? */ Shared(T* ptr, const bool b = false) : ptr(ptr), b(b) { if (ptr) { ptr->incShared(); } } /** * Copy constructor. */ Shared(const Shared& o) : ptr(nullptr), b(false) { if (o.b) { if (biconnected_copy()) { replace(o.load()); b = true; } else { replace(o.get()); b = false; } } else { replace(o.load()); } } /** * Generic copy constructor. */ template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0> Shared(const Shared<U>& o) : Shared(o.get(), false) { // } /** * Move constructor. */ Shared(Shared&& o) : ptr(o.ptr.exchange(nullptr)), b(o.b) { o.b = false; } /** * Generic move constructor. */ template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0> Shared(Shared<U>&& o) : ptr(o.ptr.exchange(nullptr)), b(o.b) { o.b = false; } /** * Destructor. */ ~Shared() { release(); } /** * Copy assignment. */ Shared& operator=(const Shared& o) { replace(o.get()); b = false; return *this; } /** * Generic copy assignment. */ template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0> Shared& operator=(const Shared<U>& o) { replace(o.get()); b = false; return *this; } /** * Move assignment. */ Shared& operator=(Shared&& o) { auto ptr = o.ptr.exchange(nullptr); auto old = this->ptr.exchange(ptr); if (old) { if (ptr == old) { old->decShared(); } else { old->decShared(); } } std::swap(b, o.b); return *this; } /** * Generic move assignment. */ template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0> Shared& operator=(Shared<U>&& o) { auto ptr = o.ptr.exchange(nullptr); auto old = this->ptr.exchange(ptr); if (old) { if (ptr == old) { old->decShared(); } else { old->decShared(); } } std::swap(b, o.b); return *this; } /** * Value assignment. */ template<class U, std::enable_if_t<is_value<U>::value,int> = 0> Shared<T>& operator=(const U& o) { *get() = o; return *this; } /** * Value assignment. */ template<class U, std::enable_if_t<is_value<U>::value,int> = 0> const Shared<T>& operator=(const U& o) const { *get() = o; return *this; } /** * Is the pointer not null? * * This is used instead of an `operator bool()` so as not to conflict with * conversion operators in the referent type. */ bool query() const { return load() != nullptr; } /** * Get the raw pointer. */ T* get(); /** * Get the raw pointer. */ T* get() const { return const_cast<Shared<T>*>(this)->get(); } /** * Get the raw pointer as const. */ const T* read() const { return get(); } /** * Deep copy. Finds bridges in the reachable graph then immediately copies * the subgraph up to the nearest reachable bridges, the remainder deferred * until needed. */ Shared<T> copy(); /** * Deep copy. */ Shared<T> copy() const { return const_cast<Shared<T>*>(this)->copy(); } /** * Deep copy. Copies the subgraph up to the nearest reachable bridges, the * remainder deferred until needed. Unlike #copy(), does not attempt to find * new bridges, but does use existing bridges. This is suitable if eager * copying, rather than lazy copying, is preferred, or for the second and * subsequent copies when replicating a graph multiple times, when the * bridge finding has already been completed by the first copy (using * #copy()). */ Shared<T> copy2(); /** * Deep copy. */ Shared<T> copy2() const { return const_cast<Shared<T>*>(this)->copy2(); } /** * Replace. Sets the raw pointer to a new value and returns the previous * value. */ T* replace(T* ptr) { if (ptr) { ptr->incShared(); } auto old = this->ptr.exchange(ptr); if (old) { if (ptr == old) { old->decShared(); } else { old->decShared(); } } b = false; return old; } /** * Release. Sets the raw pointer to null and returns the previous value. */ T* release() { auto old = ptr.exchange(nullptr); if (old) { old->decShared(); } b = false; return old; } /** * Dereference. */ T& operator*() const { return *get(); } /** * Member access. */ T* operator->() const { return get(); } /** * Call on referent. */ template<class... Args> auto& operator()(Args&&... args) { return (*get())(std::forward<Args>(args)...); } private: /** * Load the raw pointer as-is. Does not trigger copy-on-write. */ T* load() const { return ptr.load(); } /** * Store the raw pointer as-is. Does not update reference counts. */ void store(T* o) { ptr.store(o); } /** * Raw pointer. */ Atomic<T*> ptr; /** * Is this a bridge? */ bool b; }; template<class T> struct is_value<Shared<T>> { static const bool value = false; }; template<class T> struct is_pointer<Shared<T>> { static const bool value = true; }; } #include "libbirch/Spanner.hpp" #include "libbirch/Bridger.hpp" #include "libbirch/Copier.hpp" #include "libbirch/BiconnectedCopier.hpp" template<class T> T* libbirch::Shared<T>::get() { T* v = load(); if (b) { b = false; if (v->numShared() > 1) { // no need to copy for last reference /* the copy is of a biconnected component here, used the optimized * BiconnectedCopier for this */ v = static_cast<T*>(BiconnectedCopier(v).visit(static_cast<Any*>(v))); replace(v); } } return v; } template<class T> libbirch::Shared<T> libbirch::Shared<T>::copy() { /* find bridges */ Spanner().visit(0, 1, *this); Bridger().visit(1, 0, *this); /* copy */ return copy2(); } template<class T> libbirch::Shared<T> libbirch::Shared<T>::copy2() { Any* u = load(); if (b) { return Shared<T>(static_cast<T*>(u), true); } else { /* the copy is *not* of a biconnected component here, use the * general-purpose Copier for this */ return Shared<T>(static_cast<T*>(Copier().visit(u)), false); } } <commit_msg>Restored use of decSharedReachable() in Shared.<commit_after>/** * @file */ #pragma once #include "libbirch/Any.hpp" #include "libbirch/Atomic.hpp" #include "libbirch/type.hpp" #include "libbirch/memory.hpp" namespace libbirch { /** * Shared object. * * @ingroup libbirch * * @tparam T Type, must derive from Any. * * Supports reference counted garbage collection. Cycles are collected by * periodically calling collect(); currently this must be done manually at * opportune times. * * @attention While Shared maintains a pointer to a referent object, it likes * to pretend it's not a pointer. This behavior differs from * [`std::shared_ptr`](https://en.cppreference.com/w/cpp/memory/shared_ptr). * In particular, its default constructor does not initialize the pointer to * `nullptr`, but rather default-constructs an object of type `T` and sets the * pointer to that. Consider using a [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional/optional) * with a Shared value instead of `nullptr`. */ template<class T> class Shared { template<class U> friend class Shared; friend class Marker; friend class Scanner; friend class Reacher; friend class Collector; friend class Spanner; friend class Bridger; friend class Copier; friend class BiconnectedCopier; public: using value_type = T; /** * Default constructor. Constructs a new referent using the default * constructor. */ Shared() : Shared(new T(), false) { // } /** * Constructor. Constructs a new referent with the given arguments. The * first is a placeholder (pass [`std::in_place`](https://en.cppreference.com/w/cpp/utility/in_place)) * to distinguish this constructor from copy and move constructors. * * @note [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional/) * behaves similarly with regard to [`std::in_place`](https://en.cppreference.com/w/cpp/utility/in_place). */ template<class... Args> Shared(std::in_place_t, Args&&... args) : Shared(new T(std::forward<Args>(args)...), false) { // } /** * Constructor. * * @param ptr Raw pointer. * @param b Is this a bridge? */ Shared(T* ptr, const bool b = false) : ptr(ptr), b(b) { if (ptr) { ptr->incShared(); } } /** * Copy constructor. */ Shared(const Shared& o) : ptr(nullptr), b(false) { if (o.b) { if (biconnected_copy()) { replace(o.load()); b = true; } else { replace(o.get()); b = false; } } else { replace(o.load()); } } /** * Generic copy constructor. */ template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0> Shared(const Shared<U>& o) : Shared(o.get(), false) { // } /** * Move constructor. */ Shared(Shared&& o) : ptr(o.ptr.exchange(nullptr)), b(o.b) { o.b = false; } /** * Generic move constructor. */ template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0> Shared(Shared<U>&& o) : ptr(o.ptr.exchange(nullptr)), b(o.b) { o.b = false; } /** * Destructor. */ ~Shared() { release(); } /** * Copy assignment. */ Shared& operator=(const Shared& o) { replace(o.get()); b = false; return *this; } /** * Generic copy assignment. */ template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0> Shared& operator=(const Shared<U>& o) { replace(o.get()); b = false; return *this; } /** * Move assignment. */ Shared& operator=(Shared&& o) { auto ptr = o.ptr.exchange(nullptr); auto old = this->ptr.exchange(ptr); if (old) { if (ptr == old) { old->decSharedReachable(); } else { old->decShared(); } } std::swap(b, o.b); return *this; } /** * Generic move assignment. */ template<class U, std::enable_if_t<std::is_base_of<T,U>::value,int> = 0> Shared& operator=(Shared<U>&& o) { auto ptr = o.ptr.exchange(nullptr); auto old = this->ptr.exchange(ptr); if (old) { if (ptr == old) { old->decSharedReachable(); } else { old->decShared(); } } std::swap(b, o.b); return *this; } /** * Value assignment. */ template<class U, std::enable_if_t<is_value<U>::value,int> = 0> Shared<T>& operator=(const U& o) { *get() = o; return *this; } /** * Value assignment. */ template<class U, std::enable_if_t<is_value<U>::value,int> = 0> const Shared<T>& operator=(const U& o) const { *get() = o; return *this; } /** * Is the pointer not null? * * This is used instead of an `operator bool()` so as not to conflict with * conversion operators in the referent type. */ bool query() const { return load() != nullptr; } /** * Get the raw pointer. */ T* get(); /** * Get the raw pointer. */ T* get() const { return const_cast<Shared<T>*>(this)->get(); } /** * Get the raw pointer as const. */ const T* read() const { return get(); } /** * Deep copy. Finds bridges in the reachable graph then immediately copies * the subgraph up to the nearest reachable bridges, the remainder deferred * until needed. */ Shared<T> copy(); /** * Deep copy. */ Shared<T> copy() const { return const_cast<Shared<T>*>(this)->copy(); } /** * Deep copy. Copies the subgraph up to the nearest reachable bridges, the * remainder deferred until needed. Unlike #copy(), does not attempt to find * new bridges, but does use existing bridges. This is suitable if eager * copying, rather than lazy copying, is preferred, or for the second and * subsequent copies when replicating a graph multiple times, when the * bridge finding has already been completed by the first copy (using * #copy()). */ Shared<T> copy2(); /** * Deep copy. */ Shared<T> copy2() const { return const_cast<Shared<T>*>(this)->copy2(); } /** * Replace. Sets the raw pointer to a new value and returns the previous * value. */ T* replace(T* ptr) { if (ptr) { ptr->incShared(); } auto old = this->ptr.exchange(ptr); if (old) { if (ptr == old) { old->decSharedReachable(); } else { old->decShared(); } } b = false; return old; } /** * Release. Sets the raw pointer to null and returns the previous value. */ T* release() { auto old = ptr.exchange(nullptr); if (old) { old->decShared(); } b = false; return old; } /** * Dereference. */ T& operator*() const { return *get(); } /** * Member access. */ T* operator->() const { return get(); } /** * Call on referent. */ template<class... Args> auto& operator()(Args&&... args) { return (*get())(std::forward<Args>(args)...); } private: /** * Load the raw pointer as-is. Does not trigger copy-on-write. */ T* load() const { return ptr.load(); } /** * Store the raw pointer as-is. Does not update reference counts. */ void store(T* o) { ptr.store(o); } /** * Raw pointer. */ Atomic<T*> ptr; /** * Is this a bridge? */ bool b; }; template<class T> struct is_value<Shared<T>> { static const bool value = false; }; template<class T> struct is_pointer<Shared<T>> { static const bool value = true; }; } #include "libbirch/Spanner.hpp" #include "libbirch/Bridger.hpp" #include "libbirch/Copier.hpp" #include "libbirch/BiconnectedCopier.hpp" template<class T> T* libbirch::Shared<T>::get() { T* v = load(); if (b) { b = false; if (v->numShared() > 1) { // no need to copy for last reference /* the copy is of a biconnected component here, used the optimized * BiconnectedCopier for this */ v = static_cast<T*>(BiconnectedCopier(v).visit(static_cast<Any*>(v))); replace(v); } } return v; } template<class T> libbirch::Shared<T> libbirch::Shared<T>::copy() { /* find bridges */ Spanner().visit(0, 1, *this); Bridger().visit(1, 0, *this); /* copy */ return copy2(); } template<class T> libbirch::Shared<T> libbirch::Shared<T>::copy2() { Any* u = load(); if (b) { return Shared<T>(static_cast<T*>(u), true); } else { /* the copy is *not* of a biconnected component here, use the * general-purpose Copier for this */ return Shared<T>(static_cast<T*>(Copier().visit(u)), false); } } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_IO_NETWORK_MULTIPLEXER_HPP #define CAF_IO_NETWORK_MULTIPLEXER_HPP #include <string> #include <thread> #include <functional> #include "caf/extend.hpp" #include "caf/memory_managed.hpp" #include "caf/io/fwd.hpp" #include "caf/io/accept_handle.hpp" #include "caf/io/connection_handle.hpp" #include "caf/io/network/native_socket.hpp" #include "caf/mixin/memory_cached.hpp" #include "caf/detail/memory.hpp" namespace boost { namespace asio { class io_service; } // namespace asio } // namespace boost namespace caf { namespace io { namespace network { /** * Low-level backend for IO multiplexing. */ class multiplexer { public: virtual ~multiplexer(); /** * Creates a new TCP doorman from a native socket handle. */ virtual connection_handle add_tcp_scribe(broker* ptr, native_socket fd) = 0; /** * Tries to connect to host `h` on given `port` and returns a * new scribe managing the connection on success. */ virtual connection_handle add_tcp_scribe(broker* ptr, const std::string& host, uint16_t port) = 0; /** * Creates a new TCP doorman from a native socket handle. */ virtual accept_handle add_tcp_doorman(broker* ptr, native_socket fd) = 0; /** * Tries to create a new TCP doorman running on port `p`, optionally * accepting only connections from IP address `in`. */ virtual accept_handle add_tcp_doorman(broker* ptr, uint16_t port, const char* in = nullptr) = 0; /** * Simple wrapper for runnables */ struct runnable : extend<memory_managed>::with<mixin::memory_cached> { virtual void run() = 0; virtual ~runnable(); }; using runnable_ptr = std::unique_ptr<runnable, detail::disposer>; /** * Makes sure the multipler does not exit its event loop until * the destructor of `supervisor` has been called. */ struct supervisor { public: virtual ~supervisor(); }; using supervisor_ptr = std::unique_ptr<supervisor>; /** * Creates a supervisor to keep the event loop running. */ virtual supervisor_ptr make_supervisor() = 0; /** * Creates an instance using the networking backend compiled with CAF. */ static std::unique_ptr<multiplexer> make(); /** * Runs the multiplexers event loop. */ virtual void run() = 0; /** * Invokes @p fun in the multiplexer's event loop. */ template <class F> void dispatch(F fun) { if (std::this_thread::get_id() == thread_id()) { fun(); return; } post(std::move(fun)); } /** * Invokes @p fun in the multiplexer's event loop. */ template <class F> void post(F fun) { struct impl : runnable { F f; impl(F&& mf) : f(std::move(mf)) { } void run() override { f(); } }; dispatch_runnable(runnable_ptr{detail::memory::create<impl>(std::move(fun))}); } /** * Retrieves a pointer to the implementation or `nullptr` if CAF was * compiled using the default backend. */ virtual boost::asio::io_service* pimpl(); inline const std::thread::id& thread_id() const { return m_tid; } inline void thread_id(std::thread::id tid) { m_tid = std::move(tid); } protected: /** * Implementation-specific dispatching to the multiplexer's thread. */ virtual void dispatch_runnable(runnable_ptr ptr) = 0; /** * Must be set by the subclass. */ std::thread::id m_tid; }; using multiplexer_ptr = std::unique_ptr<multiplexer>; } // namespace network } // namespace io } // namespace caf #endif // CAF_IO_NETWORK_MULTIPLEXER_HPP <commit_msg>Fix class/struct mismatch<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_IO_NETWORK_MULTIPLEXER_HPP #define CAF_IO_NETWORK_MULTIPLEXER_HPP #include <string> #include <thread> #include <functional> #include "caf/extend.hpp" #include "caf/memory_managed.hpp" #include "caf/io/fwd.hpp" #include "caf/io/accept_handle.hpp" #include "caf/io/connection_handle.hpp" #include "caf/io/network/native_socket.hpp" #include "caf/mixin/memory_cached.hpp" #include "caf/detail/memory.hpp" namespace boost { namespace asio { class io_service; } // namespace asio } // namespace boost namespace caf { namespace io { namespace network { /** * Low-level backend for IO multiplexing. */ class multiplexer { public: virtual ~multiplexer(); /** * Creates a new TCP doorman from a native socket handle. */ virtual connection_handle add_tcp_scribe(broker* ptr, native_socket fd) = 0; /** * Tries to connect to host `h` on given `port` and returns a * new scribe managing the connection on success. */ virtual connection_handle add_tcp_scribe(broker* ptr, const std::string& host, uint16_t port) = 0; /** * Creates a new TCP doorman from a native socket handle. */ virtual accept_handle add_tcp_doorman(broker* ptr, native_socket fd) = 0; /** * Tries to create a new TCP doorman running on port `p`, optionally * accepting only connections from IP address `in`. */ virtual accept_handle add_tcp_doorman(broker* ptr, uint16_t port, const char* in = nullptr) = 0; /** * Simple wrapper for runnables */ struct runnable : extend<memory_managed>::with<mixin::memory_cached> { virtual void run() = 0; virtual ~runnable(); }; using runnable_ptr = std::unique_ptr<runnable, detail::disposer>; /** * Makes sure the multipler does not exit its event loop until * the destructor of `supervisor` has been called. */ class supervisor { public: virtual ~supervisor(); }; using supervisor_ptr = std::unique_ptr<supervisor>; /** * Creates a supervisor to keep the event loop running. */ virtual supervisor_ptr make_supervisor() = 0; /** * Creates an instance using the networking backend compiled with CAF. */ static std::unique_ptr<multiplexer> make(); /** * Runs the multiplexers event loop. */ virtual void run() = 0; /** * Invokes @p fun in the multiplexer's event loop. */ template <class F> void dispatch(F fun) { if (std::this_thread::get_id() == thread_id()) { fun(); return; } post(std::move(fun)); } /** * Invokes @p fun in the multiplexer's event loop. */ template <class F> void post(F fun) { struct impl : runnable { F f; impl(F&& mf) : f(std::move(mf)) { } void run() override { f(); } }; dispatch_runnable(runnable_ptr{detail::memory::create<impl>(std::move(fun))}); } /** * Retrieves a pointer to the implementation or `nullptr` if CAF was * compiled using the default backend. */ virtual boost::asio::io_service* pimpl(); inline const std::thread::id& thread_id() const { return m_tid; } inline void thread_id(std::thread::id tid) { m_tid = std::move(tid); } protected: /** * Implementation-specific dispatching to the multiplexer's thread. */ virtual void dispatch_runnable(runnable_ptr ptr) = 0; /** * Must be set by the subclass. */ std::thread::id m_tid; }; using multiplexer_ptr = std::unique_ptr<multiplexer>; } // namespace network } // namespace io } // namespace caf #endif // CAF_IO_NETWORK_MULTIPLEXER_HPP <|endoftext|>
<commit_before>#include <iostream> #include <string> using namespace std; bool isSignMagNegative(unsigned int n) { unsigned int signBit = ((n >> 31) & 0x1); if (signBit == 1) { cout << "true" << endl; return true; } else { cout << "false" << endl; return false; } } unsigned int toTwosComplement(unsigned int n) { if (isSignMagNegative(n) == true) { unsigned int twosComplement = ((~(n & 0x7fffffff)) + 1); return twosComplement; } else { return w; } } int main() { unsigned int n = 0; cin >> n; toTwosComplement(n); } <commit_msg>minor changes<commit_after>//============================================================================== // Two's Complement // // @description: Makefile for twoscomplement.cc // @author: Elisha Lai // @version: 1.0 24/09/2015 //============================================================================== #include <iostream> #include <string> using namespace std; bool isSignMagNegative(unsigned int n) { unsigned int signBit = ((n >> 31) & 0x1); if (signBit == 1) { cout << "true" << endl; return true; } else { cout << "false" << endl; return false; } // if } // isSignMagNegative unsigned int toTwosComplement(unsigned int n) { if (isSignMagNegative(n) == true) { unsigned int twosComplement = ((~(n & 0x7fffffff)) + 1); return twosComplement; } else { return w; } // if } // toTwosComplement int main() { unsigned int n = 0; cin >> n; toTwosComplement(n); } // main <|endoftext|>
<commit_before>/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org> */ #include "Daemon.hh" Daemon::Daemon(const std::string &path) : _local(path, DomainSocket::SERVER), _run(false) { } Daemon::~Daemon(void) { for (DomainSocket::iterator it = _clients.begin; it < _clients.end(); ++it) { delete *it; } } void Daemon::start(void) { _run = true; while (_run) { handleSockets(); } std::cout << "Server shutdown" << std::endl; } void Daemon::handleSockets(void) { fd_set readfds; fd_set writefds; int fd_max; struct timeval tv; fd_max = initSelect(&tv, &readfds, &writefds); if (::select(fd_max, &readfds, NULL, NULL, &tv) == -1) { throw std::runtime_error(std::string("Select Error : ") + ::strerror(errno)); } else { // If something to read on stdin if (FD_ISSET(0, &readfds)) eventTerminal(); // If new client connect if (FD_ISSET(_local.fd(), &readfds)) eventServer(); // Check clients's socket eventClients(&readfds, &writefds); } } int Daemon::initSelect(struct timeval *tv, fd_set *readfds, fd_set *writefds) { int fd_max = _local.fd(); // Timeout 100 ms tv->tv_sec = 0; tv->tv_usec = 100; // Initialize bits field for select FD_ZERO(readfds); FD_SET(_local.fd(), readfds); FD_SET(0, readfds); if (writefds != NULL) { FD_ZERO(writefds); FD_SET(_local.fd(), writefds); } for (DomainSocket *client : _clients) { FD_SET(client->fd(), readfds); if (writefds != NULL) FD_SET(client->fd(), writefds); // Check if client's fd is greater than actual fd_max fd_max = (fd_max < client->fd()) ? client->fd() : fd_max; } return fd_max + 1; } void Daemon::eventTerminal(void) { std::string msg; std::cin >> msg; if (msg == "exit") { _run = false; } } void Daemon::eventServer(void) { DomainSocket *client; try { client = _local.acceptClient(); _clients.push_back(client); } catch (std::runtime_error &e) { std::cout << e.what() << std::endl; } } void Daemon::eventClients(fd_set *readfds, fd_set *writefds) { std::string msg; for (std::vector<DomainSocket*>::iterator it = _clients.begin(); it < _clients.end(); ++it) { // Something to write on client socket if (FD_ISSET((*it)->fd(), writefds)) { if (_msgs.size()) { try { (*it)->sendMsg(_msgs.back()); _msgs.pop_back(); } catch (std::runtime_error &e) { std::cout << e.what() << std::endl; } } } // Something to read on client socket if (FD_ISSET((*it)->fd(), readfds)) { try { _msgs.push_back((*it)->recvMsg()); } catch (DomainSocket::Disconnected &e) { delete (*it); _clients.erase(it); it = _clients.begin(); } catch (std::runtime_error &e) { std::cout << e.what() << std::endl; } } } } int main(int ac, char **av) { if (ac != 2) { std::cout << "Usage : " << av[0] << " <socket_path>" << std::endl; return 1; } try { Daemon d(av[1]); d.start(); } catch (std::runtime_error &e) { } return 0; } <commit_msg>C++98 compatibility<commit_after>/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org> */ #include "Daemon.hh" Daemon::Daemon(const std::string &path) : _local(path, DomainSocket::SERVER), _run(false) { } Daemon::~Daemon(void) { for (DomainSocket::iterator it = _clients.begin; it < _clients.end(); ++it) { delete *it; } } void Daemon::start(void) { _run = true; while (_run) { handleSockets(); } std::cout << "Server shutdown" << std::endl; } void Daemon::handleSockets(void) { fd_set readfds; fd_set writefds; int fd_max; struct timeval tv; fd_max = initSelect(&tv, &readfds, &writefds); if (::select(fd_max, &readfds, NULL, NULL, &tv) == -1) { throw std::runtime_error(std::string("Select Error : ") + ::strerror(errno)); } else { // If something to read on stdin if (FD_ISSET(0, &readfds)) eventTerminal(); // If new client connect if (FD_ISSET(_local.fd(), &readfds)) eventServer(); // Check clients's socket eventClients(&readfds, &writefds); } } int Daemon::initSelect(struct timeval *tv, fd_set *readfds, fd_set *writefds) { int fd_max = _local.fd(); // Timeout 100 ms tv->tv_sec = 0; tv->tv_usec = 100; // Initialize bits field for select FD_ZERO(readfds); FD_SET(_local.fd(), readfds); FD_SET(0, readfds); if (writefds != NULL) { FD_ZERO(writefds); FD_SET(_local.fd(), writefds); } for (DomainSocket::iterator it = _clients.begin; it < _clients.end(); ++it) { FD_SET((*it)->fd(), readfds); if (writefds != NULL) FD_SET((*it)->fd(), writefds); // Check if client's fd is greater than actual fd_max fd_max = (fd_max < (*it)->fd()) ? (*it)->fd() : fd_max; } return fd_max + 1; } void Daemon::eventTerminal(void) { std::string msg; std::cin >> msg; if (msg == "exit") { _run = false; } } void Daemon::eventServer(void) { DomainSocket *client; try { client = _local.acceptClient(); _clients.push_back(client); } catch (std::runtime_error &e) { std::cout << e.what() << std::endl; } } void Daemon::eventClients(fd_set *readfds, fd_set *writefds) { std::string msg; for (std::vector<DomainSocket*>::iterator it = _clients.begin(); it < _clients.end(); ++it) { // Something to write on client socket if (FD_ISSET((*it)->fd(), writefds)) { if (_msgs.size()) { try { (*it)->sendMsg(_msgs.back()); _msgs.pop_back(); } catch (std::runtime_error &e) { std::cout << e.what() << std::endl; } } } // Something to read on client socket if (FD_ISSET((*it)->fd(), readfds)) { try { _msgs.push_back((*it)->recvMsg()); } catch (DomainSocket::Disconnected &e) { delete (*it); _clients.erase(it); it = _clients.begin(); } catch (std::runtime_error &e) { std::cout << e.what() << std::endl; } } } } int main(int ac, char **av) { if (ac != 2) { std::cout << "Usage : " << av[0] << " <socket_path>" << std::endl; return 1; } try { Daemon d(av[1]); d.start(); } catch (std::runtime_error &e) { } return 0; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "runconfigurationaspects.h" #include "project.h" #include "runconfiguration.h" #include "environmentaspect.h" #include <coreplugin/coreconstants.h> #include <utils/fancylineedit.h> #include <utils/pathchooser.h> #include <QCheckBox> #include <QLineEdit> #include <QDebug> #include <QFormLayout> #include <QLabel> #include <QToolButton> using namespace Utils; namespace ProjectExplorer { /*! \class ProjectExplorer::TerminalAspect */ TerminalAspect::TerminalAspect(RunConfiguration *runConfig, const QString &key, bool useTerminal, bool isForced) : IRunConfigurationAspect(runConfig), m_useTerminal(useTerminal), m_isForced(isForced), m_checkBox(0), m_key(key) { setDisplayName(tr("Terminal")); setId("TerminalAspect"); } IRunConfigurationAspect *TerminalAspect::create(RunConfiguration *runConfig) const { return new TerminalAspect(runConfig, m_key, false, false); } IRunConfigurationAspect *TerminalAspect::clone(RunConfiguration *runConfig) const { return new TerminalAspect(runConfig, m_key, m_useTerminal, m_isForced); } void TerminalAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_checkBox); m_checkBox = new QCheckBox(tr("Run in terminal"), parent); m_checkBox->setChecked(m_useTerminal); layout->addRow(QString(), m_checkBox); connect(m_checkBox.data(), &QAbstractButton::clicked, this, [this] { m_isForced = true; setUseTerminal(true); }); } void TerminalAspect::fromMap(const QVariantMap &map) { if (map.contains(m_key)) { m_useTerminal = map.value(m_key).toBool(); m_isForced = true; } else { m_isForced = false; } } void TerminalAspect::toMap(QVariantMap &data) const { if (m_isForced) data.insert(m_key, m_useTerminal); } bool TerminalAspect::useTerminal() const { return m_useTerminal; } void TerminalAspect::setUseTerminal(bool useTerminal) { if (m_useTerminal != useTerminal) { m_useTerminal = useTerminal; emit useTerminalChanged(useTerminal); } } /*! \class ProjectExplorer::WorkingDirectoryAspect */ WorkingDirectoryAspect::WorkingDirectoryAspect(RunConfiguration *runConfig, const QString &key, const QString &dir) : IRunConfigurationAspect(runConfig), m_workingDirectory(dir), m_chooser(0), m_key(key) { setDisplayName(tr("Working Directory")); setId("WorkingDirectoryAspect"); } IRunConfigurationAspect *WorkingDirectoryAspect::create(RunConfiguration *runConfig) const { return new WorkingDirectoryAspect(runConfig, m_key); } IRunConfigurationAspect *WorkingDirectoryAspect::clone(RunConfiguration *runConfig) const { return new WorkingDirectoryAspect(runConfig, m_key, m_workingDirectory); } void WorkingDirectoryAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_chooser); m_chooser = new PathChooser(parent); m_chooser->setHistoryCompleter(m_key); m_chooser->setExpectedKind(Utils::PathChooser::Directory); m_chooser->setPromptDialogTitle(tr("Select Working Directory")); connect(m_chooser, &PathChooser::pathChanged, this, &WorkingDirectoryAspect::setWorkingDirectory); auto resetButton = new QToolButton(parent); resetButton->setToolTip(tr("Reset to default")); resetButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_RESET))); connect(resetButton, &QAbstractButton::clicked, this, [this] { m_chooser->setPath(QString()); }); if (auto envAspect = runConfiguration()->extraAspect<EnvironmentAspect>()) { connect(envAspect, &EnvironmentAspect::environmentChanged, this, [this, envAspect] { m_chooser->setEnvironment(envAspect->environment()); }); m_chooser->setEnvironment(envAspect->environment()); } auto hbox = new QHBoxLayout; hbox->addWidget(m_chooser); hbox->addWidget(resetButton); layout->addRow(tr("Working directory:"), hbox); } void WorkingDirectoryAspect::fromMap(const QVariantMap &map) { m_workingDirectory = map.value(m_key).toBool(); } void WorkingDirectoryAspect::toMap(QVariantMap &data) const { data.insert(m_key, m_workingDirectory); } QString WorkingDirectoryAspect::workingDirectory() const { return runConfiguration()->macroExpander()->expandProcessArgs(m_workingDirectory); } QString WorkingDirectoryAspect::unexpandedWorkingDirectory() const { return m_workingDirectory; } void WorkingDirectoryAspect::setWorkingDirectory(const QString &workingDirectory) { m_workingDirectory = workingDirectory; } /*! \class ProjectExplorer::ArgumentsAspect */ ArgumentsAspect::ArgumentsAspect(RunConfiguration *runConfig, const QString &key, const QString &arguments) : IRunConfigurationAspect(runConfig), m_arguments(arguments), m_chooser(0), m_key(key) { setDisplayName(tr("Arguments")); setId("ArgumentsAspect"); } QString ArgumentsAspect::arguments() const { return runConfiguration()->macroExpander()->expandProcessArgs(m_arguments); } QString ArgumentsAspect::unexpandedArguments() const { return m_arguments; } void ArgumentsAspect::setArguments(const QString &arguments) { m_arguments = arguments; if (m_chooser) m_chooser->setText(m_arguments); } void ArgumentsAspect::fromMap(const QVariantMap &map) { m_arguments = map.value(m_key).toBool(); } void ArgumentsAspect::toMap(QVariantMap &map) const { map.insert(m_key, m_arguments); } IRunConfigurationAspect *ArgumentsAspect::create(RunConfiguration *runConfig) const { return new ArgumentsAspect(runConfig, m_key); } IRunConfigurationAspect *ArgumentsAspect::clone(RunConfiguration *runConfig) const { return new ArgumentsAspect(runConfig, m_key, m_arguments); } void ArgumentsAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_chooser); m_chooser = new FancyLineEdit(parent); m_chooser->setHistoryCompleter(m_key); connect(m_chooser, &QLineEdit::textChanged, this, &ArgumentsAspect::setArguments); layout->addRow(tr("Command line arguments:"), m_chooser); } /*! \class ProjectExplorer::ExecutableAspect */ ExecutableAspect::ExecutableAspect(RunConfiguration *runConfig, const QString &key, const QString &executable) : IRunConfigurationAspect(runConfig), m_executable(executable), m_chooser(0), m_key(key) { setDisplayName(tr("Executable")); setId("ExecutableAspect"); } QString ExecutableAspect::executable() const { return runConfiguration()->macroExpander()->expandProcessArgs(m_executable); } QString ExecutableAspect::unexpandedExecutable() const { return m_executable; } void ExecutableAspect::setExectuable(const QString &executable) { m_executable = executable; if (m_chooser) m_chooser->setText(m_executable); } void ExecutableAspect::fromMap(const QVariantMap &map) { m_executable = map.value(m_key).toBool(); } void ExecutableAspect::toMap(QVariantMap &map) const { map.insert(m_key, m_executable); } IRunConfigurationAspect *ExecutableAspect::create(RunConfiguration *runConfig) const { return new ExecutableAspect(runConfig, m_key); } IRunConfigurationAspect *ExecutableAspect::clone(RunConfiguration *runConfig) const { return new ExecutableAspect(runConfig, m_key, m_executable); } void ExecutableAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_chooser); m_chooser = new FancyLineEdit(parent); m_chooser->setHistoryCompleter(m_key); connect(m_chooser, &QLineEdit::textChanged, this, &ExecutableAspect::setExectuable); layout->addRow(tr("Command line arguments:"), m_chooser); } } // namespace ProjectExplorer <commit_msg>Fix loading project settings<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "runconfigurationaspects.h" #include "project.h" #include "runconfiguration.h" #include "environmentaspect.h" #include <coreplugin/coreconstants.h> #include <utils/fancylineedit.h> #include <utils/pathchooser.h> #include <QCheckBox> #include <QLineEdit> #include <QDebug> #include <QFormLayout> #include <QLabel> #include <QToolButton> using namespace Utils; namespace ProjectExplorer { /*! \class ProjectExplorer::TerminalAspect */ TerminalAspect::TerminalAspect(RunConfiguration *runConfig, const QString &key, bool useTerminal, bool isForced) : IRunConfigurationAspect(runConfig), m_useTerminal(useTerminal), m_isForced(isForced), m_checkBox(0), m_key(key) { setDisplayName(tr("Terminal")); setId("TerminalAspect"); } IRunConfigurationAspect *TerminalAspect::create(RunConfiguration *runConfig) const { return new TerminalAspect(runConfig, m_key, false, false); } IRunConfigurationAspect *TerminalAspect::clone(RunConfiguration *runConfig) const { return new TerminalAspect(runConfig, m_key, m_useTerminal, m_isForced); } void TerminalAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_checkBox); m_checkBox = new QCheckBox(tr("Run in terminal"), parent); m_checkBox->setChecked(m_useTerminal); layout->addRow(QString(), m_checkBox); connect(m_checkBox.data(), &QAbstractButton::clicked, this, [this] { m_isForced = true; setUseTerminal(true); }); } void TerminalAspect::fromMap(const QVariantMap &map) { if (map.contains(m_key)) { m_useTerminal = map.value(m_key).toBool(); m_isForced = true; } else { m_isForced = false; } } void TerminalAspect::toMap(QVariantMap &data) const { if (m_isForced) data.insert(m_key, m_useTerminal); } bool TerminalAspect::useTerminal() const { return m_useTerminal; } void TerminalAspect::setUseTerminal(bool useTerminal) { if (m_useTerminal != useTerminal) { m_useTerminal = useTerminal; emit useTerminalChanged(useTerminal); } } /*! \class ProjectExplorer::WorkingDirectoryAspect */ WorkingDirectoryAspect::WorkingDirectoryAspect(RunConfiguration *runConfig, const QString &key, const QString &dir) : IRunConfigurationAspect(runConfig), m_workingDirectory(dir), m_chooser(0), m_key(key) { setDisplayName(tr("Working Directory")); setId("WorkingDirectoryAspect"); } IRunConfigurationAspect *WorkingDirectoryAspect::create(RunConfiguration *runConfig) const { return new WorkingDirectoryAspect(runConfig, m_key); } IRunConfigurationAspect *WorkingDirectoryAspect::clone(RunConfiguration *runConfig) const { return new WorkingDirectoryAspect(runConfig, m_key, m_workingDirectory); } void WorkingDirectoryAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_chooser); m_chooser = new PathChooser(parent); m_chooser->setHistoryCompleter(m_key); m_chooser->setExpectedKind(Utils::PathChooser::Directory); m_chooser->setPromptDialogTitle(tr("Select Working Directory")); connect(m_chooser, &PathChooser::pathChanged, this, &WorkingDirectoryAspect::setWorkingDirectory); auto resetButton = new QToolButton(parent); resetButton->setToolTip(tr("Reset to default")); resetButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_RESET))); connect(resetButton, &QAbstractButton::clicked, this, [this] { m_chooser->setPath(QString()); }); if (auto envAspect = runConfiguration()->extraAspect<EnvironmentAspect>()) { connect(envAspect, &EnvironmentAspect::environmentChanged, this, [this, envAspect] { m_chooser->setEnvironment(envAspect->environment()); }); m_chooser->setEnvironment(envAspect->environment()); } auto hbox = new QHBoxLayout; hbox->addWidget(m_chooser); hbox->addWidget(resetButton); layout->addRow(tr("Working directory:"), hbox); } void WorkingDirectoryAspect::fromMap(const QVariantMap &map) { m_workingDirectory = map.value(m_key).toBool(); } void WorkingDirectoryAspect::toMap(QVariantMap &data) const { data.insert(m_key, m_workingDirectory); } QString WorkingDirectoryAspect::workingDirectory() const { return runConfiguration()->macroExpander()->expandProcessArgs(m_workingDirectory); } QString WorkingDirectoryAspect::unexpandedWorkingDirectory() const { return m_workingDirectory; } void WorkingDirectoryAspect::setWorkingDirectory(const QString &workingDirectory) { m_workingDirectory = workingDirectory; } /*! \class ProjectExplorer::ArgumentsAspect */ ArgumentsAspect::ArgumentsAspect(RunConfiguration *runConfig, const QString &key, const QString &arguments) : IRunConfigurationAspect(runConfig), m_arguments(arguments), m_chooser(0), m_key(key) { setDisplayName(tr("Arguments")); setId("ArgumentsAspect"); } QString ArgumentsAspect::arguments() const { return runConfiguration()->macroExpander()->expandProcessArgs(m_arguments); } QString ArgumentsAspect::unexpandedArguments() const { return m_arguments; } void ArgumentsAspect::setArguments(const QString &arguments) { m_arguments = arguments; if (m_chooser) m_chooser->setText(m_arguments); } void ArgumentsAspect::fromMap(const QVariantMap &map) { m_arguments = map.value(m_key).toString(); } void ArgumentsAspect::toMap(QVariantMap &map) const { map.insert(m_key, m_arguments); } IRunConfigurationAspect *ArgumentsAspect::create(RunConfiguration *runConfig) const { return new ArgumentsAspect(runConfig, m_key); } IRunConfigurationAspect *ArgumentsAspect::clone(RunConfiguration *runConfig) const { return new ArgumentsAspect(runConfig, m_key, m_arguments); } void ArgumentsAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_chooser); m_chooser = new FancyLineEdit(parent); m_chooser->setHistoryCompleter(m_key); connect(m_chooser, &QLineEdit::textChanged, this, &ArgumentsAspect::setArguments); layout->addRow(tr("Command line arguments:"), m_chooser); } /*! \class ProjectExplorer::ExecutableAspect */ ExecutableAspect::ExecutableAspect(RunConfiguration *runConfig, const QString &key, const QString &executable) : IRunConfigurationAspect(runConfig), m_executable(executable), m_chooser(0), m_key(key) { setDisplayName(tr("Executable")); setId("ExecutableAspect"); } QString ExecutableAspect::executable() const { return runConfiguration()->macroExpander()->expandProcessArgs(m_executable); } QString ExecutableAspect::unexpandedExecutable() const { return m_executable; } void ExecutableAspect::setExectuable(const QString &executable) { m_executable = executable; if (m_chooser) m_chooser->setText(m_executable); } void ExecutableAspect::fromMap(const QVariantMap &map) { m_executable = map.value(m_key).toBool(); } void ExecutableAspect::toMap(QVariantMap &map) const { map.insert(m_key, m_executable); } IRunConfigurationAspect *ExecutableAspect::create(RunConfiguration *runConfig) const { return new ExecutableAspect(runConfig, m_key); } IRunConfigurationAspect *ExecutableAspect::clone(RunConfiguration *runConfig) const { return new ExecutableAspect(runConfig, m_key, m_executable); } void ExecutableAspect::addToMainConfigurationWidget(QWidget *parent, QFormLayout *layout) { QTC_CHECK(!m_chooser); m_chooser = new FancyLineEdit(parent); m_chooser->setHistoryCompleter(m_key); connect(m_chooser, &QLineEdit::textChanged, this, &ExecutableAspect::setExectuable); layout->addRow(tr("Command line arguments:"), m_chooser); } } // namespace ProjectExplorer <|endoftext|>
<commit_before>#include <wendy/ConditionVariable.hpp> namespace wendy { #ifdef WIN32 ConditionVariable::ConditionVariable(CRITICAL_SECTION *criticalSection) { this->criticalSection = criticalSection; this->event = CreateEvent(NULL, FALSE, FALSE, NULL); } #else ConditionVariable::ConditionVariable(pthread_mutex_t *posixMutex) { this->posixMutex = posixMutex; pthread_cond_init(&this->posixCondition, NULL); } #endif ConditionVariable::~ConditionVariable() { # ifdef WIN32 CloseHandle(this->event); # else pthread_cond_destroy(&this->positionCondition); # endif } void ConditionVariable::wait() { # ifdef _WIN32 LeaveCriticalSection(this->criticalSection); WaitForSingleObject(this->event, INFINITE); EnterCriticalSection(this->criticalSection); # else pthread_cond_wait(&this->posixCondition, this->posixMutex); # endif } void ConditionVariable::signal() { # ifdef _WIN32 SetEvent(this->event); # else pthread_cond_signal(&this->posixCondition); # endif } } // wendy namespace <commit_msg>fixed typo in posix condition variables<commit_after>#include <wendy/ConditionVariable.hpp> namespace wendy { #ifdef WIN32 ConditionVariable::ConditionVariable(CRITICAL_SECTION *criticalSection) { this->criticalSection = criticalSection; this->event = CreateEvent(NULL, FALSE, FALSE, NULL); } #else ConditionVariable::ConditionVariable(pthread_mutex_t *posixMutex) { this->posixMutex = posixMutex; pthread_cond_init(&this->posixCondition, NULL); } #endif ConditionVariable::~ConditionVariable() { # ifdef WIN32 CloseHandle(this->event); # else pthread_cond_destroy(&this->posixCondition); # endif } void ConditionVariable::wait() { # ifdef _WIN32 LeaveCriticalSection(this->criticalSection); WaitForSingleObject(this->event, INFINITE); EnterCriticalSection(this->criticalSection); # else pthread_cond_wait(&this->posixCondition, this->posixMutex); # endif } void ConditionVariable::signal() { # ifdef _WIN32 SetEvent(this->event); # else pthread_cond_signal(&this->posixCondition); # endif } } // wendy namespace <|endoftext|>
<commit_before>#ifndef BFC_COMBINE_SET_VISITOR_HPP #define BFC_COMBINE_SET_VISITOR_HPP #include "ast/mod.hpp" #include "test_visitor.hpp" #include "opt_seq_base_visitor.hpp" #include "types.h" namespace bfc { namespace ast { class combine_set_visitor : public opt_seq_base_visitor { public: status visit(set &node) { // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible test_combine_set_visitor v; if (opt_seq.back().accept(v) == CONTINUE) { // discard the previous node (undone by this set) opt_seq.pop_back(); } } // copy the node return opt_seq_base_visitor::handle_set(node); } status visit(const set &node) { // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible test_combine_set_visitor v; if (opt_seq.back().accept(v) == CONTINUE) { // discard the previous node (undone by this set) opt_seq.pop_back(); } } // copy the node return opt_seq_base_visitor::handle_set(node); } status visit(add &node) { // discard any zero value node if (node.value() == 0) { return CONTINUE; } // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible try_combine_set_inc_visitor v(node.offset(), node.value(), true); if (opt_seq.back().accept(v) == CONTINUE) { opt_seq.pop_back(); opt_seq.emplace_back(new set(node.loc(), node.offset(), v.new_value())); return CONTINUE; } } // else make node copy return opt_seq_base_visitor::handle_add(node); } status visit(const add &node) { // discard any zero value node if (node.value() == 0) { return CONTINUE; } // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible try_combine_set_inc_visitor v(node.offset(), node.value(), true); if (opt_seq.back().accept(v) == CONTINUE) { opt_seq.pop_back(); opt_seq.emplace_back(new set(node.loc(), node.offset(), v.new_value())); return CONTINUE; } } // else make node copy return opt_seq_base_visitor::handle_add(node); } status visit(sub &node) { // discard any zero value node if (node.value() == 0) { return CONTINUE; } // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible try_combine_set_inc_visitor v(node.offset(), node.value(), false); if (opt_seq.back().accept(v) == CONTINUE) { opt_seq.pop_back(); opt_seq.emplace_back(new set(node.loc(), node.offset(), v.new_value())); return CONTINUE; } } // else make node copy return opt_seq_base_visitor::handle_sub(node); } status visit(const sub &node) { // discard any zero value node if (node.value() == 0) { return CONTINUE; } // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible try_combine_set_inc_visitor v(node.offset(), node.value(), false); if (opt_seq.back().accept(v) == CONTINUE) { opt_seq.pop_back(); opt_seq.emplace_back(new set(node.loc(), node.offset(), v.new_value())); return CONTINUE; } } // else make node copy return opt_seq_base_visitor::handle_sub(node); } private: class test_combine_set_visitor : public test_visitor { public: status visit(set &node) { return CONTINUE; } status visit(const add &set) { return CONTINUE; } status visit(add &node) { return CONTINUE; } status visit(const add &node) { return CONTINUE; } status visit(sub &node) { return CONTINUE; } status visit(const sub &node) { return CONTINUE; } }; class try_combine_set_inc_visitor : public test_visitor { public: try_combine_inc_visitor(ptrdiff_t offset, bf_value val, bool isAdd) : isAdd(isAdd), next_off(offset), next_val(val) {} bf_value new_value() { return new_val; } status visit(set &node) { if (node.offset() != next_off) { return BREAK; } new_val = node.value(); isAdd ? new_val += next_val : new_val -= next_val; return CONTINUE; } status visit(const set &node) { if (node.offset() != next_off) { return BREAK; } new_val = node.value(); isAdd ? new_val += next_val : new_val -= next_val; return CONTINUE; } private: bool isAdd; ptrdiff_t next_off; bf_value next_val; bf_value new_val; }; }; } } #endif /* !BFC_COMBINE_SET_VISITOR_HPP */ <commit_msg>Typo yo<commit_after>#ifndef BFC_COMBINE_SET_VISITOR_HPP #define BFC_COMBINE_SET_VISITOR_HPP #include "ast/mod.hpp" #include "test_visitor.hpp" #include "opt_seq_base_visitor.hpp" #include "types.h" namespace bfc { namespace ast { class combine_set_visitor : public opt_seq_base_visitor { public: status visit(set &node) { // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible test_combine_set_visitor v; if (opt_seq.back().accept(v) == CONTINUE) { // discard the previous node (undone by this set) opt_seq.pop_back(); } } // copy the node return opt_seq_base_visitor::handle_set(node); } status visit(const set &node) { // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible test_combine_set_visitor v; if (opt_seq.back().accept(v) == CONTINUE) { // discard the previous node (undone by this set) opt_seq.pop_back(); } } // copy the node return opt_seq_base_visitor::handle_set(node); } status visit(add &node) { // discard any zero value node if (node.value() == 0) { return CONTINUE; } // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible try_combine_set_inc_visitor v(node.offset(), node.value(), true); if (opt_seq.back().accept(v) == CONTINUE) { opt_seq.pop_back(); opt_seq.emplace_back(new set(node.loc(), node.offset(), v.new_value())); return CONTINUE; } } // else make node copy return opt_seq_base_visitor::handle_add(node); } status visit(const add &node) { // discard any zero value node if (node.value() == 0) { return CONTINUE; } // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible try_combine_set_inc_visitor v(node.offset(), node.value(), true); if (opt_seq.back().accept(v) == CONTINUE) { opt_seq.pop_back(); opt_seq.emplace_back(new set(node.loc(), node.offset(), v.new_value())); return CONTINUE; } } // else make node copy return opt_seq_base_visitor::handle_add(node); } status visit(sub &node) { // discard any zero value node if (node.value() == 0) { return CONTINUE; } // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible try_combine_set_inc_visitor v(node.offset(), node.value(), false); if (opt_seq.back().accept(v) == CONTINUE) { opt_seq.pop_back(); opt_seq.emplace_back(new set(node.loc(), node.offset(), v.new_value())); return CONTINUE; } } // else make node copy return opt_seq_base_visitor::handle_sub(node); } status visit(const sub &node) { // discard any zero value node if (node.value() == 0) { return CONTINUE; } // Only attempt to combine if there is a previous node if (!opt_seq.empty()) { // try to combine with the previous node if possible try_combine_set_inc_visitor v(node.offset(), node.value(), false); if (opt_seq.back().accept(v) == CONTINUE) { opt_seq.pop_back(); opt_seq.emplace_back(new set(node.loc(), node.offset(), v.new_value())); return CONTINUE; } } // else make node copy return opt_seq_base_visitor::handle_sub(node); } private: class test_combine_set_visitor : public test_visitor { public: status visit(set &node) { return CONTINUE; } status visit(const set &node) { return CONTINUE; } status visit(add &node) { return CONTINUE; } status visit(const add &node) { return CONTINUE; } status visit(sub &node) { return CONTINUE; } status visit(const sub &node) { return CONTINUE; } }; class try_combine_set_inc_visitor : public test_visitor { public: try_combine_inc_visitor(ptrdiff_t offset, bf_value val, bool isAdd) : isAdd(isAdd), next_off(offset), next_val(val) {} bf_value new_value() { return new_val; } status visit(set &node) { if (node.offset() != next_off) { return BREAK; } new_val = node.value(); isAdd ? new_val += next_val : new_val -= next_val; return CONTINUE; } status visit(const set &node) { if (node.offset() != next_off) { return BREAK; } new_val = node.value(); isAdd ? new_val += next_val : new_val -= next_val; return CONTINUE; } private: bool isAdd; ptrdiff_t next_off; bf_value next_val; bf_value new_val; }; }; } } #endif /* !BFC_COMBINE_SET_VISITOR_HPP */ <|endoftext|>
<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2019 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/cameras/Camera_Pinhole.hpp" #include "openMVG/cameras/Camera_Spherical.hpp" #include "openMVG/geometry/pose3.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/image/sample.hpp" #include "openMVG/numeric/eigen_alias_definition.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/sfm/sfm_landmark.hpp" #include "openMVG/sfm/sfm_view.hpp" #include "openMVG/types.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/progress/progress_display.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <array> #include <cstdlib> #include <cmath> #include <iomanip> using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::sfm; /// Compute a rectilinear camera focal for a given angular desired FoV and image size double FocalFromPinholeHeight ( int h, double thetaMax = openMVG::D2R(60) // Camera FoV ) { float f = 1.f; while ( thetaMax < atan2( h / (2 * f) , 1)) { ++f; } return f; } const std::array<openMVG::Mat3,6> GetCubicRotations() { using namespace openMVG; return { RotationAroundY(D2R(0)), // front RotationAroundY(D2R(-90)), // right RotationAroundY(D2R(-180)), // behind RotationAroundY(D2R(-270)), // left RotationAroundX(D2R(-90)), // up RotationAroundX(D2R(+90)) // down }; } void ComputeCubicCameraIntrinsics(const int cubic_image_size, openMVG::cameras::Pinhole_Intrinsic & pinhole_camera) { const double focal = FocalFromPinholeHeight(cubic_image_size, D2R(45)); const double principal_point_xy = cubic_image_size / 2; pinhole_camera = Pinhole_Intrinsic(cubic_image_size, cubic_image_size, focal, principal_point_xy, principal_point_xy); } template <typename ImageT> void SphericalToCubic ( const ImageT & equirectangular_image, const openMVG::cameras::Pinhole_Intrinsic & pinhole_camera, std::vector<ImageT> & cube_images ) { using namespace openMVG; using namespace openMVG::cameras; const image::Sampler2d<image::SamplerLinear> sampler; // // Initialize a camera model for each image domain // - the equirectangular panorama const Intrinsic_Spherical sphere_camera( equirectangular_image.Width() - 1, equirectangular_image.Height() - 1); // - the cube faces // // Perform backward/inverse rendering: // - For each cube face (rotation) // - Sample the panorama pixel by camera to camera bearing vector projection const int cubic_image_size = pinhole_camera.h(); cube_images.resize(6, ImageT(cubic_image_size, cubic_image_size)); // Initialize the rotation matrices corresponding to each cube face const std::array<Mat3, 6> rot_matrix = GetCubicRotations(); for (const int i_rot : {0, 1, 2, 3, 4, 5}) { // std::cout << "generate view " << i_rot << std::endl; auto & pinhole_image = cube_images[i_rot]; const int image_width = pinhole_image.Width(); const int image_height = pinhole_image.Height(); // For every pinhole image pixels for (int x = 0; x < image_width; ++x) { // std::cout << " row = " << x << std::endl; for (int y = 0; y < image_height; ++y) { // Project the pinhole bearing vector to the spherical camera const Vec3 pinhole_bearing = rot_matrix[i_rot].transpose() * pinhole_camera(Vec2(x, y)); const Vec2 sphere_proj = sphere_camera.project(pinhole_bearing); if (equirectangular_image.Contains(sphere_proj(1), sphere_proj(0))) { pinhole_image(y, x) = sampler(equirectangular_image, sphere_proj(1), sphere_proj(0)); } } } } } int main(int argc, char *argv[]) { CmdLine cmd; std::string s_sfm_data_filename; std::string s_out_dir = ""; int force_recompute_images = 1; cmd.add( make_option('i', s_sfm_data_filename, "sfmdata") ); cmd.add( make_option('o', s_out_dir, "outdir") ); cmd.add( make_option('f', force_recompute_images, "force_compute_cubic_images") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--sfmdata] filename, the SfM_Data file to convert\n" << "[-o|--outdir path]\n" << "[-f|--force_recompute_images] (default 1)\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } std::cout << "force_recompute_images = " << force_recompute_images << std::endl; // Create output dir if (!stlplus::folder_exists(s_out_dir)) stlplus::folder_create(s_out_dir); SfM_Data sfm_data; if (!Load(sfm_data, s_sfm_data_filename, ESfM_Data(ALL))) { std::cerr << std::endl << "The input SfM_Data file \""<< s_sfm_data_filename << "\" cannot be read." << std::endl; return EXIT_FAILURE; } SfM_Data sfm_data_out; // the sfm_data that stores the cubical image list std::vector<image::Image<image::RGBColor>> cube_images; // Convert every spherical view to cubic views { std::cout << "Generating cubic views:"; C_Progress_display my_progress_bar(sfm_data.GetViews().size()); const Views & views = sfm_data.GetViews(); const Poses & poses = sfm_data.GetPoses(); const Landmarks & structure = sfm_data.GetLandmarks(); // generate views and camera poses for each new views for (int i = 0; i < static_cast<int>(views.size()); ++i) { ++my_progress_bar; auto view_it = views.begin(); std::advance(view_it, i); const View * view = view_it->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; Intrinsics::const_iterator iter_intrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); const IntrinsicBase * cam = iter_intrinsic->second.get(); if (cam && cam->getType() == CAMERA_SPHERICAL) { // We have a valid view with a corresponding camera & pose //std::cout << "sfm_data.s_root_path = " << sfm_data.s_root_path << std::endl; //std::cout << "view->s_Img_path = " << view->s_Img_path << std::endl; const std::string view_path = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path); image::Image<image::RGBColor> spherical_image; if (!ReadImage(view_path.c_str(), &spherical_image)) { std::cerr << "Cannot read the input panoramic image: " << view_path << std::endl; return EXIT_FAILURE; } openMVG::cameras::Pinhole_Intrinsic pinhole_camera; const int cubic_image_size = 1024; ComputeCubicCameraIntrinsics(cubic_image_size, pinhole_camera); // when cubical image computation is needed if (force_recompute_images) SphericalToCubic(spherical_image, pinhole_camera, cube_images); const std::array<Mat3,6> rot_matrix = GetCubicRotations(); for (const int cubic_image_id : {0,1,2,3,4,5}) { std::ostringstream os; os << std::setw(8) << std::setfill('0') << cubic_image_id; const std::string dst_cube_image = stlplus::create_filespec( stlplus::folder_append_separator(s_out_dir), stlplus::basename_part(view_path) + "_perspective_" + os.str(), "png" ); // when cubical image computation is needed if (force_recompute_images) { if (!WriteImage(dst_cube_image.c_str(), cube_images[cubic_image_id])) { std::cout << "Cannot export cubic images to: " << dst_cube_image << std::endl; return EXIT_FAILURE; } } const View v( dst_cube_image, view->id_view * 6 + cubic_image_id, // Id view 0, // Id intrinsic view->id_pose * 6 + cubic_image_id, // Id pose pinhole_camera.w(), pinhole_camera.h() ); sfm_data_out.views[v.id_view] = std::make_shared<View>(v); // due to 360 cameras, rotation after BA might come with determinant -1 // if so, negate the rotation for future use. Mat3 tmp_rotation = poses.at(view->id_pose).rotation(); if (tmp_rotation.determinant()<0) tmp_rotation = tmp_rotation*(-1.0f); sfm_data_out.poses[v.id_pose] = Pose3( rot_matrix[cubic_image_id] * tmp_rotation, poses.at(view->id_pose).center() ); if (sfm_data_out.GetIntrinsics().count(v.id_intrinsic) == 0) sfm_data_out.intrinsics[v.id_intrinsic] = std::make_shared<Pinhole_Intrinsic>(pinhole_camera); } } } // end of generate views and camera poses for each new views // output camera views for debugging purpose if (0) { const int num_output_views = sfm_data_out.views.size(); std::cout << "num of output views = " << num_output_views << std::endl; for (int i = 0; i < num_output_views; ++i) { const Pose3 pose = sfm_data_out.poses[i]; std::cout << "R{" << i+1 << "} = [" << pose.rotation()(0,0) << " " << pose.rotation()(0,1) << " " << pose.rotation()(0,2) << std::endl << pose.rotation()(1,0) << " " << pose.rotation()(1,1) << " " << pose.rotation()(1,2) << std::endl << pose.rotation()(2,0) << " " << pose.rotation()(2,1) << " " << pose.rotation()(2,2) << "]';" << std::endl; std::cout << "T{" << i+1 << "} = [" << pose.center().x() << " " << pose.center().y() << " " << pose.center().z() << "]';" << std::endl; } } // generate structure and associate it with new camera views { std::cout << "Creating cubic sfm_data structure:"; C_Progress_display my_progress_bar(structure.size()); for (Landmarks::const_iterator it = structure.begin(); it != structure.end(); ++it) { // std::cout << it->second.X.x() << ", " << it->second.X.y() << ", " << it->second.X.z() << std::endl; ++my_progress_bar; const Observations & obs = it->second.obs; Observations::const_iterator itObs = obs.begin(); Landmark out_landmark; out_landmark.X = it->second.X; // iterate across 360 views that can see the point while (itObs != obs.end()) { IndexT pano_view_key = itObs->first; IndexT feature_key = itObs->second.id_feat; // get cubical camera ids and poses and reproject to see if the 3D point is inside the view bool is_reprojection_found = false; for (IndexT local_view_index = pano_view_key * 6; local_view_index < pano_view_key * 6 + 6; ++local_view_index) { IndexT intrinsic_id = sfm_data_out.views[local_view_index]->id_intrinsic; IndexT extrinsic_id = sfm_data_out.views[local_view_index]->id_pose; const Pose3 pose = sfm_data_out.poses[extrinsic_id]; const Mat34 P = sfm_data_out.intrinsics[intrinsic_id]->get_projective_equivalent(pose); const int image_height = sfm_data_out.intrinsics[intrinsic_id]->h(); const int image_width = sfm_data_out.intrinsics[intrinsic_id]->w(); Vec2 projection = Project(P, it->second.X); if (projection.x() < 0 || projection.x() >= image_width || projection.y() < 0 || projection.y() >= image_height) continue; Vec3 point_to_cam_dir = it->second.X - pose.center(); point_to_cam_dir.normalize(); Vec3 cam_looking_dir = pose.rotation().transpose() * Vec3(0,0, 1); cam_looking_dir.normalize(); const double angle = acos(point_to_cam_dir.dot(cam_looking_dir))/M_PI*180; if (angle < 0 || angle > 90) continue; // std::cout << "view " << local_view_index << " has angle = " << angle << std::endl; out_landmark.obs[local_view_index] = Observation(projection, feature_key); is_reprojection_found = true; break; // if one of the 6 views observe the 3D point, no other views from the 6 views should observe it } // end of looping 6 view of 1 pano image assert(is_reprojection_found); // make sure the observation is found ++itObs; } // end of observations from all panos sfm_data_out.structure.insert({it->first, out_landmark}); } } } // end of converting spherical view to cubical if (!Save( sfm_data_out, stlplus::create_filespec( stlplus::folder_append_separator(s_out_dir), "sfm_data_perspective.bin"), ESfM_Data(ALL))) { std::cerr << std::endl << "Cannot save the output sfm_data file" << std::endl; return EXIT_FAILURE; } std::cout << " #views: " << sfm_data_out.views.size() << "\n" << " #poses: " << sfm_data_out.poses.size() << "\n" << " #intrinsics: " << sfm_data_out.intrinsics.size() << "\n" << " #tracks: " << sfm_data_out.structure.size() << "\n" << std::endl; // Exit program return EXIT_SUCCESS; } <commit_msg>[SfM/export] Update openMVGSpherical2Cubic #1505<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2019 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/cameras/Camera_Pinhole.hpp" #include "openMVG/cameras/Camera_Spherical.hpp" #include "openMVG/geometry/pose3.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/image/sample.hpp" #include "openMVG/numeric/eigen_alias_definition.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/sfm/sfm_landmark.hpp" #include "openMVG/sfm/sfm_view.hpp" #include "openMVG/types.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/progress/progress_display.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <array> #include <cstdlib> #include <cmath> #include <iomanip> using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::sfm; /// Compute a rectilinear camera focal for a given angular desired FoV and image size double FocalFromPinholeHeight ( int h, double thetaMax = openMVG::D2R(60) // Camera FoV ) { float f = 1.f; while ( thetaMax < atan2( h / (2 * f) , 1)) { ++f; } return f; } const std::array<openMVG::Mat3,6> GetCubicRotations() { using namespace openMVG; return { RotationAroundY(D2R(0)), // front RotationAroundY(D2R(-90)), // right RotationAroundY(D2R(-180)), // behind RotationAroundY(D2R(-270)), // left RotationAroundX(D2R(-90)), // up RotationAroundX(D2R(+90)) // down }; } void ComputeCubicCameraIntrinsics(const int cubic_image_size, openMVG::cameras::Pinhole_Intrinsic & pinhole_camera) { const double focal = FocalFromPinholeHeight(cubic_image_size, D2R(45)); const double principal_point_xy = cubic_image_size / 2; pinhole_camera = Pinhole_Intrinsic(cubic_image_size, cubic_image_size, focal, principal_point_xy, principal_point_xy); } template <typename ImageT> void SphericalToCubic ( const ImageT & equirectangular_image, const openMVG::cameras::Pinhole_Intrinsic & pinhole_camera, std::vector<ImageT> & cube_images ) { using namespace openMVG; using namespace openMVG::cameras; const image::Sampler2d<image::SamplerLinear> sampler; // // Initialize a camera model for each image domain // - the equirectangular panorama const Intrinsic_Spherical sphere_camera(equirectangular_image.Width() - 1, equirectangular_image.Height() - 1); // - the cube faces // // Perform backward/inverse rendering: // - For each cube face (rotation) // - Sample the panorama pixel by camera to camera bearing vector projection const int cubic_image_size = pinhole_camera.h(); cube_images.resize(6, ImageT(cubic_image_size, cubic_image_size)); // Initialize the rotation matrices corresponding to each cube face const std::array<Mat3, 6> rot_matrix = GetCubicRotations(); for (const int i_rot : {0, 1, 2, 3, 4, 5}) { auto & pinhole_image = cube_images[i_rot]; const int image_width = pinhole_image.Width(); const int image_height = pinhole_image.Height(); // For every pinhole image pixels for (int x = 0; x < image_width; ++x) { for (int y = 0; y < image_height; ++y) { // Project the pinhole bearing vector to the spherical camera const Vec3 pinhole_bearing = rot_matrix[i_rot].transpose() * pinhole_camera(Vec2(x, y)); const Vec2 sphere_proj = sphere_camera.project(pinhole_bearing); if (equirectangular_image.Contains(sphere_proj(1), sphere_proj(0))) { pinhole_image(y, x) = sampler(equirectangular_image, sphere_proj(1), sphere_proj(0)); } } } } } int main(int argc, char *argv[]) { CmdLine cmd; std::string s_sfm_data_filename; std::string s_out_dir = ""; int force_recompute_images = 1; cmd.add( make_option('i', s_sfm_data_filename, "sfmdata") ); cmd.add( make_option('o', s_out_dir, "outdir") ); cmd.add( make_option('f', force_recompute_images, "force_compute_cubic_images") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--sfmdata] filename, the SfM_Data file to convert\n" << "[-o|--outdir path]\n" << "[-f|--force_recompute_images] (default 1)\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } std::cout << "force_recompute_images = " << force_recompute_images << std::endl; // Create output dir if (!stlplus::folder_exists(s_out_dir)) stlplus::folder_create(s_out_dir); SfM_Data sfm_data; if (!Load(sfm_data, s_sfm_data_filename, ESfM_Data(ALL))) { std::cerr << std::endl << "The input SfM_Data file \""<< s_sfm_data_filename << "\" cannot be read." << std::endl; return EXIT_FAILURE; } SfM_Data sfm_data_out; // the sfm_data that stores the cubical image list sfm_data_out.s_root_path = s_out_dir; // Convert every spherical view to cubic views { std::cout << "Generating cubic views:"; C_Progress_display my_progress_bar(sfm_data.GetViews().size()); const Views & views = sfm_data.GetViews(); const Poses & poses = sfm_data.GetPoses(); const Landmarks & structure = sfm_data.GetLandmarks(); // generate views and camera poses for each new views int error_status = 0; #pragma omp parallel for shared(error_status) if(error_status < 1) for (int i = 0; i < static_cast<int>(views.size()); ++i) { ++my_progress_bar; auto view_it = views.begin(); std::advance(view_it, i); const View * view = view_it->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; Intrinsics::const_iterator iter_intrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); const IntrinsicBase * cam = iter_intrinsic->second.get(); if (cam && cam->getType() == CAMERA_SPHERICAL) { // We have a valid view with a corresponding camera & pose const std::string view_path = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path); image::Image<image::RGBColor> spherical_image; if (!ReadImage(view_path.c_str(), &spherical_image)) { std::cerr << "Cannot read the input panoramic image: " << view_path << std::endl; #pragma omp atomic ++error_status; continue; } openMVG::cameras::Pinhole_Intrinsic pinhole_camera; const int cubic_image_size = 1024; ComputeCubicCameraIntrinsics(cubic_image_size, pinhole_camera); // when cubical image computation is needed std::vector<image::Image<image::RGBColor>> cube_images; if (force_recompute_images) SphericalToCubic(spherical_image, pinhole_camera, cube_images); const std::array<Mat3,6> rot_matrix = GetCubicRotations(); for (const int cubic_image_id : {0,1,2,3,4,5}) { std::ostringstream os; os << std::setw(8) << std::setfill('0') << cubic_image_id; const std::string dst_cube_image = stlplus::create_filespec( stlplus::folder_append_separator(s_out_dir), stlplus::basename_part(view_path) + "_perspective_" + os.str(), "png"); // when cubical image computation is needed if (force_recompute_images) { if (!WriteImage(dst_cube_image.c_str(), cube_images[cubic_image_id])) { std::cout << "Cannot export cubic images to: " << dst_cube_image << std::endl; #pragma omp atomic ++error_status; continue; } } const View v( stlplus::filename_part(dst_cube_image), view->id_view * 6 + cubic_image_id, // Id view 0, // Id intrinsic view->id_pose * 6 + cubic_image_id, // Id pose pinhole_camera.w(), pinhole_camera.h()); sfm_data_out.views[v.id_view] = std::make_shared<View>(v); // due to 360 cameras, rotation after BA might come with determinant -1 // if so, negate the rotation for future use. Mat3 tmp_rotation = poses.at(view->id_pose).rotation(); if (tmp_rotation.determinant() < 0) { std::cout << "Negative determinant" << std::endl; tmp_rotation = tmp_rotation*(-1.0f); } sfm_data_out.poses[v.id_pose] = Pose3(rot_matrix[cubic_image_id] * tmp_rotation, poses.at(view->id_pose).center()); if (sfm_data_out.GetIntrinsics().count(v.id_intrinsic) == 0) sfm_data_out.intrinsics[v.id_intrinsic] = std::make_shared<Pinhole_Intrinsic>(pinhole_camera); } } else { std::cout << "Loaded scene does not have spherical camera" << std::endl; #pragma omp atomic ++error_status; continue; } } // end of generate views and camera poses for each new views if (error_status > 0) // early exit return EXIT_FAILURE; // generate structure and associate it with new camera views { std::cout << "Creating cubic sfm_data structure:"; C_Progress_display my_progress_bar(structure.size()); for (const auto & it_structure : structure) { ++my_progress_bar; const Observations & obs = it_structure.second.obs; Landmark out_landmark; out_landmark.X = it_structure.second.X; // iterate across 360 views that can see the point for(const auto & it_obs : obs) { const IndexT pano_view_key = it_obs.first; const IndexT feature_key = it_obs.second.id_feat; // get cubical camera ids and poses and reproject to see if the 3D point is inside the view bool is_reprojection_found = false; for (IndexT local_view_index = pano_view_key * 6; local_view_index < pano_view_key * 6 + 6; ++local_view_index) { const IndexT intrinsic_id = sfm_data_out.views[local_view_index]->id_intrinsic; const IndexT extrinsic_id = sfm_data_out.views[local_view_index]->id_pose; const Pose3 pose = sfm_data_out.poses[extrinsic_id]; const auto cam = sfm_data_out.intrinsics[intrinsic_id]; const int image_height = cam->h(); const int image_width = cam->w(); const Vec2 projection = cam->project(pose(it_structure.second.X)); if (projection.x() < 0 || projection.x() >= image_width || projection.y() < 0 || projection.y() >= image_height) continue; const Vec3 point_to_cam_dir = (it_structure.second.X - pose.center()).normalized(); const Vec3 cam_looking_dir = (pose.rotation().transpose() * Vec3(0, 0, 1)).normalized(); const double angle = R2D(acos(point_to_cam_dir.dot(cam_looking_dir))); if (angle < 0 || angle > 90) continue; out_landmark.obs[local_view_index] = Observation(projection, feature_key); is_reprojection_found = true; break; // if one of the 6 views observe the 3D point, no other views from the 6 views should observe it } // end of looping 6 view of 1 pano image assert(is_reprojection_found); // make sure the observation is found } // end of observations from all panos sfm_data_out.structure.insert({it_structure.first, out_landmark}); } } } // end of converting spherical view to cubical if (!Save(sfm_data_out, stlplus::create_filespec(stlplus::folder_append_separator(s_out_dir), "sfm_data_perspective.bin"), ESfM_Data(ALL))) { std::cerr << std::endl << "Cannot save the output sfm_data file" << std::endl; return EXIT_FAILURE; } std::cout << " #views: " << sfm_data_out.views.size() << "\n" << " #poses: " << sfm_data_out.poses.size() << "\n" << " #intrinsics: " << sfm_data_out.intrinsics.size() << "\n" << " #tracks: " << sfm_data_out.structure.size() << "\n" << std::endl; // Exit program return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** * \file * \brief MessageQueueBase class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_ #include "distortos/Semaphore.hpp" #include "distortos/internal/synchronization/QueueFunctor.hpp" #include "distortos/internal/synchronization/SemaphoreFunctor.hpp" #include "estd/SortedIntrusiveForwardList.hpp" #include <memory> namespace distortos { namespace internal { /// MessageQueueBase class implements basic functionality of MessageQueue template class class MessageQueueBase { public: /// entry in the MessageQueueBase struct Entry { /** * \brief Entry's constructor * * \param [in] priorityy is the priority of the entry * \param [in] storagee is the storage for the entry */ constexpr Entry(const uint8_t priorityy, void* const storagee) : node{}, priority{priorityy}, storage{storagee} { } /// node for intrusive forward list estd::IntrusiveForwardListNode node; /// priority of the entry uint8_t priority; /// storage for the entry void* storage; }; /// type of uninitialized storage for Entry using EntryStorage = typename std::aligned_storage<sizeof(Entry), alignof(Entry)>::type; /// unique_ptr (with deleter) to EntryStorage[] using EntryStorageUniquePointer = std::unique_ptr<EntryStorage[], void(&)(EntryStorage*)>; /** * type of uninitialized storage for value * * \tparam T is the type of data in queue */ template<typename T> using ValueStorage = typename std::aligned_storage<sizeof(T), alignof(T)>::type; /// unique_ptr (with deleter) to storage using ValueStorageUniquePointer = std::unique_ptr<void, void(&)(void*)>; /// functor which gives descending priority order of elements on the list struct DescendingPriority { /** * \brief DescendingPriority's constructor */ constexpr DescendingPriority() { } /** * \brief DescendingPriority's function call operator * * \param [in] left is the object on the left side of comparison * \param [in] right is the object on the right side of comparison * * \return true if left's priority is less than right's priority */ bool operator()(const Entry& left, const Entry& right) const { return left.priority < right.priority; } }; /// type of entry list using EntryList = estd::SortedIntrusiveForwardList<DescendingPriority, Entry, &Entry::node>; /// type of free entry list using FreeEntryList = EntryList::UnsortedIntrusiveForwardList; /** * \brief InternalFunctor is a type-erased interface for functors which execute common code of pop() and push() * operations. * * The functor will be called by MessageQueueBase internals with references to \a entryList_ and \a freeEntryList_. * It should perform common actions and execute the QueueFunctor passed from callers. */ class InternalFunctor : public estd::TypeErasedFunctor<void(EntryList&, FreeEntryList&)> { }; /** * \brief MessageQueueBase's constructor * * \param [in] entryStorageUniquePointer is a rvalue reference to EntryStorageUniquePointer with storage for queue * entries (sufficiently large for \a maxElements EntryStorage objects) and appropriate deleter * \param [in] valueStorageUniquePointer is a rvalue reference to ValueStorageUniquePointer with storage for queue * elements (sufficiently large for \a maxElements, each \a elementSize bytes long) and appropriate deleter * \param [in] elementSize is the size of single queue element, bytes * \param [in] maxElements is the number of elements in \a entryStorage array and valueStorage memory block */ MessageQueueBase(EntryStorageUniquePointer&& entryStorageUniquePointer, ValueStorageUniquePointer&& valueStorageUniquePointer, size_t elementSize, size_t maxElements); /** * \brief MessageQueueBase's destructor */ ~MessageQueueBase(); /** * \brief Implementation of pop() using type-erased functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_ * \param [out] priority is a reference to variable that will be used to return priority of popped value * \param [in] functor is a reference to QueueFunctor which will execute actions related to popping - it will get a * pointer to storage with element * * \return 0 if element was popped successfully, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int pop(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t& priority, const QueueFunctor& functor); /** * \brief Implementation of push() using type-erased functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_ * \param [in] priority is the priority of new element * \param [in] functor is a reference to QueueFunctor which will execute actions related to pushing - it will get a * pointer to storage for element * * \return 0 if element was pushed successfully, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int push(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority, const QueueFunctor& functor); private: /** * \brief Implementation of pop() and push() using type-erased internal functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a waitSemaphore * \param [in] internalFunctor is a reference to InternalFunctor which will execute actions related to * popping/pushing * \param [in] waitSemaphore is a reference to semaphore that will be waited for, \a popSemaphore_ for pop(), \a * pushSemaphore_ for push() * \param [in] postSemaphore is a reference to semaphore that will be posted after the operation, \a pushSemaphore_ * for pop(), \a popSemaphore_ for push() * * \return 0 if operation was successful, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int popPush(const SemaphoreFunctor& waitSemaphoreFunctor, const InternalFunctor& internalFunctor, Semaphore& waitSemaphore, Semaphore& postSemaphore); /// semaphore guarding access to "pop" functions - its value is equal to the number of available elements Semaphore popSemaphore_; /// semaphore guarding access to "push" functions - its value is equal to the number of free slots Semaphore pushSemaphore_; /// storage for queue entries const EntryStorageUniquePointer entryStorageUniquePointer_; /// storage for queue elements const ValueStorageUniquePointer valueStorageUniquePointer_; /// list of available entries, sorted in descending order of priority EntryList entryList_; /// list of "free" entries FreeEntryList freeEntryList_; }; } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_ <commit_msg>Add MessageQueueBase::getCapacity()<commit_after>/** * \file * \brief MessageQueueBase class header * * \author Copyright (C) 2015-2019 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_ #include "distortos/Semaphore.hpp" #include "distortos/internal/synchronization/QueueFunctor.hpp" #include "distortos/internal/synchronization/SemaphoreFunctor.hpp" #include "estd/SortedIntrusiveForwardList.hpp" #include <memory> namespace distortos { namespace internal { /// MessageQueueBase class implements basic functionality of MessageQueue template class class MessageQueueBase { public: /// entry in the MessageQueueBase struct Entry { /** * \brief Entry's constructor * * \param [in] priorityy is the priority of the entry * \param [in] storagee is the storage for the entry */ constexpr Entry(const uint8_t priorityy, void* const storagee) : node{}, priority{priorityy}, storage{storagee} { } /// node for intrusive forward list estd::IntrusiveForwardListNode node; /// priority of the entry uint8_t priority; /// storage for the entry void* storage; }; /// type of uninitialized storage for Entry using EntryStorage = typename std::aligned_storage<sizeof(Entry), alignof(Entry)>::type; /// unique_ptr (with deleter) to EntryStorage[] using EntryStorageUniquePointer = std::unique_ptr<EntryStorage[], void(&)(EntryStorage*)>; /** * type of uninitialized storage for value * * \tparam T is the type of data in queue */ template<typename T> using ValueStorage = typename std::aligned_storage<sizeof(T), alignof(T)>::type; /// unique_ptr (with deleter) to storage using ValueStorageUniquePointer = std::unique_ptr<void, void(&)(void*)>; /// functor which gives descending priority order of elements on the list struct DescendingPriority { /** * \brief DescendingPriority's constructor */ constexpr DescendingPriority() { } /** * \brief DescendingPriority's function call operator * * \param [in] left is the object on the left side of comparison * \param [in] right is the object on the right side of comparison * * \return true if left's priority is less than right's priority */ bool operator()(const Entry& left, const Entry& right) const { return left.priority < right.priority; } }; /// type of entry list using EntryList = estd::SortedIntrusiveForwardList<DescendingPriority, Entry, &Entry::node>; /// type of free entry list using FreeEntryList = EntryList::UnsortedIntrusiveForwardList; /** * \brief InternalFunctor is a type-erased interface for functors which execute common code of pop() and push() * operations. * * The functor will be called by MessageQueueBase internals with references to \a entryList_ and \a freeEntryList_. * It should perform common actions and execute the QueueFunctor passed from callers. */ class InternalFunctor : public estd::TypeErasedFunctor<void(EntryList&, FreeEntryList&)> { }; /** * \brief MessageQueueBase's constructor * * \param [in] entryStorageUniquePointer is a rvalue reference to EntryStorageUniquePointer with storage for queue * entries (sufficiently large for \a maxElements EntryStorage objects) and appropriate deleter * \param [in] valueStorageUniquePointer is a rvalue reference to ValueStorageUniquePointer with storage for queue * elements (sufficiently large for \a maxElements, each \a elementSize bytes long) and appropriate deleter * \param [in] elementSize is the size of single queue element, bytes * \param [in] maxElements is the number of elements in \a entryStorage array and valueStorage memory block */ MessageQueueBase(EntryStorageUniquePointer&& entryStorageUniquePointer, ValueStorageUniquePointer&& valueStorageUniquePointer, size_t elementSize, size_t maxElements); /** * \brief MessageQueueBase's destructor */ ~MessageQueueBase(); /** * \return maximum number of elements in queue */ size_t getCapacity() const { return popSemaphore_.getMaxValue(); } /** * \brief Implementation of pop() using type-erased functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_ * \param [out] priority is a reference to variable that will be used to return priority of popped value * \param [in] functor is a reference to QueueFunctor which will execute actions related to popping - it will get a * pointer to storage with element * * \return 0 if element was popped successfully, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int pop(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t& priority, const QueueFunctor& functor); /** * \brief Implementation of push() using type-erased functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_ * \param [in] priority is the priority of new element * \param [in] functor is a reference to QueueFunctor which will execute actions related to pushing - it will get a * pointer to storage for element * * \return 0 if element was pushed successfully, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int push(const SemaphoreFunctor& waitSemaphoreFunctor, uint8_t priority, const QueueFunctor& functor); private: /** * \brief Implementation of pop() and push() using type-erased internal functor * * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a waitSemaphore * \param [in] internalFunctor is a reference to InternalFunctor which will execute actions related to * popping/pushing * \param [in] waitSemaphore is a reference to semaphore that will be waited for, \a popSemaphore_ for pop(), \a * pushSemaphore_ for push() * \param [in] postSemaphore is a reference to semaphore that will be posted after the operation, \a pushSemaphore_ * for pop(), \a popSemaphore_ for push() * * \return 0 if operation was successful, error code otherwise: * - error codes returned by \a waitSemaphoreFunctor's operator() call; * - error codes returned by Semaphore::post(); */ int popPush(const SemaphoreFunctor& waitSemaphoreFunctor, const InternalFunctor& internalFunctor, Semaphore& waitSemaphore, Semaphore& postSemaphore); /// semaphore guarding access to "pop" functions - its value is equal to the number of available elements Semaphore popSemaphore_; /// semaphore guarding access to "push" functions - its value is equal to the number of free slots Semaphore pushSemaphore_; /// storage for queue entries const EntryStorageUniquePointer entryStorageUniquePointer_; /// storage for queue elements const ValueStorageUniquePointer valueStorageUniquePointer_; /// list of available entries, sorted in descending order of priority EntryList entryList_; /// list of "free" entries FreeEntryList freeEntryList_; }; } // namespace internal } // namespace distortos #endif // INCLUDE_DISTORTOS_INTERNAL_SYNCHRONIZATION_MESSAGEQUEUEBASE_HPP_ <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <test/models/model_test_fixture.hpp> class Models_BugsExamples_Vol1_Bones : public Model_Test_Fixture<Models_BugsExamples_Vol1_Bones> { protected: virtual void SetUp() { } public: static std::vector<std::string> get_model_path() { std::vector<std::string> model_path; model_path.push_back("models"); model_path.push_back("bugs_examples"); model_path.push_back("vol1"); model_path.push_back("bones"); model_path.push_back("bones"); return model_path; } static bool has_data() { return true; } static std::vector<std::pair<size_t, double> > get_expected_values() { std::vector<std::pair<size_t, double> > expected_values; return expected_values; } }; INSTANTIATE_TYPED_TEST_CASE_P(Models_BugsExamples_Vol1_Bones, Model_Test_Fixture, Models_BugsExamples_Vol1_Bones); <commit_msg>test/models/bugs_examples/vol1/bones/bones_test: added reference values for the parameters<commit_after>#include <gtest/gtest.h> #include <test/models/model_test_fixture.hpp> class Models_BugsExamples_Vol1_Bones : public Model_Test_Fixture<Models_BugsExamples_Vol1_Bones> { protected: virtual void SetUp() { } public: static std::vector<std::string> get_model_path() { std::vector<std::string> model_path; model_path.push_back("models"); model_path.push_back("bugs_examples"); model_path.push_back("vol1"); model_path.push_back("bones"); model_path.push_back("bones"); return model_path; } static bool has_data() { return true; } static std::vector<std::pair<size_t, double> > get_expected_values() { using std::make_pair; std::vector<std::pair<size_t, double> > expected_values; expected_values.push_back(make_pair( 0U, 0.3244)); expected_values.push_back(make_pair( 1U, 1.366)); expected_values.push_back(make_pair( 2U, 2.357)); expected_values.push_back(make_pair( 3U, 2.902)); expected_values.push_back(make_pair( 4U, 5.535)); expected_values.push_back(make_pair( 5U, 6.751)); expected_values.push_back(make_pair( 6U, 6.451)); expected_values.push_back(make_pair( 7U, 8.93)); expected_values.push_back(make_pair( 8U, 8.981)); expected_values.push_back(make_pair( 9U, 11.94)); expected_values.push_back(make_pair(10U, 11.58)); expected_values.push_back(make_pair(11U, 15.79)); expected_values.push_back(make_pair(12U, 16.96)); return expected_values; } }; INSTANTIATE_TYPED_TEST_CASE_P(Models_BugsExamples_Vol1_Bones, Model_Test_Fixture, Models_BugsExamples_Vol1_Bones); <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.2 2000/03/22 00:58:11 rahulj * Now we throw exceptions when errors occur. * Simplified code based on assumption that calling * function will allocate enough storage to store the * incoming data. * * Revision 1.1 2000/03/20 23:48:51 rahulj * Added Socket based NetAccessor. This will enable one to * use HTTP URL's for system id's. Default build options do * not use this NetAccessor. Specify the '-n socket' option * to 'runConfigure' to configure Xerces-C to use this new * feature. The code works under Solaris 2.6, Linux, AIX * and HPUX 11 with aCC. * Todo's: enable proper error handling. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <memory.h> #include <iostream.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <errno.h> #include <util/XMLNetAccessor.hpp> #include <util/NetAccessors/Socket/UnixHTTPURLInputStream.hpp> #include <util/XMLString.hpp> #include <util/XMLExceptMsgs.hpp> #include <util/Janitor.hpp> // // This define specifies the size of the buffer used to read chunks // out of the URL input stream. // #define URLISBUFMAXSIZE 8192 // // URL's, as per the standards, is essentially composed of just ASCII characters // and hence converting it to a 'char *' requires just to drop the leading zero // byte. However, the URL's have to be 'escaped', meaning that certain unsafe // and reserved characters have to be escaped to their corresponding hex values. // // The input Unicode string is assumed to be 0 terminated. // The caller is responsible to free the memory allocated to store the resultant // 'char *' string. // static char* localTranscode(const XMLCh* latinStrInUnicode) { unsigned int lent = XMLString::stringLen(latinStrInUnicode); char* retval = new char[lent + 1]; unsigned int i = 0; for (i = 0; i < lent; i++) retval[i] = (char) latinStrInUnicode[i]; // drop the leading byte. retval[lent] = 0; return retval; } UnixHTTPURLInputStream::UnixHTTPURLInputStream(const XMLURL& urlSource) : fSocket(0) , fBytesProcessed(0) { const XMLCh* uri = urlSource.getURLText(); char* uriAsCharStar = localTranscode(uri); ArrayJanitor<char> janBuf(uriAsCharStar); const XMLCh* hostName = urlSource.getHost(); char* hostNameAsCharStar = localTranscode(hostName); ArrayJanitor<char> janBuf1(hostNameAsCharStar); struct hostent* hostEntPtr = 0; struct sockaddr_in sa; char obuf[1024]; // URL's should be < 1018 bytes. if ((hostEntPtr = gethostbyname(hostNameAsCharStar)) == NULL) { unsigned long numAddress = inet_addr(hostNameAsCharStar); if (numAddress < 0) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_TargetResolution); } if ((hostEntPtr = gethostbyaddr((const char *) &numAddress, sizeof(unsigned long), AF_INET)) == NULL) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_TargetResolution); } } memcpy((void *) &sa.sin_addr, (const void *) hostEntPtr->h_addr, hostEntPtr->h_length); sa.sin_family = hostEntPtr->h_addrtype; sa.sin_port = htons(80); int s = socket(hostEntPtr->h_addrtype, SOCK_STREAM, 0); if (s < 0) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_CreateSocket); } if (connect(s, (struct sockaddr *) &sa, sizeof(sa)) < 0) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_ConnSocket); } // Now you can simply read and write from/to the socket. sprintf(obuf, "GET %s\n\n", uriAsCharStar); int lent = strlen(obuf); int aLent = 0; if ((aLent = write(s, (void *) obuf, lent)) != lent) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_WriteSocket); } fSocket = s; } UnixHTTPURLInputStream::~UnixHTTPURLInputStream() { shutdown(fSocket, 2); close(fSocket); } unsigned int UnixHTTPURLInputStream::readBytes(XMLByte* const toFill , const unsigned int maxToRead) { unsigned int retval = 0; int lent = read(fSocket, (void *) toFill, maxToRead); if (lent < 0) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_ReadSocket); } else { retval = lent; fBytesProcessed += retval; } return retval; } <commit_msg>Connect to the port specified in the URL, rather than the default one.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.3 2000/03/24 01:30:32 rahulj * Connect to the port specified in the URL, rather than the default * one. * * Revision 1.2 2000/03/22 00:58:11 rahulj * Now we throw exceptions when errors occur. * Simplified code based on assumption that calling * function will allocate enough storage to store the * incoming data. * * Revision 1.1 2000/03/20 23:48:51 rahulj * Added Socket based NetAccessor. This will enable one to * use HTTP URL's for system id's. Default build options do * not use this NetAccessor. Specify the '-n socket' option * to 'runConfigure' to configure Xerces-C to use this new * feature. The code works under Solaris 2.6, Linux, AIX * and HPUX 11 with aCC. * Todo's: enable proper error handling. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <memory.h> #include <iostream.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <errno.h> #include <util/XMLNetAccessor.hpp> #include <util/NetAccessors/Socket/UnixHTTPURLInputStream.hpp> #include <util/XMLString.hpp> #include <util/XMLExceptMsgs.hpp> #include <util/Janitor.hpp> // // This define specifies the size of the buffer used to read chunks // out of the URL input stream. // #define URLISBUFMAXSIZE 8192 // // URL's, as per the standards, is essentially composed of just ASCII characters // and hence converting it to a 'char *' requires just to drop the leading zero // byte. However, the URL's have to be 'escaped', meaning that certain unsafe // and reserved characters have to be escaped to their corresponding hex values. // // The input Unicode string is assumed to be 0 terminated. // The caller is responsible to free the memory allocated to store the resultant // 'char *' string. // static char* localTranscode(const XMLCh* latinStrInUnicode) { unsigned int lent = XMLString::stringLen(latinStrInUnicode); char* retval = new char[lent + 1]; unsigned int i = 0; for (i = 0; i < lent; i++) retval[i] = (char) latinStrInUnicode[i]; // drop the leading byte. retval[lent] = 0; return retval; } UnixHTTPURLInputStream::UnixHTTPURLInputStream(const XMLURL& urlSource) : fSocket(0) , fBytesProcessed(0) { const XMLCh* uri = urlSource.getURLText(); char* uriAsCharStar = localTranscode(uri); ArrayJanitor<char> janBuf(uriAsCharStar); const XMLCh* hostName = urlSource.getHost(); char* hostNameAsCharStar = localTranscode(hostName); ArrayJanitor<char> janBuf1(hostNameAsCharStar); unsigned short portNumber = (unsigned short) urlSource.getPortNum(); struct hostent* hostEntPtr = 0; struct sockaddr_in sa; char obuf[1024]; // URL's should be < 1018 bytes. if ((hostEntPtr = gethostbyname(hostNameAsCharStar)) == NULL) { unsigned long numAddress = inet_addr(hostNameAsCharStar); if (numAddress < 0) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_TargetResolution); } if ((hostEntPtr = gethostbyaddr((const char *) &numAddress, sizeof(unsigned long), AF_INET)) == NULL) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_TargetResolution); } } memcpy((void *) &sa.sin_addr, (const void *) hostEntPtr->h_addr, hostEntPtr->h_length); sa.sin_family = hostEntPtr->h_addrtype; sa.sin_port = htons(portNumber); int s = socket(hostEntPtr->h_addrtype, SOCK_STREAM, 0); if (s < 0) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_CreateSocket); } if (connect(s, (struct sockaddr *) &sa, sizeof(sa)) < 0) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_ConnSocket); } // Now you can simply read and write from/to the socket. sprintf(obuf, "GET %s\n\n", uriAsCharStar); int lent = strlen(obuf); int aLent = 0; if ((aLent = write(s, (void *) obuf, lent)) != lent) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_WriteSocket); } fSocket = s; } UnixHTTPURLInputStream::~UnixHTTPURLInputStream() { shutdown(fSocket, 2); close(fSocket); } unsigned int UnixHTTPURLInputStream::readBytes(XMLByte* const toFill , const unsigned int maxToRead) { unsigned int retval = 0; int lent = read(fSocket, (void *) toFill, maxToRead); if (lent < 0) { ThrowXML(NetAccessorException, XMLExcepts::NetAcc_ReadSocket); } else { retval = lent; fBytesProcessed += retval; } return retval; } <|endoftext|>
<commit_before>// // Created by Axel Naumann on 09/12/15. // //#include "cling/Interpreter/Jupyter/Kernel.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include <map> #include <string> namespace cling { namespace Jupyter { struct MIMEDataRef { const char* m_Data; const long m_Size; MIMEDataRef(const std::string& str): m_Data(str.c_str()), m_Size((long)str.length() + 1) {} MIMEDataRef(const char* str): MIMEDataRef(std::string(str)) {} MIMEDataRef(const char* data, long size): m_Data(data), m_Size(size) {} }; /// Push MIME stuff to Jupyter. To be called from user code. ///\param contentDict - dictionary of MIME type versus content. E.g. /// {{"text/html", {"<div></div>", }} void pushOutput(const std::map<std::string, MIMEDataRef> contentDict) { FILE* outpipe = popen("???", "w"); // Pipe sees (all numbers are longs, except for the first: // - num bytes in a long (sent as a single unsigned char!) // - num elements of the MIME dictionary; Jupyter selects one to display. // For each MIME dictionary element: // - MIME type as 0-terminated string // - size of MIME data buffer (including the terminating 0 for // 0-terminated strings) // - MIME data buffer // Write number of dictionary elements (and the size of that number in a // char) unsigned char sizeLong = sizeof(long); fwrite(&sizeLong, 1, 1, outpipe); long dictSize = contentDict.size(); fwrite(&dictSize, sizeof(long), 1, outpipe); for (auto iContent: contentDict) { const std::string& mimeType = iContent.first; fwrite(mimeType.c_str(), mimeType.size() + 1, 1, outpipe); const MIMEDataRef& mimeData = iContent.second; fwrite(&mimeData.m_Size, sizeof(long), 1, outpipe); fwrite(mimeData.m_Data, mimeData.m_Size, 1, outpipe); } pclose(outpipe); } } // namespace Jupyter } // namespace cling extern "C" { ///\{ ///\name Cling4CTypes /// The Python compatible view of cling /// The Interpreter object cast to void* using TheInterpreter = void ; /// Create an interpreter object. TheInterpreter* cling_create(int argc, const char *argv[], const char* llvmdir) { auto interp = new cling::Interpreter(argc, argv, llvmdir); return interp; } /// Destroy the interpreter. void cling_destroy(TheInterpreter *interpVP) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; delete interp; } /// Evaluate a string of code. Returns 0 on success. int cling_eval(TheInterpreter *interpVP, const char *code) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; //cling::Value V; cling::Interpreter::CompilationResult Res = interp->process(code /*, V*/); if (Res != cling::Interpreter::kSuccess) return 1; cling::Jupyter::pushOutput({{"text/html", "You just executed C++ code!"}}); return 0; } ///\} } // extern "C" <commit_msg>Code completion interfaces (though no real implementation yet).<commit_after>// // Created by Axel Naumann on 09/12/15. // //#include "cling/Interpreter/Jupyter/Kernel.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Value.h" #include <map> #include <string> namespace cling { namespace Jupyter { struct MIMEDataRef { const char* m_Data; const long m_Size; MIMEDataRef(const std::string& str): m_Data(str.c_str()), m_Size((long)str.length() + 1) {} MIMEDataRef(const char* str): MIMEDataRef(std::string(str)) {} MIMEDataRef(const char* data, long size): m_Data(data), m_Size(size) {} }; /// Push MIME stuff to Jupyter. To be called from user code. ///\param contentDict - dictionary of MIME type versus content. E.g. /// {{"text/html", {"<div></div>", }} void pushOutput(const std::map<std::string, MIMEDataRef> contentDict) { FILE* outpipe = popen("???", "w"); // Pipe sees (all numbers are longs, except for the first: // - num bytes in a long (sent as a single unsigned char!) // - num elements of the MIME dictionary; Jupyter selects one to display. // For each MIME dictionary element: // - MIME type as 0-terminated string // - size of MIME data buffer (including the terminating 0 for // 0-terminated strings) // - MIME data buffer // Write number of dictionary elements (and the size of that number in a // char) unsigned char sizeLong = sizeof(long); fwrite(&sizeLong, 1, 1, outpipe); long dictSize = contentDict.size(); fwrite(&dictSize, sizeof(long), 1, outpipe); for (auto iContent: contentDict) { const std::string& mimeType = iContent.first; fwrite(mimeType.c_str(), mimeType.size() + 1, 1, outpipe); const MIMEDataRef& mimeData = iContent.second; fwrite(&mimeData.m_Size, sizeof(long), 1, outpipe); fwrite(mimeData.m_Data, mimeData.m_Size, 1, outpipe); } pclose(outpipe); } } // namespace Jupyter } // namespace cling extern "C" { ///\{ ///\name Cling4CTypes /// The Python compatible view of cling /// The Interpreter object cast to void* using TheInterpreter = void ; /// Create an interpreter object. TheInterpreter* cling_create(int argc, const char *argv[], const char* llvmdir) { auto interp = new cling::Interpreter(argc, argv, llvmdir); return interp; } /// Destroy the interpreter. void cling_destroy(TheInterpreter *interpVP) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; delete interp; } /// Evaluate a string of code. Returns 0 on success. int cling_eval(TheInterpreter *interpVP, const char *code) { cling::Interpreter *interp = (cling::Interpreter *) interpVP; //cling::Value V; cling::Interpreter::CompilationResult Res = interp->process(code /*, V*/); if (Res != cling::Interpreter::kSuccess) return 1; cling::Jupyter::pushOutput({{"text/html", "You just executed C++ code!"}}); return 0; } /// Code completion interfaces. /// Start completion of code. Returns a handle to be passed to /// cling_complete_next() to iterate over the completion options. Returns nulptr /// if no completions are known. void* cling_complete_start(const char* code) { return new int(42); } /// Grab the next completion of some code. Returns nullptr if none is left. const char* cling_complete_next(void* completionHandle) { int* counter = *(int*) completionHandle; if (++(*counter) > 43) { delete counter; return nullptr; } return "COMPLETE!"; } ///\} } // extern "C" <|endoftext|>
<commit_before>#include <iostream> #include "../src/aggregator/compact_1_2.h" void compact_1_2_regex_test() { std::string db_name = "/tmp/lv_db"; for (const auto & name:{db_name, db_name + "_a", db_name + "_b"}) { if (LeviDB::IOEnv::fileExists(name)) { for (const std::string & child:LeviDB::IOEnv::getChildren(name)) { LeviDB::IOEnv::deleteFile((name + '/') += child); } LeviDB::IOEnv::deleteDir(name); } } typedef LeviDB::Regex::R R; auto r_obj = std::make_shared<R>(R("5") << R("0", "9", 0, INT_MAX)); LeviDB::SeqGenerator seq_gen; LeviDB::Options options{}; options.create_if_missing = true; auto db = std::make_unique<LeviDB::DBSingle>(db_name, options, &seq_gen); for (int i = 0; i < 100; ++i) { db->put(LeviDB::WriteOptions{}, std::to_string(i), std::to_string(i)); } LeviDB::Compacting1To2DB compact_db(std::move(db), &seq_gen); assert(compact_db.immut_product_a()->canRelease()); assert(compact_db.immut_product_b()->canRelease()); { auto snapshot = compact_db.makeSnapshot(); std::thread task([it = compact_db.makeRegexIterator(r_obj, std::make_unique<LeviDB::Snapshot>( snapshot->immut_seq_num()))]() noexcept { try { while (it->valid()) { auto item = it->item(); assert(item.first == item.second && item.second[0] == '5'); it->next(); } } catch (const LeviDB::Exception & e) { std::cout << e.toString() << std::endl; } }); task.detach(); for (int i = 40; i < 60; ++i) { compact_db.put(LeviDB::WriteOptions{}, std::to_string(i), "X"); } { auto it = compact_db.makeRegexReversedIterator(r_obj, std::make_unique<LeviDB::Snapshot>( snapshot->immut_seq_num())); while (it->valid()) { auto item = it->item(); assert(item.first == item.second && item.second[0] == '5'); it->next(); } } { auto it = compact_db.makeRegexIterator(r_obj, compact_db.makeSnapshot()); while (it->valid()) { auto item = it->item(); if (item.first.size() == 1) { assert(item.second == "5"); } else { assert(item.second == "X"); } it->next(); } } std::this_thread::sleep_for(std::chrono::seconds(1)); std::thread task_2([it = compact_db.makeRegexIterator(r_obj, std::make_unique<LeviDB::Snapshot>( snapshot->immut_seq_num()))]() noexcept { try { while (it->valid()) { auto item = it->item(); assert(item.first == item.second && item.second[0] == '5'); it->next(); } } catch (const LeviDB::Exception & e) { std::cout << e.toString() << std::endl; } }); task_2.detach(); } while (!compact_db.canRelease()) { compact_db.tryApplyPending(); std::this_thread::sleep_for(std::chrono::seconds(1)); } { auto it = compact_db.makeRegexIterator(r_obj, compact_db.makeSnapshot()); while (it->valid()) { auto item = it->item(); if (item.first.size() == 1) { assert(item.second == "5"); } else { assert(item.second == "X"); } it->next(); } } for (int i = 40; i < 60; ++i) { compact_db.put(LeviDB::WriteOptions{}, std::to_string(i), std::to_string(i)); } compact_db.tryApplyPending(); assert(compact_db.canRelease()); std::cout << __FUNCTION__ << std::endl; }<commit_msg>add more compact 1 to 2 iter tests<commit_after>#include <iostream> #include "../src/aggregator/compact_1_2.h" void compact_1_2_regex_test() { std::string db_name = "/tmp/lv_db"; for (const auto & name:{db_name, db_name + "_a", db_name + "_b"}) { if (LeviDB::IOEnv::fileExists(name)) { for (const std::string & child:LeviDB::IOEnv::getChildren(name)) { LeviDB::IOEnv::deleteFile((name + '/') += child); } LeviDB::IOEnv::deleteDir(name); } } typedef LeviDB::Regex::R R; auto r_obj = std::make_shared<R>(R("5") << R("0", "9", 0, INT_MAX)); LeviDB::SeqGenerator seq_gen; LeviDB::Options options{}; options.create_if_missing = true; auto db = std::make_unique<LeviDB::DBSingle>(db_name, options, &seq_gen); for (int i = 0; i < 100; ++i) { db->put(LeviDB::WriteOptions{}, std::to_string(i), std::to_string(i)); } LeviDB::Compacting1To2DB compact_db(std::move(db), &seq_gen); assert(compact_db.immut_product_a()->canRelease()); assert(compact_db.immut_product_b()->canRelease()); { auto snapshot = compact_db.makeSnapshot(); std::thread task([it = compact_db.makeRegexIterator(r_obj, std::make_unique<LeviDB::Snapshot>( snapshot->immut_seq_num()))]() noexcept { try { while (it->valid()) { auto item = it->item(); assert(item.first == item.second && item.second[0] == '5'); it->next(); } } catch (const LeviDB::Exception & e) { std::cout << e.toString() << std::endl; } }); task.detach(); for (int i = 40; i < 60; ++i) { compact_db.put(LeviDB::WriteOptions{}, std::to_string(i), "X"); } { auto it = compact_db.makeRegexIterator(r_obj, compact_db.makeSnapshot()); while (it->valid()) { auto item = it->item(); if (item.first.size() == 1) { assert(item.second == "5"); } else { assert(item.second == "X"); } it->next(); } } { auto it = compact_db.makeRegexReversedIterator(r_obj, std::make_unique<LeviDB::Snapshot>( snapshot->immut_seq_num())); while (it->valid()) { auto item = it->item(); assert(item.first == item.second && item.second[0] == '5'); it->next(); } } std::this_thread::sleep_for(std::chrono::seconds(1)); std::thread task_2([it = compact_db.makeRegexIterator(r_obj, std::make_unique<LeviDB::Snapshot>( snapshot->immut_seq_num()))]() noexcept { try { while (it->valid()) { auto item = it->item(); assert(item.first == item.second && item.second[0] == '5'); it->next(); } } catch (const LeviDB::Exception & e) { std::cout << e.toString() << std::endl; } }); task_2.detach(); } while (!compact_db.canRelease()) { compact_db.tryApplyPending(); std::this_thread::sleep_for(std::chrono::seconds(1)); } { auto it = compact_db.makeRegexIterator(r_obj, compact_db.makeSnapshot()); while (it->valid()) { auto item = it->item(); if (item.first.size() == 1) { assert(item.second == "5"); } else { assert(item.second == "X"); } it->next(); } } for (int i = 40; i < 60; ++i) { compact_db.put(LeviDB::WriteOptions{}, std::to_string(i), std::to_string(i)); } compact_db.tryApplyPending(); assert(compact_db.canRelease()); std::cout << __FUNCTION__ << std::endl; }<|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 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. #include <sys/socket.h> #include <errno.h> #include <fd_map.hpp> #include <tcp_fd.hpp> #include <udp_fd.hpp> int socket(int domain, int type, int protocol) { // disallow strange domains, like ALG if (domain < 0 || domain > AF_INET6) { errno = EAFNOSUPPORT; return -1; } // disallow RAW etc if (type < 0 || type > SOCK_DGRAM) { errno = EINVAL; return -1; } // we are purposefully ignoring the protocol argument if (protocol < 0) { errno = EPROTONOSUPPORT; return -1; } return [](const int type)->int{ switch(type) { case SOCK_STREAM: return FD_map::_open<TCP_FD>().get_id(); case SOCK_DGRAM: return FD_map::_open<UDP_FD>().get_id(); default: return -1; } }(type); } int connect(int socket, const struct sockaddr *address, socklen_t len) { try { auto& fd = FD_map::_get(socket); return fd.connect(address, len); } catch (const FD_not_found&) { errno = EBADF; return -1; } } ssize_t send(int socket, const void *message, size_t len, int fmt) { try { auto& fd = FD_map::_get(socket); return fd.send(message, len, fmt); } catch (const FD_not_found&) { errno = EBADF; return -1; } } int listen(int socket, int backlog) { try { auto& fd = FD_map::_get(socket); return fd.listen(backlog); } catch (const FD_not_found&) { errno = EBADF; return -1; } } int bind(int socket, const struct sockaddr* address, socklen_t len) { try { auto& fd = FD_map::_get(socket); return fd.bind(address, len); } catch (const FD_not_found&) { errno = EBADF; return -1; } } <commit_msg>posix: Add recv global function<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 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. #include <sys/socket.h> #include <errno.h> #include <fd_map.hpp> #include <tcp_fd.hpp> #include <udp_fd.hpp> int socket(int domain, int type, int protocol) { // disallow strange domains, like ALG if (domain < 0 || domain > AF_INET6) { errno = EAFNOSUPPORT; return -1; } // disallow RAW etc if (type < 0 || type > SOCK_DGRAM) { errno = EINVAL; return -1; } // we are purposefully ignoring the protocol argument if (protocol < 0) { errno = EPROTONOSUPPORT; return -1; } return [](const int type)->int{ switch(type) { case SOCK_STREAM: return FD_map::_open<TCP_FD>().get_id(); case SOCK_DGRAM: return FD_map::_open<UDP_FD>().get_id(); default: return -1; } }(type); } int connect(int socket, const struct sockaddr *address, socklen_t len) { try { auto& fd = FD_map::_get(socket); return fd.connect(address, len); } catch (const FD_not_found&) { errno = EBADF; return -1; } } ssize_t send(int socket, const void *message, size_t len, int fmt) { try { auto& fd = FD_map::_get(socket); return fd.send(message, len, fmt); } catch (const FD_not_found&) { errno = EBADF; return -1; } } ssize_t recv(int socket, void *buffer, size_t length, int flags) { try { auto& fd = FD_map::_get(socket); return fd.recv(buffer, length, flags); } catch (const FD_not_found&) { errno = EBADF; return -1; } } int listen(int socket, int backlog) { try { auto& fd = FD_map::_get(socket); return fd.listen(backlog); } catch (const FD_not_found&) { errno = EBADF; return -1; } } int bind(int socket, const struct sockaddr* address, socklen_t len) { try { auto& fd = FD_map::_get(socket); return fd.bind(address, len); } catch (const FD_not_found&) { errno = EBADF; return -1; } } <|endoftext|>
<commit_before>#include "search.hpp" #include "idastar.hpp" #include "astar.hpp" #include "astar-dump.hpp" #include "wastar.hpp" #include "greedy.hpp" #include "bugsy.hpp" #include "bugsy-slim.hpp" #include "arastar.hpp" #include "lsslrtastar2.hpp" #include "fhatlrtastar.hpp" #include "dtastar-dump.hpp" #include "dtastar.hpp" #include "monstar-dump.hpp" /* #include "rtastar.hpp" #include "multilrtastar.hpp" #include "lsslrtastar.hpp" #include "flrtastar.hpp" #include "flrtastar2.hpp" #include "cautiouslrtastar.hpp" #include "frankenlrtastar.hpp" #include "wlrtastar.hpp" #include "dflrtastar.hpp" #include "mrastar.hpp" #include "greedylrtastar.hpp" #include "uclrtastar.hpp" */ #include <cstddef> #include <cstdio> // Functions for conveniently defining a new main // function for a domain. void dfheader(FILE*); void dffooter(FILE*); void dfpair(FILE *, const char *, const char *, ...); void dfprocstatus(FILE*); void fatal(const char*, ...); template<class D> SearchAlgorithm<D> *getsearch(int argc, const char *argv[]); template<class D> Result<D> search(D &d, int argc, const char *argv[]) { return searchGet(getsearch, d, argc, argv); } template<class D> Result<D> searchGet(SearchAlgorithm<D>*(*get)(int, const char *[]), D &d, int argc, const char *argv[]) { SearchAlgorithm<D> *srch = get(argc, argv); if (!srch && argc > 1) fatal("Unknow search algorithm: %s", argv[1]); if (!srch) fatal("Must specify a search algorithm"); typename D::State s0 = d.initialstate(); dfpair(stdout, "initial heuristic", "%f", (double) d.h(s0)); dfpair(stdout, "initial distance", "%f", (double) d.d(s0)); dfpair(stdout, "algorithm", argv[1]); try { srch->search(d, s0); } catch (std::bad_alloc&) { dfpair(stdout, "out of memory", "%s", "true"); srch->res.path.clear(); srch->res.ops.clear(); srch->finish(); } if (srch->res.path.size() > 0) { dfpair(stdout, "final sol cost", "%f", (double) d.pathcost(srch->res.path, srch->res.ops)); } else { dfpair(stdout, "final sol cost", "%f", -1.0); } srch->output(stdout); Result<D> res = srch->res; delete srch; return res; } template<class D> SearchAlgorithm<D> *getsearch(int argc, const char *argv[]) { if (argc < 2) fatal("No algorithm specified"); if (strcmp(argv[1], "idastar") == 0) return new Idastar<D>(argc, argv); else if (strcmp(argv[1], "astar") == 0) return new Astar<D>(argc, argv); else if (strcmp(argv[1], "astar-dump") == 0) return new Astar_dump<D>(argc, argv); else if (strcmp(argv[1], "wastar") == 0) return new Wastar<D>(argc, argv); else if (strcmp(argv[1], "greedy") == 0) return new Greedy<D>(argc, argv); else if (strcmp(argv[1], "speedy") == 0) return new Greedy<D, true>(argc, argv); else if (strcmp(argv[1], "bugsy") == 0) return new Bugsy<D>(argc, argv); else if (strcmp(argv[1], "bugsy-slim") == 0) return new Bugsy_slim<D>(argc, argv); else if (strcmp(argv[1], "arastar") == 0) return new Arastar<D>(argc, argv); else if (strcmp(argv[1], "arastarmon") == 0) return new ArastarMon<D>(argc, argv); else if (strcmp(argv[1], "dtastar-dump") == 0) return new Dtastar_dump<D>(argc, argv); else if (strcmp(argv[1], "lsslrtastar2") == 0) return new Lsslrtastar2<D>(argc, argv); else if (strcmp(argv[1], "fhatlrtastar") == 0) return new Fhatlrtastar<D>(argc, argv); else if (strcmp(argv[1], "dtastar") == 0) return new Dtastar<D>(argc, argv); else if (strcmp(argv[1], "monstar-dump") == 0) return new Monstar_dump<D>(argc, argv); /* else if (strcmp(argv[1], "mrastar") == 0) return new Mrastar<D>(argc, argv); else if (strcmp(argv[1], "dflrtastar") == 0) return new Dflrtastar<D>(argc, argv); else if (strcmp(argv[1], "greedylrtastar") == 0) return new Greedylrtastar<D>(argc, argv); else if (strcmp(argv[1], "uclrtastar") == 0) return new Uclrtastar<D>(argc, argv); else if (strcmp(argv[1], "multilrtastar") == 0) return new Multilrtastar<D>(argc, argv); else if (strcmp(argv[1], "cautiouslrtastar") == 0) return new Cautiouslrtastar<D>(argc, argv); else if (strcmp(argv[1], "frankenlrtastar") == 0) return new Frankenlrtastar<D>(argc, argv); else if (strcmp(argv[1], "wlrtastar") == 0) return new Wlrtastar<D>(argc, argv); else if (strcmp(argv[1], "rtastar") == 0) return new Rtastar<D>(argc, argv); else if (strcmp(argv[1], "lsslrtastar") == 0) return new Lsslrtastar<D>(argc, argv); else if (strcmp(argv[1], "flrtastar") == 0) return new Flrtastar<D>(argc, argv); else if (strcmp(argv[1], "flrtastar2") == 0) return new Flrtastar2<D>(argc, argv); */ fatal("Unknown algorithm: %s", argv[1]); return NULL; // Unreachable } <commit_msg>search: reenable RTA*.<commit_after>#include "search.hpp" #include "idastar.hpp" #include "astar.hpp" #include "astar-dump.hpp" #include "wastar.hpp" #include "greedy.hpp" #include "bugsy.hpp" #include "bugsy-slim.hpp" #include "arastar.hpp" #include "lsslrtastar2.hpp" #include "fhatlrtastar.hpp" #include "dtastar-dump.hpp" #include "dtastar.hpp" #include "monstar-dump.hpp" #include "rtastar.hpp" /* #include "multilrtastar.hpp" #include "lsslrtastar.hpp" #include "flrtastar.hpp" #include "flrtastar2.hpp" #include "cautiouslrtastar.hpp" #include "frankenlrtastar.hpp" #include "wlrtastar.hpp" #include "dflrtastar.hpp" #include "mrastar.hpp" #include "greedylrtastar.hpp" #include "uclrtastar.hpp" */ #include <cstddef> #include <cstdio> // Functions for conveniently defining a new main // function for a domain. void dfheader(FILE*); void dffooter(FILE*); void dfpair(FILE *, const char *, const char *, ...); void dfprocstatus(FILE*); void fatal(const char*, ...); template<class D> SearchAlgorithm<D> *getsearch(int argc, const char *argv[]); template<class D> Result<D> search(D &d, int argc, const char *argv[]) { return searchGet(getsearch, d, argc, argv); } template<class D> Result<D> searchGet(SearchAlgorithm<D>*(*get)(int, const char *[]), D &d, int argc, const char *argv[]) { SearchAlgorithm<D> *srch = get(argc, argv); if (!srch && argc > 1) fatal("Unknow search algorithm: %s", argv[1]); if (!srch) fatal("Must specify a search algorithm"); typename D::State s0 = d.initialstate(); dfpair(stdout, "initial heuristic", "%f", (double) d.h(s0)); dfpair(stdout, "initial distance", "%f", (double) d.d(s0)); dfpair(stdout, "algorithm", argv[1]); try { srch->search(d, s0); } catch (std::bad_alloc&) { dfpair(stdout, "out of memory", "%s", "true"); srch->res.path.clear(); srch->res.ops.clear(); srch->finish(); } if (srch->res.path.size() > 0) { dfpair(stdout, "final sol cost", "%f", (double) d.pathcost(srch->res.path, srch->res.ops)); } else { dfpair(stdout, "final sol cost", "%f", -1.0); } srch->output(stdout); Result<D> res = srch->res; delete srch; return res; } template<class D> SearchAlgorithm<D> *getsearch(int argc, const char *argv[]) { if (argc < 2) fatal("No algorithm specified"); if (strcmp(argv[1], "idastar") == 0) return new Idastar<D>(argc, argv); else if (strcmp(argv[1], "astar") == 0) return new Astar<D>(argc, argv); else if (strcmp(argv[1], "astar-dump") == 0) return new Astar_dump<D>(argc, argv); else if (strcmp(argv[1], "wastar") == 0) return new Wastar<D>(argc, argv); else if (strcmp(argv[1], "greedy") == 0) return new Greedy<D>(argc, argv); else if (strcmp(argv[1], "speedy") == 0) return new Greedy<D, true>(argc, argv); else if (strcmp(argv[1], "bugsy") == 0) return new Bugsy<D>(argc, argv); else if (strcmp(argv[1], "bugsy-slim") == 0) return new Bugsy_slim<D>(argc, argv); else if (strcmp(argv[1], "arastar") == 0) return new Arastar<D>(argc, argv); else if (strcmp(argv[1], "arastarmon") == 0) return new ArastarMon<D>(argc, argv); else if (strcmp(argv[1], "dtastar-dump") == 0) return new Dtastar_dump<D>(argc, argv); else if (strcmp(argv[1], "lsslrtastar2") == 0) return new Lsslrtastar2<D>(argc, argv); else if (strcmp(argv[1], "fhatlrtastar") == 0) return new Fhatlrtastar<D>(argc, argv); else if (strcmp(argv[1], "dtastar") == 0) return new Dtastar<D>(argc, argv); else if (strcmp(argv[1], "monstar-dump") == 0) return new Monstar_dump<D>(argc, argv); else if (strcmp(argv[1], "rtastar") == 0) return new Rtastar<D>(argc, argv); /* else if (strcmp(argv[1], "mrastar") == 0) return new Mrastar<D>(argc, argv); else if (strcmp(argv[1], "dflrtastar") == 0) return new Dflrtastar<D>(argc, argv); else if (strcmp(argv[1], "greedylrtastar") == 0) return new Greedylrtastar<D>(argc, argv); else if (strcmp(argv[1], "uclrtastar") == 0) return new Uclrtastar<D>(argc, argv); else if (strcmp(argv[1], "multilrtastar") == 0) return new Multilrtastar<D>(argc, argv); else if (strcmp(argv[1], "cautiouslrtastar") == 0) return new Cautiouslrtastar<D>(argc, argv); else if (strcmp(argv[1], "frankenlrtastar") == 0) return new Frankenlrtastar<D>(argc, argv); else if (strcmp(argv[1], "wlrtastar") == 0) return new Wlrtastar<D>(argc, argv); else if (strcmp(argv[1], "lsslrtastar") == 0) return new Lsslrtastar<D>(argc, argv); else if (strcmp(argv[1], "flrtastar") == 0) return new Flrtastar<D>(argc, argv); else if (strcmp(argv[1], "flrtastar2") == 0) return new Flrtastar2<D>(argc, argv); */ fatal("Unknown algorithm: %s", argv[1]); return NULL; // Unreachable } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief Aql, query parser /// /// @file /// /// DISCLAIMER /// /// Copyright 2014 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "Aql/Parser.h" #include "Aql/AstNode.h" #include "Aql/QueryResult.h" using namespace triagens::aql; // ----------------------------------------------------------------------------- // --SECTION-- constructors / destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief create the parser //////////////////////////////////////////////////////////////////////////////// Parser::Parser (Query* query) : _query(query), _ast(nullptr), _scanner(nullptr), _buffer(query->queryString()), _remainingLength(query->queryLength()), _offset(0), _marker(nullptr), _stack() { _ast = new Ast(query, this); _stack.reserve(16); } //////////////////////////////////////////////////////////////////////////////// /// @brief destroy the parser //////////////////////////////////////////////////////////////////////////////// Parser::~Parser () { if (_ast != nullptr) { delete _ast; } } // ----------------------------------------------------------------------------- // --SECTION-- public functions // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief set data for write queries //////////////////////////////////////////////////////////////////////////////// bool Parser::configureWriteQuery (QueryType type, AstNode const* collectionNode, AstNode* optionNode) { TRI_ASSERT(type != AQL_QUERY_READ); // check if we currently are in a subquery if (_ast->isInSubQuery()) { // data modification not allowed in sub-queries _query->registerError(TRI_ERROR_QUERY_MODIFY_IN_SUBQUERY); return false; } // check current query type auto oldType = _query->type(); if (oldType != AQL_QUERY_READ) { // already a data-modification query, cannot have two data-modification operations in one query _query->registerError(TRI_ERROR_QUERY_MULTI_MODIFY); return false; } // now track which collection is going to be modified _ast->setWriteCollection(collectionNode); if (optionNode != nullptr && ! optionNode->isConstant()) { _query->registerError(TRI_ERROR_QUERY_COMPILE_TIME_OPTIONS); } // register type _query->type(type); return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief parse the query //////////////////////////////////////////////////////////////////////////////// QueryResult Parser::parse () { // start main scope auto scopes = _ast->scopes(); scopes->start(AQL_SCOPE_MAIN); Aqllex_init(&_scanner); Aqlset_extra(this, _scanner); try { // parse the query string if (Aqlparse(this)) { // lexing/parsing failed THROW_ARANGO_EXCEPTION(TRI_ERROR_QUERY_PARSE); } Aqllex_destroy(_scanner); } catch (...) { Aqllex_destroy(_scanner); throw; } // end main scope scopes->endCurrent(); TRI_ASSERT(scopes->numActive() == 0); QueryResult result; result.collectionNames = _query->collectionNames(); result.bindParameters = _ast->bindParameters(); result.json = _ast->toJson(TRI_UNKNOWN_MEM_ZONE, false); return result; } //////////////////////////////////////////////////////////////////////////////// /// @brief register a parse error, position is specified as line / column //////////////////////////////////////////////////////////////////////////////// void Parser::registerParseError (int errorCode, char const* format, char const* data, int line, int column) { char buffer[512]; snprintf(buffer, sizeof(buffer), format, data); return registerParseError(errorCode, buffer, line, column); } //////////////////////////////////////////////////////////////////////////////// /// @brief register a parse error, position is specified as line / column //////////////////////////////////////////////////////////////////////////////// void Parser::registerParseError (int errorCode, char const* data, int line, int column) { TRI_ASSERT(errorCode != TRI_ERROR_NO_ERROR); TRI_ASSERT(data != nullptr); // extract the query string part where the error happened std::string const region(_query->extractRegion(line, column)); // note: line numbers reported by bison/flex start at 1, columns start at 0 char buffer[512]; snprintf(buffer, sizeof(buffer), "%s near '%s' at position %d:%d", data, region.c_str(), line, column + 1); registerError(errorCode, buffer); } //////////////////////////////////////////////////////////////////////////////// /// @brief register a non-parse error //////////////////////////////////////////////////////////////////////////////// void Parser::registerError (int errorCode, char const* data) { _query->registerError(errorCode, data); } //////////////////////////////////////////////////////////////////////////////// /// @brief push an AstNode into the list element on top of the stack //////////////////////////////////////////////////////////////////////////////// void Parser::pushList (AstNode* node) { auto list = static_cast<AstNode*>(peekStack()); TRI_ASSERT(list->type == NODE_TYPE_LIST); list->addMember(node); } //////////////////////////////////////////////////////////////////////////////// /// @brief push an AstNode into the array element on top of the stack //////////////////////////////////////////////////////////////////////////////// void Parser::pushArray (char const* attributeName, AstNode* node) { auto array = static_cast<AstNode*>(peekStack()); TRI_ASSERT(array->type == NODE_TYPE_ARRAY); auto element = _ast->createNodeArrayElement(attributeName, node); array->addMember(element); } //////////////////////////////////////////////////////////////////////////////// /// @brief push a temporary value on the parser's stack //////////////////////////////////////////////////////////////////////////////// void Parser::pushStack (void* value) { _stack.push_back(value); } //////////////////////////////////////////////////////////////////////////////// /// @brief pop a temporary value from the parser's stack //////////////////////////////////////////////////////////////////////////////// void* Parser::popStack () { TRI_ASSERT(! _stack.empty()); void* result = _stack.back(); _stack.pop_back(); return result; } //////////////////////////////////////////////////////////////////////////////// /// @brief peek at a temporary value from the parser's stack //////////////////////////////////////////////////////////////////////////////// void* Parser::peekStack () { TRI_ASSERT(! _stack.empty()); return _stack.back(); } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <commit_msg>Parser: when throwing parse exceptions add the query and a pointer to the actual indicated error to the message.<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief Aql, query parser /// /// @file /// /// DISCLAIMER /// /// Copyright 2014 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "Aql/Parser.h" #include "Aql/AstNode.h" #include "Aql/QueryResult.h" using namespace triagens::aql; // ----------------------------------------------------------------------------- // --SECTION-- constructors / destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief create the parser //////////////////////////////////////////////////////////////////////////////// Parser::Parser (Query* query) : _query(query), _ast(nullptr), _scanner(nullptr), _buffer(query->queryString()), _remainingLength(query->queryLength()), _offset(0), _marker(nullptr), _stack() { _ast = new Ast(query, this); _stack.reserve(16); } //////////////////////////////////////////////////////////////////////////////// /// @brief destroy the parser //////////////////////////////////////////////////////////////////////////////// Parser::~Parser () { if (_ast != nullptr) { delete _ast; } } // ----------------------------------------------------------------------------- // --SECTION-- public functions // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief set data for write queries //////////////////////////////////////////////////////////////////////////////// bool Parser::configureWriteQuery (QueryType type, AstNode const* collectionNode, AstNode* optionNode) { TRI_ASSERT(type != AQL_QUERY_READ); // check if we currently are in a subquery if (_ast->isInSubQuery()) { // data modification not allowed in sub-queries _query->registerError(TRI_ERROR_QUERY_MODIFY_IN_SUBQUERY); return false; } // check current query type auto oldType = _query->type(); if (oldType != AQL_QUERY_READ) { // already a data-modification query, cannot have two data-modification operations in one query _query->registerError(TRI_ERROR_QUERY_MULTI_MODIFY); return false; } // now track which collection is going to be modified _ast->setWriteCollection(collectionNode); if (optionNode != nullptr && ! optionNode->isConstant()) { _query->registerError(TRI_ERROR_QUERY_COMPILE_TIME_OPTIONS); } // register type _query->type(type); return true; } //////////////////////////////////////////////////////////////////////////////// /// @brief parse the query //////////////////////////////////////////////////////////////////////////////// QueryResult Parser::parse () { // start main scope auto scopes = _ast->scopes(); scopes->start(AQL_SCOPE_MAIN); Aqllex_init(&_scanner); Aqlset_extra(this, _scanner); try { // parse the query string if (Aqlparse(this)) { // lexing/parsing failed THROW_ARANGO_EXCEPTION(TRI_ERROR_QUERY_PARSE); } Aqllex_destroy(_scanner); } catch (...) { Aqllex_destroy(_scanner); throw; } // end main scope scopes->endCurrent(); TRI_ASSERT(scopes->numActive() == 0); QueryResult result; result.collectionNames = _query->collectionNames(); result.bindParameters = _ast->bindParameters(); result.json = _ast->toJson(TRI_UNKNOWN_MEM_ZONE, false); return result; } //////////////////////////////////////////////////////////////////////////////// /// @brief register a parse error, position is specified as line / column //////////////////////////////////////////////////////////////////////////////// void Parser::registerParseError (int errorCode, char const* format, char const* data, int line, int column) { char buffer[512]; snprintf(buffer, sizeof(buffer), format, data); return registerParseError(errorCode, buffer, line, column); } //////////////////////////////////////////////////////////////////////////////// /// @brief register a parse error, position is specified as line / column //////////////////////////////////////////////////////////////////////////////// void Parser::registerParseError (int errorCode, char const* data, int line, int column) { TRI_ASSERT(errorCode != TRI_ERROR_NO_ERROR); TRI_ASSERT(data != nullptr); // extract the query string part where the error happened std::string const region(_query->extractRegion(line, column)); // create a neat pointer to the location of the error. auto arrowpointer = (char*) malloc (sizeof(char) * (column + 10) ); size_t i; for (i = 0; i < (size_t) column; i++) { arrowpointer[i] = ' '; } if (i > 0) { i --; arrowpointer[i++] = '^'; } arrowpointer[i++] = '^'; arrowpointer[i++] = '^'; arrowpointer[i++] = '\0'; // note: line numbers reported by bison/flex start at 1, columns start at 0 char buffer[512]; snprintf(buffer, sizeof(buffer), "%s near '%s' at position %d:%d:\n%s\n%s\n", data, region.c_str(), line, column + 1, _query->queryString(), arrowpointer); free(arrowpointer); registerError(errorCode, buffer); } //////////////////////////////////////////////////////////////////////////////// /// @brief register a non-parse error //////////////////////////////////////////////////////////////////////////////// void Parser::registerError (int errorCode, char const* data) { _query->registerError(errorCode, data); } //////////////////////////////////////////////////////////////////////////////// /// @brief push an AstNode into the list element on top of the stack //////////////////////////////////////////////////////////////////////////////// void Parser::pushList (AstNode* node) { auto list = static_cast<AstNode*>(peekStack()); TRI_ASSERT(list->type == NODE_TYPE_LIST); list->addMember(node); } //////////////////////////////////////////////////////////////////////////////// /// @brief push an AstNode into the array element on top of the stack //////////////////////////////////////////////////////////////////////////////// void Parser::pushArray (char const* attributeName, AstNode* node) { auto array = static_cast<AstNode*>(peekStack()); TRI_ASSERT(array->type == NODE_TYPE_ARRAY); auto element = _ast->createNodeArrayElement(attributeName, node); array->addMember(element); } //////////////////////////////////////////////////////////////////////////////// /// @brief push a temporary value on the parser's stack //////////////////////////////////////////////////////////////////////////////// void Parser::pushStack (void* value) { _stack.push_back(value); } //////////////////////////////////////////////////////////////////////////////// /// @brief pop a temporary value from the parser's stack //////////////////////////////////////////////////////////////////////////////// void* Parser::popStack () { TRI_ASSERT(! _stack.empty()); void* result = _stack.back(); _stack.pop_back(); return result; } //////////////////////////////////////////////////////////////////////////////// /// @brief peek at a temporary value from the parser's stack //////////////////////////////////////////////////////////////////////////////// void* Parser::peekStack () { TRI_ASSERT(! _stack.empty()); return _stack.back(); } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <|endoftext|>
<commit_before><commit_msg>ppl: fix missing _<commit_after><|endoftext|>
<commit_before>/// @file tinycc.cc /// This example demonstrates loading, running and scripting a very simple NaCl /// module. To load the NaCl module, the browser first looks for the /// CreateModule() factory method (at the end of this file). It calls /// CreateModule() once to load the module code from your .nexe. After the /// .nexe code is loaded, CreateModule() is not called again. /// /// Once the .nexe code is loaded, the browser than calls the CreateInstance() /// method on the object returned by CreateModule(). It calls CreateInstance() /// each time it encounters an <embed> tag that references your NaCl module. /// /// The browser can talk to your NaCl module via the postMessage() Javascript /// function. When you call postMessage() on your NaCl module from the browser, /// this becomes a call to the HandleMessage() method of your pp::Instance /// subclass. You can send messages back to the browser by calling the /// PostMessage() method on your pp::Instance. Note that these two methods /// (postMessage() in Javascript and PostMessage() in C++) are asynchronous. /// This means they return immediately - there is no waiting for the message /// to be handled. This has implications in your program design, particularly /// when mutating property values that are exposed to both the browser and the /// NaCl module. #include <dirent.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <memory> #include <string> #include <vector> #include <ppapi/cpp/instance.h> #include <ppapi/cpp/module.h> #include <ppapi/cpp/var.h> #include <nacl-mounts/base/MainThreadRunner.h> #include <nacl-mounts/base/UrlLoaderJob.h> #include <nacl-mounts/memory/MemMount.h> #include "../libtcc.h" using namespace std; extern "C" int mount(const char *type, const char *dir, int flags, void *data); extern "C" int umount(const char *path); extern "C" int simple_tar_extract(const char *path); static void* InitFileSystemThread(void* data); /// The Instance class. One of these exists for each instance of your NaCl /// module on the web page. The browser will ask the Module object to create /// a new Instance for each occurence of the <embed> tag that has these /// attributes: /// type="application/x-nacl" /// src="tinycc.nmf" /// To communicate with the browser, you must override HandleMessage() for /// receiving messages from the borwser, and use PostMessage() to send messages /// back to the browser. Note that this interface is entirely asynchronous. class TinyccInstance : public pp::Instance { public: /// The constructor creates the plugin-side instance. /// @param[in] instance the handle to the browser-side plugin instance. explicit TinyccInstance(PP_Instance instance) : pp::Instance(instance) { PostMessage(pp::Var("status:INITIALIZED")); } virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) { runner_.reset(new MainThreadRunner(this)); pthread_t th; pthread_create(&th, NULL, &InitFileSystemThread, this); return true; } virtual ~TinyccInstance() { } /// Handler for messages coming in from the browser via postMessage(). The /// @a var_message can contain anything: a JSON string; a string that encodes /// method names and arguments; etc. For example, you could use /// JSON.stringify in the browser to create a message that contains a method /// name and some parameters, something like this: /// var json_message = JSON.stringify({ "myMethod" : "3.14159" }); /// nacl_module.postMessage(json_message); /// On receipt of this message in @a var_message, you could parse the JSON to /// retrieve the method name, match it to a function call, and then call it /// with the parameter. /// @param[in] var_message The message posted by the browser. virtual void HandleMessage(const pp::Var& var_message) { if (!var_message.is_string()) { PostMessage(pp::Var("unexpected type: " + var_message.DebugString())); return; } errors_.clear(); const string& msg = var_message.AsString(); size_t colon_offset = msg.find(':'); if (colon_offset == string::npos) { PostMessage(pp::Var("invalid command: " + var_message.DebugString())); } const string& cmd = msg.substr(0, colon_offset); int output_type = TCC_OUTPUT_MEMORY; if (cmd == "preprocess") { output_type = TCC_OUTPUT_PREPROCESS; } else if (cmd == "compile") { output_type = TCC_OUTPUT_OBJ; } else if (cmd == "run") { output_type = TCC_OUTPUT_MEMORY; } else { PostMessage(pp::Var("invalid command: " + cmd)); return; } close(1); close(2); int fd; fd = open("/tmp/stdout.txt", O_WRONLY | O_CREAT | O_TRUNC); assert(fd == 1); fd = open("/tmp/stderr.txt", O_WRONLY | O_CREAT | O_TRUNC); assert(fd == 2); fd = open("/tmp/input.c", O_WRONLY | O_CREAT | O_TRUNC); assert(fd >= 0); write(fd, msg.c_str() + colon_offset + 1, msg.size() - colon_offset - 1); close(fd); ScopedTCCState tcc_state; TCCState* s1 = tcc_state.get(); tcc_set_error_func(s1, this, &TinyccInstance::HandleTCCError); tcc_set_output_type(s1, output_type); tcc_add_include_path(s1, "/usr/include"); tcc_add_include_path(s1, "/usr/lib/tcc/include"); tcc_add_file(s1, "/tmp/input.c"); if (output_type == TCC_OUTPUT_OBJ) { tcc_output_file(s1, "/tmp/out"); } if (errors_.empty() && output_type == TCC_OUTPUT_MEMORY) { char* argv[] = { (char*)"./a.out", NULL }; tcc_run(s1, 1, argv); } string out; close(1); close(2); if (errors_.empty()) { fd = open("/tmp/stdout.txt", O_RDONLY); if (fd >= 0) { string o; ReadFromFD(fd, &o); if (!o.empty()) { out += "=== STDOUT ===\n"; out += o; } } fd = open("/tmp/stderr.txt", O_RDONLY); if (fd >= 0) { string o; ReadFromFD(fd, &o); if (!o.empty()) { out += "=== STDERR ===\n"; out += o; } } } else { out += "=== COMPILE ERROR ===\n"; for (size_t i = 0; i < errors_.size(); i++) { out += errors_[i]; out += '\n'; } } if (output_type == TCC_OUTPUT_OBJ) { int fd = open("/tmp/out", O_RDONLY); if (fd < 0) { PostMessage(pp::Var( string("failed to read output: ") + strerror(errno))); return; } ReadFromFD(fd, &out); PostMessage(pp::Var(out)); return; } PostMessage(pp::Var(out)); } static void HandleTCCError(void* data, const char* msg) { TinyccInstance* self = (TinyccInstance*)data; self->errors_.push_back(msg); } void InitFileSystem() { PostMessageFromThread("status:DOWNLOADING DATA"); UrlLoaderJob *job = new UrlLoaderJob; job->set_url("x86_64-nacl.sar?v16"); std::vector<char> data; job->set_dst(&data); runner_->RunJob(job); PostMessageFromThread("status:WRITING DATA"); int fd = open("/x86_64-nacl.sar", O_CREAT | O_WRONLY); if (fd < 0) { PostMessageFromThread("status:WRITE DATA FAILED"); return; } write(fd, &data[0], data.size()); close(fd); mkdir("/tmp", 0777); mkdir("/usr", 0777); chdir("/usr"); PostMessageFromThread("status:EXTRACTING DATA"); int r = simple_tar_extract("/x86_64-nacl.sar"); if (r != 0) { PostMessageFromThread("status:EXTRACT DATA FAILED"); } #ifdef __x86_64__ PostMessageFromThread("status:READY (64bit)"); #else PostMessageFromThread("status:READY (32bit)"); #endif } private: class PostMessageJob : public MainThreadJob { public: PostMessageJob(const string& msg) : msg_(msg) {} virtual ~PostMessageJob() {} virtual void Run(MainThreadRunner::JobEntry* entry) { pp::Instance* self = MainThreadRunner::ExtractPepperInstance(entry); self->PostMessage(pp::Var(msg_)); MainThreadRunner::ResultCompletion(entry, 0); } private: string msg_; }; struct ScopedTCCState { ScopedTCCState() { s1_ = tcc_new(); } ~ScopedTCCState() { tcc_delete(s1_); } TCCState* get() { return s1_; } private: TCCState* s1_; }; void PostMessageFromThread(const string& msg) { PostMessageJob* job = new PostMessageJob(msg); runner_->RunJob(job); } static void ReadFromFD(int fd, string* out) { off_t size = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); char* buf = (char*)malloc(size + 1); buf[size] = '\0'; read(fd, buf, size); close(fd); *out = buf; free(buf); } static string ReadFromFile(const char* file) { int fd = open(file, O_RDONLY); string s; ReadFromFD(fd, &s); return s; } auto_ptr<MainThreadRunner> runner_; auto_ptr<MemMount> mount_; vector<string> errors_; }; void* InitFileSystemThread(void* data) { TinyccInstance* self = (TinyccInstance*)data; self->InitFileSystem(); return NULL; } /// The Module class. The browser calls the CreateInstance() method to create /// an instance of your NaCl module on the web page. The browser creates a new /// instance for each <embed> tag with type="application/x-nacl". class TinyccModule : public pp::Module { public: TinyccModule() : pp::Module() {} virtual ~TinyccModule() {} /// Create and return a TinyccInstance object. /// @param[in] instance The browser-side instance. /// @return the plugin-side instance. virtual pp::Instance* CreateInstance(PP_Instance instance) { return new TinyccInstance(instance); } }; namespace pp { /// Factory function called by the browser when the module is first loaded. /// The browser keeps a singleton of this module. It calls the /// CreateInstance() method on the object you return to make instances. There /// is one instance per <embed> tag on the page. This is the main binding /// point for your NaCl module with the browser. Module* CreateModule() { return new TinyccModule(); } } // namespace pp <commit_msg>[NaCl] correct the path to data<commit_after>/// @file tinycc.cc /// This example demonstrates loading, running and scripting a very simple NaCl /// module. To load the NaCl module, the browser first looks for the /// CreateModule() factory method (at the end of this file). It calls /// CreateModule() once to load the module code from your .nexe. After the /// .nexe code is loaded, CreateModule() is not called again. /// /// Once the .nexe code is loaded, the browser than calls the CreateInstance() /// method on the object returned by CreateModule(). It calls CreateInstance() /// each time it encounters an <embed> tag that references your NaCl module. /// /// The browser can talk to your NaCl module via the postMessage() Javascript /// function. When you call postMessage() on your NaCl module from the browser, /// this becomes a call to the HandleMessage() method of your pp::Instance /// subclass. You can send messages back to the browser by calling the /// PostMessage() method on your pp::Instance. Note that these two methods /// (postMessage() in Javascript and PostMessage() in C++) are asynchronous. /// This means they return immediately - there is no waiting for the message /// to be handled. This has implications in your program design, particularly /// when mutating property values that are exposed to both the browser and the /// NaCl module. #include <dirent.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <memory> #include <string> #include <vector> #include <ppapi/cpp/instance.h> #include <ppapi/cpp/module.h> #include <ppapi/cpp/var.h> #include <nacl-mounts/base/MainThreadRunner.h> #include <nacl-mounts/base/UrlLoaderJob.h> #include <nacl-mounts/memory/MemMount.h> #include "../libtcc.h" using namespace std; extern "C" int mount(const char *type, const char *dir, int flags, void *data); extern "C" int umount(const char *path); extern "C" int simple_tar_extract(const char *path); static void* InitFileSystemThread(void* data); /// The Instance class. One of these exists for each instance of your NaCl /// module on the web page. The browser will ask the Module object to create /// a new Instance for each occurence of the <embed> tag that has these /// attributes: /// type="application/x-nacl" /// src="tinycc.nmf" /// To communicate with the browser, you must override HandleMessage() for /// receiving messages from the borwser, and use PostMessage() to send messages /// back to the browser. Note that this interface is entirely asynchronous. class TinyccInstance : public pp::Instance { public: /// The constructor creates the plugin-side instance. /// @param[in] instance the handle to the browser-side plugin instance. explicit TinyccInstance(PP_Instance instance) : pp::Instance(instance) { PostMessage(pp::Var("status:INITIALIZED")); } virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]) { runner_.reset(new MainThreadRunner(this)); pthread_t th; pthread_create(&th, NULL, &InitFileSystemThread, this); return true; } virtual ~TinyccInstance() { } /// Handler for messages coming in from the browser via postMessage(). The /// @a var_message can contain anything: a JSON string; a string that encodes /// method names and arguments; etc. For example, you could use /// JSON.stringify in the browser to create a message that contains a method /// name and some parameters, something like this: /// var json_message = JSON.stringify({ "myMethod" : "3.14159" }); /// nacl_module.postMessage(json_message); /// On receipt of this message in @a var_message, you could parse the JSON to /// retrieve the method name, match it to a function call, and then call it /// with the parameter. /// @param[in] var_message The message posted by the browser. virtual void HandleMessage(const pp::Var& var_message) { if (!var_message.is_string()) { PostMessage(pp::Var("unexpected type: " + var_message.DebugString())); return; } errors_.clear(); const string& msg = var_message.AsString(); size_t colon_offset = msg.find(':'); if (colon_offset == string::npos) { PostMessage(pp::Var("invalid command: " + var_message.DebugString())); } const string& cmd = msg.substr(0, colon_offset); int output_type = TCC_OUTPUT_MEMORY; if (cmd == "preprocess") { output_type = TCC_OUTPUT_PREPROCESS; } else if (cmd == "compile") { output_type = TCC_OUTPUT_OBJ; } else if (cmd == "run") { output_type = TCC_OUTPUT_MEMORY; } else { PostMessage(pp::Var("invalid command: " + cmd)); return; } close(1); close(2); int fd; fd = open("/tmp/stdout.txt", O_WRONLY | O_CREAT | O_TRUNC); assert(fd == 1); fd = open("/tmp/stderr.txt", O_WRONLY | O_CREAT | O_TRUNC); assert(fd == 2); fd = open("/tmp/input.c", O_WRONLY | O_CREAT | O_TRUNC); assert(fd >= 0); write(fd, msg.c_str() + colon_offset + 1, msg.size() - colon_offset - 1); close(fd); ScopedTCCState tcc_state; TCCState* s1 = tcc_state.get(); tcc_set_error_func(s1, this, &TinyccInstance::HandleTCCError); tcc_set_output_type(s1, output_type); tcc_add_include_path(s1, "/data/usr/include"); tcc_add_include_path(s1, "/data/usr/lib/tcc/include"); tcc_add_file(s1, "/tmp/input.c"); if (output_type == TCC_OUTPUT_OBJ) { tcc_output_file(s1, "/tmp/out"); } if (errors_.empty() && output_type == TCC_OUTPUT_MEMORY) { char* argv[] = { (char*)"./a.out", NULL }; tcc_run(s1, 1, argv); } string out; close(1); close(2); if (errors_.empty()) { fd = open("/tmp/stdout.txt", O_RDONLY); if (fd >= 0) { string o; ReadFromFD(fd, &o); if (!o.empty()) { out += "=== STDOUT ===\n"; out += o; } } fd = open("/tmp/stderr.txt", O_RDONLY); if (fd >= 0) { string o; ReadFromFD(fd, &o); if (!o.empty()) { out += "=== STDERR ===\n"; out += o; } } } else { out += "=== COMPILE ERROR ===\n"; for (size_t i = 0; i < errors_.size(); i++) { out += errors_[i]; out += '\n'; } } if (output_type == TCC_OUTPUT_OBJ) { int fd = open("/tmp/out", O_RDONLY); if (fd < 0) { PostMessage(pp::Var( string("failed to read output: ") + strerror(errno))); return; } ReadFromFD(fd, &out); PostMessage(pp::Var(out)); return; } PostMessage(pp::Var(out)); } static void HandleTCCError(void* data, const char* msg) { TinyccInstance* self = (TinyccInstance*)data; self->errors_.push_back(msg); } void InitFileSystem() { PostMessageFromThread("status:DOWNLOADING DATA"); UrlLoaderJob *job = new UrlLoaderJob; job->set_url("data.sar"); std::vector<char> data; job->set_dst(&data); runner_->RunJob(job); PostMessageFromThread("status:WRITING DATA"); int fd = open("/data.sar", O_CREAT | O_WRONLY); if (fd < 0) { PostMessageFromThread("status:WRITE DATA FAILED"); return; } write(fd, &data[0], data.size()); close(fd); mkdir("/tmp", 0777); mkdir("/data", 0777); chdir("/data"); PostMessageFromThread("status:EXTRACTING DATA"); int r = simple_tar_extract("/data.sar"); if (r != 0) { PostMessageFromThread("status:EXTRACT DATA FAILED"); } #ifdef __x86_64__ PostMessageFromThread("status:READY (64bit)"); #else PostMessageFromThread("status:READY (32bit)"); #endif } private: class PostMessageJob : public MainThreadJob { public: PostMessageJob(const string& msg) : msg_(msg) {} virtual ~PostMessageJob() {} virtual void Run(MainThreadRunner::JobEntry* entry) { pp::Instance* self = MainThreadRunner::ExtractPepperInstance(entry); self->PostMessage(pp::Var(msg_)); MainThreadRunner::ResultCompletion(entry, 0); } private: string msg_; }; struct ScopedTCCState { ScopedTCCState() { s1_ = tcc_new(); } ~ScopedTCCState() { tcc_delete(s1_); } TCCState* get() { return s1_; } private: TCCState* s1_; }; void PostMessageFromThread(const string& msg) { PostMessageJob* job = new PostMessageJob(msg); runner_->RunJob(job); } static void ReadFromFD(int fd, string* out) { off_t size = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); char* buf = (char*)malloc(size + 1); buf[size] = '\0'; read(fd, buf, size); close(fd); *out = buf; free(buf); } static string ReadFromFile(const char* file) { int fd = open(file, O_RDONLY); string s; ReadFromFD(fd, &s); return s; } auto_ptr<MainThreadRunner> runner_; auto_ptr<MemMount> mount_; vector<string> errors_; }; void* InitFileSystemThread(void* data) { TinyccInstance* self = (TinyccInstance*)data; self->InitFileSystem(); return NULL; } /// The Module class. The browser calls the CreateInstance() method to create /// an instance of your NaCl module on the web page. The browser creates a new /// instance for each <embed> tag with type="application/x-nacl". class TinyccModule : public pp::Module { public: TinyccModule() : pp::Module() {} virtual ~TinyccModule() {} /// Create and return a TinyccInstance object. /// @param[in] instance The browser-side instance. /// @return the plugin-side instance. virtual pp::Instance* CreateInstance(PP_Instance instance) { return new TinyccInstance(instance); } }; namespace pp { /// Factory function called by the browser when the module is first loaded. /// The browser keeps a singleton of this module. It calls the /// CreateInstance() method on the object you return to make instances. There /// is one instance per <embed> tag on the page. This is the main binding /// point for your NaCl module with the browser. Module* CreateModule() { return new TinyccModule(); } } // namespace pp <|endoftext|>