text
string
size
int64
token_count
int64
#include "household.hpp" namespace epiabm { Household::Household(size_t mcellPos) : MembersInterface(mcellPos), m_params(), m_mcellPos(mcellPos) {} size_t Household::microcellPos() const { return m_mcellPos; } HouseholdParams& Household::params() { return m_params; } } // namespace epiabm
337
123
#ifdef HAVE_CONFIG_H #include <../../config.h> #endif /* * Copyright (c) 1990, 1991 Stanford University * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided * that the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Stanford not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. Stanford makes no representations about * the suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * STANFORD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. * IN NO EVENT SHALL STANFORD BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Implementation of ULabel, an object derived from Graphic. */ #include <Unidraw/globals.h> #include <Unidraw/Graphic/ulabel.h> #include <IV-2_6/InterViews/painter.h> #include <InterViews/transformer.h> #include <IV-2_6/_enter.h> #include <string.h> /*****************************************************************************/ ULabel::ULabel (const char* s, Graphic* gr) : Graphic(gr) { _font = nil; if (gr != nil) { ULabel::SetFont(gr->GetFont()); } _string = strnew(s); } ULabel::~ULabel () { delete [] _string; Unref(_font); } void ULabel::SetFont (PSFont* font) { if (_font != font) { Ref(font); Unref(_font); _font = font; invalidateCaches(); } } extern PSPattern* pssolid; // hack (see header file) PSPattern* ULabel::GetPattern () { return pssolid; } PSFont* ULabel::GetFont () { return _font; } Graphic* ULabel::Copy () { return new ULabel(_string, this); } void ULabel::getExtent ( float& x0, float& y0, float& cx, float& cy, float& tol, Graphic* gs ) { PSFont* f = gs->GetFont(); float width = f->Width(_string); float height = f->Height(); if (gs->GetTransformer() == nil) { x0 = 0; y0 = 0; cx = width / 2; cy = height / 2; } else { transformRect(0, 0, width, height, x0, y0, cx, cy, gs); cx = (cx + x0)/2; cy = (cy + y0)/2; } tol = 0; } boolean ULabel::contains (PointObj& po, Graphic* gs) { PointObj pt (&po); PSFont* f = gs->GetFont(); invTransform(pt._x, pt._y, gs); BoxObj b (0, 0, f->Width(_string), f->Height()); return b.Contains(pt); } boolean ULabel::intersects (BoxObj& userb, Graphic* gs) { Transformer* t = gs->GetTransformer(); PSFont* f = gs->GetFont(); Coord xmax = f->Width(_string); Coord ymax = f->Height(); Coord tx0, ty0, tx1, ty1; if (t != nil && t->Rotated()) { Coord x[4], tx[5]; Coord y[4], ty[5]; x[0] = x[3] = y[0] = y[1] = 0; x[2] = x[1] = xmax; y[2] = y[3] = ymax; transformList(x, y, 4, tx, ty, gs); tx[4] = tx[0]; ty[4] = ty[0]; FillPolygonObj fp (tx, ty, 5); return fp.Intersects(userb); } else if (t != nil) { t->Transform(0, 0, tx0, ty0); t->Transform(xmax, ymax, tx1, ty1); BoxObj b1 (tx0, ty0, tx1, ty1); return b1.Intersects(userb); } else { BoxObj b2 (0, 0, xmax, ymax); return b2.Intersects(userb); } } void ULabel::draw (Canvas *c, Graphic* gs) { update(gs); _p->Text(c, _string, 0, 0); }
3,686
1,437
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <cstring> #include "lite/api/paddle_use_kernels.h" #include "lite/api/paddle_use_ops.h" #include "lite/core/arena/framework.h" #include "lite/tests/utils/fill_data.h" namespace paddle { namespace lite { template <class T> class SequencePadTester : public arena::TestCase { protected: std::string x_ = "x"; std::string pad_value_ = "pad_value"; std::string out_ = "out"; std::string length_ = "length"; DDim x_dims_{{9, 2, 3, 4}}; LoD x_lod_{{{0, 2, 5, 9}}}; T value_ = 0; int padded_length_ = 4; public: SequencePadTester(const Place& place, const std::string& alias) : TestCase(place, alias) {} void RunBaseline(Scope* scope) override { auto* out = scope->NewTensor(out_); auto out_shape = x_dims_.Vectorize(); out_shape[0] = padded_length_; out_shape.insert(out_shape.begin(), static_cast<int64_t>(x_lod_[0].size() - 1)); out->Resize(out_shape); auto* out_data = out->template mutable_data<T>(); for (int64_t i = 0; i < out->numel(); i++) { out_data[i] = value_; } int n = x_dims_.production() / x_dims_[0]; int out_step = padded_length_ * n; auto* x = scope->FindTensor(x_); auto* x_data = x->template data<T>(); for (size_t i = 1; i < x_lod_[0].size(); i++) { int x_step = (x_lod_[0][i] - x_lod_[0][i - 1]) * n; memcpy(out_data, x_data, sizeof(T) * x_step); x_data += x_step; out_data += out_step; } auto* length = scope->NewTensor(length_); length->Resize({static_cast<int64_t>(x_lod_[0].size() - 1)}); int64_t* length_data = length->template mutable_data<int64_t>(); for (size_t i = 1; i < x_lod_[0].size(); i++) { length_data[i - 1] = x_lod_[0][i] - x_lod_[0][i - 1]; } } void PrepareOpDesc(cpp::OpDesc* op_desc) { op_desc->SetType("sequence_pad"); op_desc->SetInput("X", {x_}); op_desc->SetInput("PadValue", {pad_value_}); op_desc->SetOutput("Out", {out_}); op_desc->SetOutput("Length", {length_}); op_desc->SetAttr("padded_length", padded_length_); } void PrepareData() override { std::vector<T> x_data(x_dims_.production()); fill_data_rand<T>(x_data.data(), -10, 10, x_dims_.production()); SetCommonTensor(x_, x_dims_, x_data.data(), x_lod_); std::vector<T> pad_value_data{0}; SetCommonTensor(pad_value_, DDim{{1}}, pad_value_data.data()); } }; template <class T> void TestSequencePad(const Place place, const float abs_error, const std::string alias) { std::unique_ptr<arena::TestCase> tester( new SequencePadTester<T>(place, alias)); arena::Arena arena(std::move(tester), place, abs_error); arena.TestPrecision(); } TEST(sequence_pad, precision) { Place place; float abs_error = 1e-5; #if defined(LITE_WITH_ARM) || defined(LITE_WITH_X86) place = TARGET(kHost); #else return; #endif TestSequencePad<float>(place, abs_error, "def"); TestSequencePad<int>(place, abs_error, "int32"); TestSequencePad<int64_t>(place, abs_error, "int64"); } } // namespace lite } // namespace paddle
3,745
1,445
// Copyright 2013 Daniel Parker // Distributed under the Boost license, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See https://github.com/danielaparker/jsoncons for latest version #ifndef JSONCONS_JSON_CONTAINER_HPP #define JSONCONS_JSON_CONTAINER_HPP #include <string> #include <vector> #include <deque> #include <exception> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #include <sstream> #include <iomanip> #include <utility> #include <initializer_list> #include <jsoncons/jsoncons.hpp> #include <jsoncons/json_traits.hpp> #include <jsoncons/jsoncons_util.hpp> namespace jsoncons { template <class Json> class Json_string_base_ { public: typedef typename Json::allocator_type allocator_type; Json_string_base_() : self_allocator_() { } Json_string_base_(const allocator_type& allocator) : self_allocator_(allocator) { } private: allocator_type self_allocator_; }; template <class Json> class Json_string_ { public: typedef typename Json::allocator_type allocator_type; typedef typename Json::char_allocator_type char_allocator_type; typedef typename Json::char_type char_type; typedef typename Json::string_storage_type string_storage_type; typedef typename string_storage_type::iterator iterator; typedef typename string_storage_type::const_iterator const_iterator; //using Json_string_base_<Json>::get_allocator; Json_string_() : //Json_string_base_<Json>(), string_() { } Json_string_(const Json_string_& val) : //Json_string_base_<Json>(val.get_allocator()), string_(val.string_) { } Json_string_(const Json_string_& val, const allocator_type& allocator) : //Json_string_base_<Json>(allocator), string_(val.string_,char_allocator_type(allocator)) { } Json_string_(Json_string_&& val) JSONCONS_NOEXCEPT : //Json_string_base_<Json>(val.get_allocator()), string_(std::move(val.string_)) { } Json_string_(Json_string_&& val, const allocator_type& allocator) : //Json_string_base_<Json>(allocator), string_(std::move(val.string_),char_allocator_type(allocator)) { } explicit Json_string_(const allocator_type& allocator) : //Json_string_base_<Json>(allocator), string_(char_allocator_type(allocator)) { } Json_string_(const char_type* data, size_t length) : //Json_string_base_<Json>(), string_(data,length) { } Json_string_(const char_type* data, size_t length, allocator_type allocator) : //Json_string_base_<Json>(allocator), string_(data, length, allocator) { } const char_type* data() const { return string_.data(); } const char_type* c_str() const { return string_.c_str(); } size_t length() const { return string_.size(); } allocator_type get_allocator() const { return string_.get_allocator(); } private: string_storage_type string_; Json_string_<Json>& operator=(const Json_string_<Json>&) = delete; }; // json_array template <class Json> class Json_array_base_ { public: typedef typename Json::allocator_type allocator_type; public: Json_array_base_() : self_allocator_() { } Json_array_base_(const allocator_type& allocator) : self_allocator_(allocator) { } allocator_type get_allocator() const { return self_allocator_; } allocator_type self_allocator_; }; template <class Json> class json_array: public Json_array_base_<Json> { public: typedef typename Json::allocator_type allocator_type; typedef Json value_type; typedef typename std::allocator_traits<allocator_type>:: template rebind_alloc<value_type> val_allocator_type; typedef typename Json::array_storage_type array_storage_type; typedef typename array_storage_type::iterator iterator; typedef typename array_storage_type::const_iterator const_iterator; typedef typename std::iterator_traits<iterator>::reference reference; typedef typename std::iterator_traits<const_iterator>::reference const_reference; using Json_array_base_<Json>::get_allocator; json_array() : Json_array_base_<Json>(), elements_() { } explicit json_array(const allocator_type& allocator) : Json_array_base_<Json>(allocator), elements_(val_allocator_type(allocator)) { } explicit json_array(size_t n, const allocator_type& allocator = allocator_type()) : Json_array_base_<Json>(allocator), elements_(n,Json(),val_allocator_type(allocator)) { } explicit json_array(size_t n, const Json& value, const allocator_type& allocator = allocator_type()) : Json_array_base_<Json>(allocator), elements_(n,value,val_allocator_type(allocator)) { } template <class InputIterator> json_array(InputIterator begin, InputIterator end, const allocator_type& allocator = allocator_type()) : Json_array_base_<Json>(allocator), elements_(begin,end,val_allocator_type(allocator)) { } json_array(const json_array& val) : Json_array_base_<Json>(val.get_allocator()), elements_(val.elements_) { } json_array(const json_array& val, const allocator_type& allocator) : Json_array_base_<Json>(allocator), elements_(val.elements_,val_allocator_type(allocator)) { } json_array(json_array&& val) JSONCONS_NOEXCEPT : Json_array_base_<Json>(val.get_allocator()), elements_(std::move(val.elements_)) { } json_array(json_array&& val, const allocator_type& allocator) : Json_array_base_<Json>(allocator), elements_(std::move(val.elements_),val_allocator_type(allocator)) { } json_array(std::initializer_list<Json> init) : Json_array_base_<Json>(), elements_(std::move(init)) { } json_array(std::initializer_list<Json> init, const allocator_type& allocator) : Json_array_base_<Json>(allocator), elements_(std::move(init),val_allocator_type(allocator)) { } ~json_array() { } void swap(json_array<Json>& val) { elements_.swap(val.elements_); } size_t size() const {return elements_.size();} size_t capacity() const {return elements_.capacity();} void clear() {elements_.clear();} void shrink_to_fit() { for (size_t i = 0; i < elements_.size(); ++i) { elements_[i].shrink_to_fit(); } elements_.shrink_to_fit(); } void reserve(size_t n) {elements_.reserve(n);} void resize(size_t n) {elements_.resize(n);} void resize(size_t n, const Json& val) {elements_.resize(n,val);} void remove_range(size_t from_index, size_t to_index) { JSONCONS_ASSERT(from_index <= to_index); JSONCONS_ASSERT(to_index <= elements_.size()); elements_.erase(elements_.begin()+from_index,elements_.begin()+to_index); } void erase(iterator first, iterator last) { elements_.erase(first,last); } Json& operator[](size_t i) {return elements_[i];} const Json& operator[](size_t i) const {return elements_[i];} template <class T, class U=allocator_type, typename std::enable_if<is_stateless<U>::value >::type* = nullptr> void add(T&& value) { elements_.emplace_back(Json(std::forward<T&&>(value))); } template <class T, class U=allocator_type, typename std::enable_if<!is_stateless<U>::value >::type* = nullptr> void add(T&& value) { elements_.emplace_back(std::forward<T&&>(value),get_allocator()); } #if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 9 // work around https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54577 template <class T, class U=allocator_type> typename std::enable_if<is_stateless<U>::value,iterator>::type add(const_iterator pos, T&& value) { iterator it = elements_.begin() + (pos - elements_.begin()); return elements_.emplace(it, Json(std::forward<T&&>(value))); } #else template <class T, class U=allocator_type> typename std::enable_if<is_stateless<U>::value,iterator>::type add(const_iterator pos, T&& value) { return elements_.emplace(pos, Json(std::forward<T&&>(value))); } #endif iterator begin() {return elements_.begin();} iterator end() {return elements_.end();} const_iterator begin() const {return elements_.begin();} const_iterator end() const {return elements_.end();} bool operator==(const json_array<Json>& rhs) const { if (size() != rhs.size()) { return false; } for (size_t i = 0; i < size(); ++i) { if (elements_[i] != rhs.elements_[i]) { return false; } } return true; } private: array_storage_type elements_; json_array& operator=(const json_array<Json>&) = delete; }; // json_object template <class BidirectionalIt,class BinaryPredicate> BidirectionalIt last_wins_unique_sequence(BidirectionalIt first, BidirectionalIt last, BinaryPredicate compare) { if (first == last) { return last; } typedef typename BidirectionalIt::value_type value_type; typedef typename BidirectionalIt::pointer pointer; std::vector<value_type> dups; { std::vector<pointer> v(std::distance(first,last)); auto p = v.begin(); for (auto it = first; it != last; ++it) { *p++ = &(*it); } std::sort(v.begin(), v.end(), [&](pointer a, pointer b){return compare(*a,*b)<0;}); auto it = v.begin(); auto end = v.end(); for (auto begin = it+1; begin != end; ++it, ++begin) { if (compare(*(*it),*(*begin)) == 0) { dups.push_back(*(*it)); } } } if (dups.size() == 0) { return last; } auto it = last; for (auto p = first; p != last && p != it; ) { bool no_dup = true; if (dups.size() > 0) { for (auto q = dups.begin(); no_dup && q != dups.end();) { if (compare(*p,*q) == 0) { dups.erase(q); no_dup = false; } else { ++q; } } } if (!no_dup) { --it; for (auto r = p; r != it; ++r) { *r = std::move(*(r+1)); } } else { ++p; } } return it; } template <class KeyT, class ValueT> class key_value_pair { public: typedef KeyT key_storage_type; typedef typename KeyT::value_type char_type; typedef typename KeyT::allocator_type allocator_type; typedef typename ValueT::string_view_type string_view_type; key_value_pair() { } key_value_pair(const key_storage_type& name, const ValueT& val) : key_(name), value_(val) { } key_value_pair(key_storage_type&& name, ValueT&& val) : key_(std::forward<key_storage_type&&>(name)), value_(std::forward<ValueT&&>(val)) { } key_value_pair(const key_value_pair& member) : key_(member.key_), value_(member.value_) { } key_value_pair(key_value_pair&& member) : key_(std::move(member.key_)), value_(std::move(member.value_)) { } template <class T> key_value_pair(key_storage_type&& name, T&& val, const allocator_type& allocator) : key_(std::forward<key_storage_type&&>(name)), value_(std::forward<T&&>(val), allocator) { } string_view_type key() const { return string_view_type(key_.data(),key_.size()); } ValueT& value() { return value_; } const ValueT& value() const { return value_; } void value(const ValueT& value) { value_ = value; } void value(ValueT&& value) { value_ = std::forward<ValueT&&>(value); } void swap(key_value_pair& member) { key_.swap(member.key_); value_.swap(member.value_); } key_value_pair& operator=(const key_value_pair& member) { if (this != & member) { key_ = member.key_; value_ = member.value_; } return *this; } key_value_pair& operator=(key_value_pair&& member) { if (this != &member) { key_.swap(member.key_); value_.swap(member.value_); } return *this; } void shrink_to_fit() { key_.shrink_to_fit(); value_.shrink_to_fit(); } #if !defined(JSONCONS_NO_DEPRECATED) const key_storage_type& name() const { return key_; } #endif private: key_storage_type key_; ValueT value_; }; template <class KeyT,class Json> class Json_object_ { public: typedef typename Json::allocator_type allocator_type; typedef typename Json::char_type char_type; typedef typename Json::char_allocator_type char_allocator_type; typedef KeyT key_storage_type; typedef typename Json::string_view_type string_view_type; typedef key_value_pair<KeyT,Json> value_type; typedef typename std::allocator_traits<allocator_type>:: template rebind_alloc<value_type> kvp_allocator_type; typedef typename Json::object_storage_type object_storage_type; typedef typename object_storage_type::iterator iterator; typedef typename object_storage_type::const_iterator const_iterator; protected: allocator_type self_allocator_; object_storage_type members_; public: Json_object_() : self_allocator_(), members_() { } Json_object_(const allocator_type& allocator) : self_allocator_(allocator), members_(kvp_allocator_type(allocator)) { } Json_object_(const Json_object_& val) : self_allocator_(val.get_allocator()), members_(val.members_) { } Json_object_(Json_object_&& val) : self_allocator_(val.get_allocator()), members_(std::move(val.members_)) { } Json_object_(const Json_object_& val, const allocator_type& allocator) : self_allocator_(allocator), members_(val.members_,kvp_allocator_type(allocator)) { } Json_object_(Json_object_&& val,const allocator_type& allocator) : self_allocator_(allocator), members_(std::move(val.members_),kvp_allocator_type(allocator)) { } void swap(Json_object_& val) { members_.swap(val.members_); } allocator_type get_allocator() const { return this->self_allocator_; } }; template <class KeyT,class Json,bool PreserveOrder> class json_object { }; // Do not preserve order template <class KeyT,class Json> class json_object<KeyT,Json,false> : public Json_object_<KeyT,Json> { public: using typename Json_object_<KeyT,Json>::allocator_type; using typename Json_object_<KeyT,Json>::char_type; using typename Json_object_<KeyT,Json>::char_allocator_type; using typename Json_object_<KeyT,Json>::key_storage_type; using typename Json_object_<KeyT,Json>::string_view_type; using typename Json_object_<KeyT,Json>::value_type; using typename Json_object_<KeyT,Json>::kvp_allocator_type; using typename Json_object_<KeyT,Json>::object_storage_type; using typename Json_object_<KeyT,Json>::iterator; using typename Json_object_<KeyT,Json>::const_iterator; using Json_object_<KeyT,Json>::get_allocator; json_object() : Json_object_<KeyT,Json>() { } json_object(const allocator_type& allocator) : Json_object_<KeyT,Json>(allocator) { } json_object(const json_object& val) : Json_object_<KeyT,Json>(val) { } json_object(json_object&& val) : Json_object_<KeyT,Json>(std::forward<json_object&&>(val)) { } json_object(const json_object& val, const allocator_type& allocator) : Json_object_<KeyT,Json>(val,allocator) { } json_object(json_object&& val,const allocator_type& allocator) : Json_object_<KeyT,Json>(std::forward<json_object&&>(val),allocator) { } json_object(std::initializer_list<typename Json::array> init) : Json_object_<KeyT,Json>() { for (const auto& element : init) { if (element.size() != 2 || !element[0].is_string()) { JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list"); break; } } for (auto& element : init) { set(element[0].as_string_view(), std::move(element[1])); } } json_object(std::initializer_list<typename Json::array> init, const allocator_type& allocator) : Json_object_<KeyT,Json>(allocator) { for (const auto& element : init) { if (element.size() != 2 || !element[0].is_string()) { JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list"); break; } } for (auto& element : init) { set(element[0].as_string_view(), std::move(element[1])); } } void swap(json_object& val) { Json_object_<KeyT,Json>::swap(val); } iterator begin() { return this->members_.begin(); } iterator end() { return this->members_.end(); } const_iterator begin() const { return this->members_.begin(); } const_iterator end() const { return this->members_.end(); } size_t size() const {return this->members_.size();} size_t capacity() const {return this->members_.capacity();} void clear() {this->members_.clear();} void shrink_to_fit() { for (size_t i = 0; i < this->members_.size(); ++i) { this->members_[i].shrink_to_fit(); } this->members_.shrink_to_fit(); } void reserve(size_t n) {this->members_.reserve(n);} Json& at(size_t i) { if (i >= this->members_.size()) { JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript"); } return this->members_[i].value(); } const Json& at(size_t i) const { if (i >= this->members_.size()) { JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript"); } return this->members_[i].value(); } iterator find(string_view_type name) { auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); auto result = (it != this->members_.end() && it->key() == name) ? it : this->members_.end(); return result; } const_iterator find(string_view_type name) const { auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); auto result = (it != this->members_.end() && it->key() == name) ? it : this->members_.end(); return result; } void erase(iterator first, iterator last) { this->members_.erase(first,last); } void erase(string_view_type name) { auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); if (it != this->members_.end() && it->key() == name) { this->members_.erase(it); } } template<class InputIt, class UnaryPredicate> void insert(InputIt first, InputIt last, UnaryPredicate pred) { size_t count = std::distance(first,last); this->members_.reserve(this->members_.size() + count); for (auto s = first; s != last; ++s) { this->members_.emplace_back(pred(*s)); } std::stable_sort(this->members_.begin(),this->members_.end(), [](const value_type& a, const value_type& b){return a.key().compare(b.key()) < 0;}); auto it = std::unique(this->members_.rbegin(), this->members_.rend(), [](const value_type& a, const value_type& b){ return !(a.key().compare(b.key()));}); this->members_.erase(this->members_.begin(),it.base()); } template <class T, class U=allocator_type, typename std::enable_if<is_stateless<U>::value >::type* = nullptr> void set(string_view_type name, T&& value) { auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); if (it == this->members_.end()) { this->members_.emplace_back(key_storage_type(name.begin(),name.end()), std::forward<T&&>(value)); } else if (it->key() == name) { it->value(Json(std::forward<T&&>(value))); } else { this->members_.emplace(it, key_storage_type(name.begin(),name.end()), std::forward<T&&>(value)); } } template <class T, class U=allocator_type, typename std::enable_if<!is_stateless<U>::value >::type* = nullptr> void set(string_view_type name, T&& value) { auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); if (it == this->members_.end()) { this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()), std::forward<T&&>(value),get_allocator() ); } else if (it->key() == name) { it->value(Json(std::forward<T&&>(value),get_allocator() )); } else { this->members_.emplace(it, key_storage_type(name.begin(),name.end(), get_allocator()), std::forward<T&&>(value),get_allocator() ); } } template <class T, class U=allocator_type, typename std::enable_if<is_stateless<U>::value >::type* = nullptr> void set_(key_storage_type&& name, T&& value) { string_view_type s(name.data(), name.size()); auto it = std::lower_bound(this->members_.begin(),this->members_.end(), s, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); if (it == this->members_.end()) { this->members_.emplace_back(std::forward<key_storage_type&&>(name), std::forward<T&&>(value)); } else if (string_view_type(it->key().data(),it->key().length()) == s) { it->value(Json(std::forward<T&&>(value))); } else { this->members_.emplace(it, std::forward<key_storage_type&&>(name), std::forward<T&&>(value)); } } template <class T, class U=allocator_type, typename std::enable_if<!is_stateless<U>::value >::type* = nullptr> void set_(key_storage_type&& name, T&& value) { string_view_type s(name.data(), name.size()); auto it = std::lower_bound(this->members_.begin(),this->members_.end(), s, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); if (it == this->members_.end()) { this->members_.emplace_back(std::forward<key_storage_type&&>(name), std::forward<T&&>(value),get_allocator() ); } else if (string_view_type(it->key().data(), it->key().length()) == s) { it->value(Json(std::forward<T&&>(value),get_allocator() )); } else { this->members_.emplace(it, std::forward<key_storage_type&&>(name), std::forward<T&&>(value),get_allocator() ); } } template <class T, class U=allocator_type> typename std::enable_if<is_stateless<U>::value,iterator>::type set(iterator hint, string_view_type name, T&& value) { iterator it; if (hint != this->members_.end() && hint->key() <= name) { it = std::lower_bound(hint,this->members_.end(), name, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); } else { it = std::lower_bound(this->members_.begin(),this->members_.end(), name, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); } if (it == this->members_.end()) { this->members_.emplace_back(key_storage_type(name.begin(),name.end()), std::forward<T&&>(value)); it = this->members_.begin() + (this->members_.size() - 1); } else if (it->key() == name) { it->value(Json(std::forward<T&&>(value))); } else { it = this->members_.emplace(it, key_storage_type(name.begin(),name.end()), std::forward<T&&>(value)); } return it; } template <class T, class U=allocator_type> typename std::enable_if<!is_stateless<U>::value,iterator>::type set(iterator hint, string_view_type name, T&& value) { iterator it; if (hint != this->members_.end() && hint->key() <= name) { it = std::lower_bound(hint,this->members_.end(), name, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); } else { it = std::lower_bound(this->members_.begin(),this->members_.end(), name, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); } if (it == this->members_.end()) { this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()), std::forward<T&&>(value),get_allocator() ); it = this->members_.begin() + (this->members_.size() - 1); } else if (it->key() == name) { it->value(Json(std::forward<T&&>(value),get_allocator() )); } else { it = this->members_.emplace(it, key_storage_type(name.begin(),name.end(), get_allocator()), std::forward<T&&>(value),get_allocator() ); } return it; } template <class T, class U=allocator_type> typename std::enable_if<is_stateless<U>::value,iterator>::type set_(iterator hint, key_storage_type&& name, T&& value) { string_view_type s(name.data(), name.size()); iterator it; if (hint != this->members_.end() && hint->key() <= s) { it = std::lower_bound(hint,this->members_.end(), s, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); } else { it = std::lower_bound(this->members_.begin(),this->members_.end(), s, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); } if (it == this->members_.end()) { this->members_.emplace_back(std::forward<key_storage_type&&>(name), std::forward<T&&>(value)); it = this->members_.begin() + (this->members_.size() - 1); } else if (string_view_type(it->key().data(), it->key().length()) == s) { it->value(Json(std::forward<T&&>(value))); } else { it = this->members_.emplace(it, std::forward<key_storage_type&&>(name), std::forward<T&&>(value)); } return it; } template <class T, class U=allocator_type> typename std::enable_if<!is_stateless<U>::value,iterator>::type set_(iterator hint, key_storage_type&& name, T&& value) { string_view_type s(name.data(), name.size()); iterator it; if (hint != this->members_.end() && hint->key() <= s) { it = std::lower_bound(hint,this->members_.end(), s, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); } else { it = std::lower_bound(this->members_.begin(),this->members_.end(), s, [](const value_type& a, string_view_type k){return a.key().compare(k) < 0;}); } if (it == this->members_.end()) { this->members_.emplace_back(std::forward<key_storage_type&&>(name), std::forward<T&&>(value),get_allocator() ); it = this->members_.begin() + (this->members_.size() - 1); } else if (string_view_type(it->key().data(), it->key().length()) == s) { it->value(Json(std::forward<T&&>(value),get_allocator() )); } else { it = this->members_.emplace(it, std::forward<key_storage_type&&>(name), std::forward<T&&>(value),get_allocator() ); } return it; } bool operator==(const json_object& rhs) const { if (size() != rhs.size()) { return false; } for (auto it = this->members_.begin(); it != this->members_.end(); ++it) { auto rhs_it = std::lower_bound(rhs.begin(), rhs.end(), *it, [](const value_type& a, const value_type& b){return a.key().compare(b.key()) < 0;}); if (rhs_it == rhs.end() || rhs_it->key() != it->key() || rhs_it->value() != it->value()) { return false; } } return true; } private: json_object& operator=(const json_object&) = delete; }; // Preserve order template <class KeyT,class Json> class json_object<KeyT,Json,true> : public Json_object_<KeyT,Json> { public: using typename Json_object_<KeyT,Json>::allocator_type; using typename Json_object_<KeyT,Json>::char_type; using typename Json_object_<KeyT,Json>::char_allocator_type; using typename Json_object_<KeyT,Json>::key_storage_type; using typename Json_object_<KeyT,Json>::string_view_type; using typename Json_object_<KeyT,Json>::value_type; using typename Json_object_<KeyT,Json>::kvp_allocator_type; using typename Json_object_<KeyT,Json>::object_storage_type; using typename Json_object_<KeyT,Json>::iterator; using typename Json_object_<KeyT,Json>::const_iterator; using Json_object_<KeyT,Json>::get_allocator; json_object() : Json_object_<KeyT,Json>() { } json_object(const allocator_type& allocator) : Json_object_<KeyT,Json>(allocator) { } json_object(const json_object& val) : Json_object_<KeyT,Json>(val) { } json_object(json_object&& val) : Json_object_<KeyT,Json>(std::forward<json_object&&>(val)) { } json_object(const json_object& val, const allocator_type& allocator) : Json_object_<KeyT,Json>(val,allocator) { } json_object(json_object&& val,const allocator_type& allocator) : Json_object_<KeyT,Json>(std::forward<json_object&&>(val),allocator) { } json_object(std::initializer_list<typename Json::array> init) : Json_object_<KeyT,Json>() { for (const auto& element : init) { if (element.size() != 2 || !element[0].is_string()) { JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list"); break; } } for (auto& element : init) { set(element[0].as_string_view(), std::move(element[1])); } } json_object(std::initializer_list<typename Json::array> init, const allocator_type& allocator) : Json_object_<KeyT,Json>(allocator) { for (const auto& element : init) { if (element.size() != 2 || !element[0].is_string()) { JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list"); break; } } for (auto& element : init) { set(element[0].as_string_view(), std::move(element[1])); } } void swap(json_object& val) { Json_object_<KeyT,Json>::swap(val); } iterator begin() { return this->members_.begin(); } iterator end() { return this->members_.end(); } const_iterator begin() const { return this->members_.begin(); } const_iterator end() const { return this->members_.end(); } size_t size() const {return this->members_.size();} size_t capacity() const {return this->members_.capacity();} void clear() {this->members_.clear();} void shrink_to_fit() { for (size_t i = 0; i < this->members_.size(); ++i) { this->members_[i].shrink_to_fit(); } this->members_.shrink_to_fit(); } void reserve(size_t n) {this->members_.reserve(n);} Json& at(size_t i) { if (i >= this->members_.size()) { JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript"); } return this->members_[i].value(); } const Json& at(size_t i) const { if (i >= this->members_.size()) { JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript"); } return this->members_[i].value(); } iterator find(string_view_type name) { return std::find_if(this->members_.begin(),this->members_.end(), [name](const value_type& kvp){return kvp.key() == name;}); } const_iterator find(string_view_type name) const { return std::find_if(this->members_.begin(),this->members_.end(), [name](const value_type& kvp){return kvp.key() == name;}); } void erase(iterator first, iterator last) { this->members_.erase(first,last); } void erase(string_view_type name) { auto it = std::find_if(this->members_.begin(),this->members_.end(), [name](const value_type& kvp){return kvp.key() == name;}); if (it != this->members_.end()) { this->members_.erase(it); } } template<class InputIt, class UnaryPredicate> void insert(InputIt first, InputIt last, UnaryPredicate pred) { size_t count = std::distance(first,last); this->members_.reserve(this->members_.size() + count); for (auto s = first; s != last; ++s) { this->members_.emplace_back(pred(*s)); } auto it = last_wins_unique_sequence(this->members_.begin(), this->members_.end(), [](const value_type& a, const value_type& b){ return a.key().compare(b.key());}); this->members_.erase(it,this->members_.end()); } template <class T, class U=allocator_type, typename std::enable_if<is_stateless<U>::value >::type* = nullptr> void set(string_view_type name, T&& value) { auto it = std::find_if(this->members_.begin(),this->members_.end(), [name](const value_type& a){return a.key() == name;}); if (it == this->members_.end()) { this->members_.emplace_back(key_storage_type(name.begin(),name.end()), std::forward<T&&>(value)); } else { it->value(Json(std::forward<T&&>(value))); } } template <class T, class U=allocator_type, typename std::enable_if<!is_stateless<U>::value >::type* = nullptr> void set(string_view_type name, T&& value) { auto it = std::find_if(this->members_.begin(),this->members_.end(), [name](const value_type& a){return a.key() == name;}); if (it == this->members_.end()) { this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()), std::forward<T&&>(value),get_allocator()); } else { it->value(Json(std::forward<T&&>(value),get_allocator())); } } template <class T, class U=allocator_type, typename std::enable_if<is_stateless<U>::value >::type* = nullptr> void set_(key_storage_type&& name, T&& value) { string_view_type s(name.data(),name.size()); auto it = std::find_if(this->members_.begin(),this->members_.end(), [s](const value_type& a){return a.key().compare(s) == 0;}); if (it == this->members_.end()) { this->members_.emplace_back(std::forward<key_storage_type&&>(name), std::forward<T&&>(value)); } else { it->value(Json(std::forward<T&&>(value))); } } template <class T, class U=allocator_type, typename std::enable_if<!is_stateless<U>::value >::type* = nullptr> void set_(key_storage_type&& name, T&& value) { string_view_type s(name.data(),name.size()); auto it = std::find_if(this->members_.begin(),this->members_.end(), [s](const value_type& a){return a.key().compare(s) == 0;}); if (it == this->members_.end()) { this->members_.emplace_back(std::forward<key_storage_type&&>(name), std::forward<T&&>(value),get_allocator()); } else { it->value(Json(std::forward<T&&>(value),get_allocator())); } } template <class T, class U=allocator_type> typename std::enable_if<is_stateless<U>::value,iterator>::type set(iterator hint, string_view_type name, T&& value) { iterator it = hint; if (it == this->members_.end()) { this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()), std::forward<T&&>(value)); it = this->members_.begin() + (this->members_.size() - 1); } else if (it->key() == name) { it->value(Json(std::forward<T&&>(value))); } else { it = this->members_.emplace(it, key_storage_type(name.begin(),name.end()), std::forward<T&&>(value)); } return it; } template <class T, class U=allocator_type> typename std::enable_if<!is_stateless<U>::value,iterator>::type set(iterator hint, string_view_type name, T&& value) { iterator it = hint; if (it == this->members_.end()) { this->members_.emplace_back(key_storage_type(name.begin(),name.end(),get_allocator()), std::forward<T&&>(value),get_allocator()); it = this->members_.begin() + (this->members_.size() - 1); } else if (it->key() == name) { it->value(Json(std::forward<T&&>(value),get_allocator())); } else { it = this->members_.emplace(it, key_storage_type(name.begin(),name.end(),get_allocator()), std::forward<T&&>(value),get_allocator()); } return it; } template <class T, class U=allocator_type> typename std::enable_if<is_stateless<U>::value,iterator>::type set_(iterator hint, key_storage_type&& name, T&& value) { iterator it = hint; if (it == this->members_.end()) { this->members_.emplace_back(std::forward<key_storage_type&&>(name), std::forward<T&&>(value)); it = this->members_.begin() + (this->members_.size() - 1); } else if (it->key() == name) { it->value(Json(std::forward<T&&>(value))); } else { it = this->members_.emplace(it, std::forward<key_storage_type&&>(name), std::forward<T&&>(value)); } return it; } template <class T, class U=allocator_type> typename std::enable_if<!is_stateless<U>::value,iterator>::type set_(iterator hint, key_storage_type&& name, T&& value) { iterator it = hint; if (it == this->members_.end()) { this->members_.emplace_back(std::forward<key_storage_type&&>(name), std::forward<T&&>(value), get_allocator()); it = this->members_.begin() + (this->members_.size() - 1); } else if (it->key() == name) { it->value(Json(std::forward<T&&>(value), get_allocator())); } else { it = this->members_.emplace(it, std::forward<key_storage_type&&>(name), std::forward<T&&>(value), get_allocator()); } return it; } bool operator==(const json_object& rhs) const { if (size() != rhs.size()) { return false; } for (auto it = this->members_.begin(); it != this->members_.end(); ++it) { auto rhs_it = std::find_if(rhs.begin(),rhs.end(), [it](const value_type& a){return a.key() == it->key();}); if (rhs_it == rhs.end() || rhs_it->key() != it->key() || rhs_it->value() != it->value()) { return false; } } return true; } private: json_object& operator=(const json_object&) = delete; }; } #endif
43,948
13,787
#ifndef TEXTNET_LAYER_RESHAPE_LAYER_INL_HPP_ #define TEXTNET_LAYER_RESHAPE_LAYER_INL_HPP_ #include <iostream> #include <fstream> #include <sstream> #include <set> #include <mshadow/tensor.h> #include "../layer.h" #include "../op.h" namespace textnet { namespace layer { template<typename xpu> class ReshapeLayer : public Layer<xpu>{ public: ReshapeLayer(LayerType type) { this->layer_type = type; } virtual ~ReshapeLayer(void) {} virtual int BottomNodeNum() { return 1; } virtual int TopNodeNum() { return 1; } virtual int ParamNodeNum() { return 0; } void PrintTensor(const char * name, mshadow::Tensor<xpu, 1> x) { mshadow::Shape<1> s = x.shape_; cout << name << " shape " << s[0] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { cout << x[d1] << " "; } cout << endl; } void PrintTensor(const char * name, mshadow::Tensor<xpu, 2> x) { mshadow::Shape<2> s = x.shape_; cout << name << " shape " << s[0] << "x" << s[1] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { for (unsigned int d2 = 0; d2 < s[1]; ++d2) { cout << x[d1][d2] << " "; } cout << endl; } cout << endl; } void PrintTensor(const char * name, mshadow::Tensor<xpu, 3> x) { mshadow::Shape<3> s = x.shape_; cout << name << " shape " << s[0] << "x" << s[1] << "x" << s[2] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { for (unsigned int d2 = 0; d2 < s[1]; ++d2) { for (unsigned int d3 = 0; d3 < s[2]; ++d3) { cout << x[d1][d2][d3] << " "; } cout << ";"; } cout << endl; } } void PrintTensor(const char * name, mshadow::Tensor<xpu, 4> x) { mshadow::Shape<4> s = x.shape_; cout << name << " shape " << s[0] << "x" << s[1] << "x" << s[2] << "x" << s[3] << endl; for (unsigned int d1 = 0; d1 < s[0]; ++d1) { for (unsigned int d2 = 0; d2 < s[1]; ++d2) { for (unsigned int d3 = 0; d3 < s[2]; ++d3) { for (unsigned int d4 = 0; d4 < s[3]; ++d4) { cout << x[d1][d2][d3][d4] << " "; } cout << "|"; } cout << ";"; } cout << endl; } } virtual void Require() { // default value, just set the value you want this->defaults["D0"] = SettingV(0); this->defaults["D1"] = SettingV(0); this->defaults["D2"] = SettingV(0); this->defaults["D3"] = SettingV(0); this->defaults["L0"] = SettingV(0); this->defaults["L1"] = SettingV(0); // require value, set to SettingV(), // it will force custom to set in config Layer<xpu>::Require(); } virtual void SetupLayer(std::map<std::string, SettingV> &setting, const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top, mshadow::Random<xpu> *prnd) { Layer<xpu>::SetupLayer(setting, bottom, top, prnd); utils::Check(bottom.size() == BottomNodeNum(), "ReshapeLayer:bottom size problem."); utils::Check(top.size() == TopNodeNum(), "ReshapeLayer:top size problem."); // Dx represents data axis x shape // Lx represents length axis x shape // if set to 0, copy the shape size as bottom axis // if set to -1, automatically compute shape. // So only one -1 can be set, and its value can be derived from other values. D0 = setting["D0"].iVal(); D1 = setting["D1"].iVal(); D2 = setting["D2"].iVal(); D3 = setting["D3"].iVal(); L0 = setting["L0"].iVal(); L1 = setting["L1"].iVal(); } virtual void Reshape(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top, bool show_info = false) { utils::Check(bottom.size() == BottomNodeNum(), "ReshapeLayer:bottom size problem."); utils::Check(top.size() == TopNodeNum(), "ReshapeLayer:top size problem."); in_data_shape = bottom[0]->data.shape_; in_len_shape = bottom[0]->length.shape_; out_data_shape[0] = D0==0 ? in_data_shape[0] : D0; out_data_shape[1] = D1==0 ? in_data_shape[1] : D1; out_data_shape[2] = D2==0 ? in_data_shape[2] : D2; out_data_shape[3] = D3==0 ? in_data_shape[3] : D3; out_len_shape[0] = L0==0 ? in_len_shape[0] : L0; out_len_shape[1] = L1==0 ? in_len_shape[1] : L1; if (D0 == -1) { out_data_shape[0] = 1; out_data_shape[0] = in_data_shape.Size() / out_data_shape.Size(); } else if (D1 == -1) { out_data_shape[1] = 1; out_data_shape[1] = in_data_shape.Size() / out_data_shape.Size(); } else if (D2 == -1) { out_data_shape[2] = 1; out_data_shape[2] = in_data_shape.Size() / out_data_shape.Size(); } else if (D3 == -1) { out_data_shape[3] = 1; out_data_shape[3] = in_data_shape.Size() / out_data_shape.Size(); } if (L0 == -1) { out_len_shape[0] = 1; out_len_shape[0] = in_len_shape.Size() / out_len_shape.Size(); } else if (L1 == -1) { out_len_shape[1] = 1; out_len_shape[1] = in_len_shape.Size() / out_len_shape.Size(); } utils::Check(out_data_shape.Size() == in_data_shape.Size(), "ReshapeLayer: data shape mismatch."); utils::Check(out_len_shape.Size() == in_len_shape.Size(), "ReshapeLayer: length shape mismatch."); top[0]->Resize(out_data_shape, out_len_shape, true); if (show_info) { bottom[0]->PrintShape("bottom0"); top[0]->PrintShape("top0"); } } virtual void CheckReshape(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top) { // Check for reshape bool need_reshape = false; if (in_data_shape.Size() != bottom[0]->data.shape_.Size()) { need_reshape = true; } // Do reshape if (need_reshape) { this->Reshape(bottom, top); } } virtual void Forward(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top) { using namespace mshadow::expr; mshadow::Tensor<xpu, 1> bottom0_data = bottom[0]->data_d1(); mshadow::Tensor<xpu, 1> bottom0_len = bottom[0]->length_d1(); mshadow::Tensor<xpu, 1> top0_data = top[0]->data_d1(); mshadow::Tensor<xpu, 1> top0_len = top[0]->length_d1(); top0_data = F<op::identity>(bottom0_data); top0_len = F<op::identity>(bottom0_len); } virtual void Backprop(const std::vector<Node<xpu>*> &bottom, const std::vector<Node<xpu>*> &top) { using namespace mshadow::expr; mshadow::Tensor<xpu, 1> bottom0_diff = bottom[0]->diff_d1(); mshadow::Tensor<xpu, 1> top0_diff = top[0]->diff_d1(); bottom0_diff = F<op::identity>(top0_diff); } protected: int D0; int D1; int D2; int D3; int L0; int L1; mshadow::Shape<4> in_data_shape; mshadow::Shape<2> in_len_shape; mshadow::Shape<4> out_data_shape; mshadow::Shape<2> out_len_shape; }; } // namespace layer } // namespace textnet #endif
7,113
2,748
#include <stdio.h> #include <stdlib.h> #include <bits/stdc++.h> using namespace std; char square[10] = { 'o', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; int choice, player; int checkForWin(); void displayBoard(); void markBoard(char mark); int main() { int gameStatus; char mark; player = 1; do { displayBoard(); // change turns player = (player % 2) ? 1 : 2; // get input cout<< "Player " <<player <<" enter a number: "; cin >> choice; // set the correct character based on player turn mark = (player == 1) ? 'X' : 'O'; // set board based on user choice or invalid choice markBoard(mark); gameStatus = checkForWin(); player++; } while (gameStatus == -1); if (gameStatus == 1) cout<< "==>\aPlayer "<<--player <<" wins"; else cout<< "==>\aGame draw"; return 0; } int checkForWin() { int returnValue = 0; if (square[1] == square[2] && square[2] == square[3]) { returnValue = 1; } else if (square[4] == square[5] && square[5] == square[6]) returnValue = 1; else if (square[7] == square[8] && square[8] == square[9]) returnValue = 1; else if (square[1] == square[4] && square[4] == square[7]) returnValue = 1; else if (square[2] == square[5] && square[5] == square[8]) returnValue = 1; else if (square[3] == square[6] && square[6] == square[9]) returnValue = 1; else if (square[1] == square[5] && square[5] == square[9]) returnValue = 1; else if (square[3] == square[5] && square[5] == square[7]) returnValue = 1; else if (square[1] != '1' && square[2] != '2' && square[3] != '3' && square[4] != '4' && square[5] != '5' && square[6] != '6' && square[7] != '7' && square[8] != '8' && square[9] != '9') returnValue = 0; else returnValue = -1; return returnValue; } void displayBoard() { system("cls"); cout<< "\n\n\tTic Tac Toe\n\n"; cout<<"Player 1 (X) - Player 2 (O)\n\n\n"; cout<<" | | \n"; cout<<" " << square[1] << " | " << square[2] << " | " << square[3] <<endl; cout<<"_____|_____|_____\n"; cout<<" | | \n"; cout<<" " << square[4] << " | " << square[5] << " | " << square[6]<< endl; cout<<"_____|_____|_____\n"; cout<<" | | \n"; cout<<" " << square[7] << " | " << square[8] << " | " << square[9]<< endl; cout<<" | | \n"; } void markBoard(char mark) { if (choice == 1 && square[1] == '1') square[1] = mark; else if (choice == 2 && square[2] == '2') square[2] = mark; else if (choice == 3 && square[3] == '3') square[3] = mark; else if (choice == 4 && square[4] == '4') square[4] = mark; else if (choice == 5 && square[5] == '5') square[5] = mark; else if (choice == 6 && square[6] == '6') square[6] = mark; else if (choice == 7 && square[7] == '7') square[7] = mark; else if (choice == 8 && square[8] == '8') square[8] = mark; else if (choice == 9 && square[9] == '9') square[9] = mark; else { cout<< "Invalid move "; player--; } }
3,312
1,279
#include<iostream> #include<cstdio> #include<cmath> using namespace std; int main() { double m,n,p,k; while(scanf("%lf %lf",&n,&p)!=EOF) { k=pow(p,1/n); printf("%0.lf\n",k); } return 0; }
224
105
/* * Copyright 2016-2020 JetBrains s.r.o. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ #pragma once #include <cstdlib> /* Check the given pointer to see if it's null. If so, fail, printing to stderr that insufficient memory is available. */ template <typename T> static inline T* check_allocation(T* value) { if (value == nullptr) { fprintf(stderr, "Insufficient memory available\n"); abort(); } return value; }
512
170
#include "cpshm.h" #include <stdio.h> #include "cpstring.h" const char* shm_id = "test_nwdl_shm"; struct TEST_SHM_DATA { char str[128]; int len; }; void print_data(TEST_SHM_DATA* data) { printf("TEST_SHM_DATA::str: %s \nTEST_SHM_DATA::len: %d\n\n", data->str, data->len); } int test_1() { cpshm_t shm_t = 0; int ret = -1; ret = cpshm_exist(shm_id); if (CPDL_SUCCESS != ret) { ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t); if (CPDL_SUCCESS != ret) { return -1; } ret = cpshm_exist(shm_id); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t); return -2; } } else { ret = cpshm_map(shm_id, &shm_t); if (CPDL_SUCCESS != ret) { return -1; } } TEST_SHM_DATA* data = 0; unsigned int len = 0; ret = cpshm_data(shm_t, (cpshm_d*)&data, &len); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t);; return -4; } strlcpy(data->str, "test_1 shm by nonwill", 128); data->len = strlen(data->str); print_data(data); ret = cpshm_unmap(shm_t); data = 0; ret = cpshm_exist(shm_id); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t); return -2; } cpshm_t shm_t2 = 0; ret = cpshm_map(shm_id, &shm_t2); ret = cpshm_data(shm_t2, (cpshm_d*)&data, &len); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t2); ret = cpshm_close(&shm_t); return -5; } print_data(data); ret = cpshm_close(&shm_t2); ret = cpshm_close(&shm_t); return 1; } int test_2() { cpshm_t shm_t = 0; int ret = -1; ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t); if (CPDL_SUCCESS != ret) { return -1; } TEST_SHM_DATA* data = 0; unsigned int len = 0; ret = cpshm_data(shm_t, (cpshm_d*)&data, &len); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t); return -5; } strlcpy(data->str, "test_2 shm by nonwill", 128); data->len = strlen(data->str); print_data(data); ret = cpshm_close(&shm_t); shm_t = 0; data = 0; ret = cpshm_exist(shm_id); if (CPDL_SUCCESS == ret) { //ret = cpshm_close(&shm_t); return -2; } ret = cpshm_map(shm_id, &shm_t); if (CPDL_SUCCESS == ret) { ret = cpshm_close(&shm_t); return -3; } ret = cpshm_data(shm_t, (cpshm_d*)&data, &len); if (CPDL_SUCCESS == ret) { print_data(data); ret = cpshm_close(&shm_t); return -4; } return 1; } int test_3() { cpshm_t shm_t = 0; int ret = -1; ret = cpshm_exist(shm_id); if (CPDL_SUCCESS != ret) { ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t); if (CPDL_SUCCESS != ret) { return -1; } ret = cpshm_exist(shm_id); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t); return -2; } } TEST_SHM_DATA* data = 0; unsigned int len = 0; ret = cpshm_data(shm_t, (cpshm_d*)&data, &len); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t);; return -4; } strlcpy(data->str, "test_3 shm by nonwill", 128); data->len = strlen(data->str); print_data(data); cpshm_t shm_t2 = 0; ret = cpshm_map(shm_id, &shm_t2); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t); return -5; } ret = cpshm_close(&shm_t); ret = cpshm_data(shm_t2, (cpshm_d*)&data, &len); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t2); return -5; } print_data(data); ret = cpshm_close(&shm_t2); return 1; } void test_4() { cpshm_t shm_t = 0; int ret = -1; ret = cpshm_exist(shm_id); if (CPDL_SUCCESS != ret) { ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t); if (CPDL_SUCCESS != ret) { return ; } ret = cpshm_exist(shm_id); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t); return ; } } cpshm_t shm_t2 = 0; cpshm_t shm_t3 = 0; ret = cpshm_map(shm_id, &shm_t2); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t); return ; } ret = cpshm_close(&shm_t2); ret = cpshm_map(shm_id, &shm_t3); if (CPDL_SUCCESS != ret) { ret = cpshm_close(&shm_t); return ; } else { ret = cpshm_close(&shm_t3); } ret = cpshm_exist(shm_id); if (CPDL_SUCCESS != ret) { printf("test_4 cpshm_exist : no shm exist\n"); } ret = cpshm_close(&shm_t); } int main(int /*argc*/, char* /*argv*/[]) { test_1(); test_2(); test_3(); test_4(); #ifdef _NWCP_WIN32 system("pause"); #endif return 1; }
5,277
2,300
// Name: SeaOfThieves, Version: 2.0.23 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- void UTaleQuestMultiTargetCompassServiceDesc::AfterRead() { UTaleQuestToolServiceDesc::AfterRead(); READ_PTR_FULL(CompassDesc, UClass); } void UTaleQuestMultiTargetCompassServiceDesc::BeforeDelete() { UTaleQuestToolServiceDesc::BeforeDelete(); DELE_PTR_FULL(CompassDesc); } void UTaleQuestSetCompassTargetToTargetStep::AfterRead() { UTaleQuestStep::AfterRead(); } void UTaleQuestSetCompassTargetToTargetStep::BeforeDelete() { UTaleQuestStep::BeforeDelete(); } void UTaleQuestSetCompassTargetBaseStepDesc::AfterRead() { UTaleQuestStepDesc::AfterRead(); } void UTaleQuestSetCompassTargetBaseStepDesc::BeforeDelete() { UTaleQuestStepDesc::BeforeDelete(); } void UTaleQuestSetCompassTargetToActorStepDesc::AfterRead() { UTaleQuestSetCompassTargetBaseStepDesc::AfterRead(); } void UTaleQuestSetCompassTargetToActorStepDesc::BeforeDelete() { UTaleQuestSetCompassTargetBaseStepDesc::BeforeDelete(); } void UTaleQuestSetCompassTargetToPointStepDesc::AfterRead() { UTaleQuestSetCompassTargetBaseStepDesc::AfterRead(); } void UTaleQuestSetCompassTargetToPointStepDesc::BeforeDelete() { UTaleQuestSetCompassTargetBaseStepDesc::BeforeDelete(); } void AMultiTargetEnchantedCompass::AfterRead() { ACompass::AfterRead(); READ_PTR_FULL(InventoryItem, UInventoryItemComponent); } void AMultiTargetEnchantedCompass::BeforeDelete() { ACompass::BeforeDelete(); DELE_PTR_FULL(InventoryItem); } // Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.GetFloatMax // (Final, Native, Public, BlueprintCallable, BlueprintPure) // Parameters: // float ReturnValue (ConstParm, Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash) float APrototypeMultiTargetEnchantedCompass::GetFloatMax() { static auto fn = UObject::FindObject<UFunction>("Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.GetFloatMax"); APrototypeMultiTargetEnchantedCompass_GetFloatMax_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.CalculateDesiredYaw // (Event, Public, HasOutParms, HasDefaults, BlueprintEvent, Const) // Parameters: // struct FRotator CompassRotation (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor) // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash) float APrototypeMultiTargetEnchantedCompass::CalculateDesiredYaw(const struct FRotator& CompassRotation) { static auto fn = UObject::FindObject<UFunction>("Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.CalculateDesiredYaw"); APrototypeMultiTargetEnchantedCompass_CalculateDesiredYaw_Params params; params.CompassRotation = CompassRotation; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.BP_GetTargetLocations // (Final, Native, Public, BlueprintCallable, BlueprintPure) // Parameters: // TArray<struct FVector> ReturnValue (ConstParm, Parm, OutParm, ZeroConstructor, ReturnParm) TArray<struct FVector> APrototypeMultiTargetEnchantedCompass::BP_GetTargetLocations() { static auto fn = UObject::FindObject<UFunction>("Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.BP_GetTargetLocations"); APrototypeMultiTargetEnchantedCompass_BP_GetTargetLocations_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } void APrototypeMultiTargetEnchantedCompass::AfterRead() { AMultiTargetEnchantedCompass::AfterRead(); } void APrototypeMultiTargetEnchantedCompass::BeforeDelete() { AMultiTargetEnchantedCompass::BeforeDelete(); } void UTaleQuestMultiTargetCompassAddTrackedLocationStep::AfterRead() { UTaleQuestStep::AfterRead(); READ_PTR_FULL(Desc, UTaleQuestMultiTargetCompassAddTrackedLocationStepDesc); } void UTaleQuestMultiTargetCompassAddTrackedLocationStep::BeforeDelete() { UTaleQuestStep::BeforeDelete(); DELE_PTR_FULL(Desc); } void UTaleQuestMultiTargetCompassAddTrackedLocationStepDesc::AfterRead() { UTaleQuestStepDesc::AfterRead(); } void UTaleQuestMultiTargetCompassAddTrackedLocationStepDesc::BeforeDelete() { UTaleQuestStepDesc::BeforeDelete(); } void UTaleQuestMultiTargetCompassRemoveTrackedLocationStep::AfterRead() { UTaleQuestStep::AfterRead(); } void UTaleQuestMultiTargetCompassRemoveTrackedLocationStep::BeforeDelete() { UTaleQuestStep::BeforeDelete(); } void UTaleQuestMultiTargetCompassRemoveTrackedLocationStepDesc::AfterRead() { UTaleQuestStepDesc::AfterRead(); } void UTaleQuestMultiTargetCompassRemoveTrackedLocationStepDesc::BeforeDelete() { UTaleQuestStepDesc::BeforeDelete(); } void UTaleQuestMultiTargetCompassService::AfterRead() { UTaleQuestToolService::AfterRead(); } void UTaleQuestMultiTargetCompassService::BeforeDelete() { UTaleQuestToolService::BeforeDelete(); } } #ifdef _MSC_VER #pragma pack(pop) #endif
5,722
1,911
// Copyright 2016 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 "modules/webgl/WebGLGetBufferSubDataAsync.h" #include "core/dom/DOMException.h" #include "gpu/GLES2/gl2extchromium.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "modules/webgl/WebGL2RenderingContextBase.h" namespace blink { WebGLGetBufferSubDataAsync::WebGLGetBufferSubDataAsync( WebGLRenderingContextBase* context) : WebGLExtension(context) {} WebGLExtensionName WebGLGetBufferSubDataAsync::name() const { return WebGLGetBufferSubDataAsyncName; } WebGLGetBufferSubDataAsync* WebGLGetBufferSubDataAsync::create( WebGLRenderingContextBase* context) { return new WebGLGetBufferSubDataAsync(context); } bool WebGLGetBufferSubDataAsync::supported(WebGLRenderingContextBase* context) { return true; } const char* WebGLGetBufferSubDataAsync::extensionName() { return "WEBGL_get_buffer_sub_data_async"; } ScriptPromise WebGLGetBufferSubDataAsync::getBufferSubDataAsync( ScriptState* scriptState, GLenum target, GLintptr srcByteOffset, DOMArrayBufferView* dstData, GLuint dstOffset, GLuint length) { ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); WebGLExtensionScopedContext scoped(this); if (scoped.isLost()) { DOMException* exception = DOMException::create(InvalidStateError, "context lost"); resolver->reject(exception); return promise; } WebGL2RenderingContextBase* context = nullptr; { WebGLRenderingContextBase* contextBase = scoped.context(); DCHECK_GE(contextBase->version(), 2u); context = static_cast<WebGL2RenderingContextBase*>(contextBase); } WebGLBuffer* sourceBuffer = nullptr; void* destinationDataPtr = nullptr; long long destinationByteLength = 0; const char* message = context->validateGetBufferSubData( __FUNCTION__, target, srcByteOffset, dstData, dstOffset, length, &sourceBuffer, &destinationDataPtr, &destinationByteLength); if (message) { // If there was a GL error, it was already synthesized in // validateGetBufferSubData, so it's not done here. DOMException* exception = DOMException::create(InvalidStateError, message); resolver->reject(exception); return promise; } message = context->validateGetBufferSubDataBounds( __FUNCTION__, sourceBuffer, srcByteOffset, destinationByteLength); if (message) { // If there was a GL error, it was already synthesized in // validateGetBufferSubDataBounds, so it's not done here. DOMException* exception = DOMException::create(InvalidStateError, message); resolver->reject(exception); return promise; } // If the length of the copy is zero, this is a no-op. if (!destinationByteLength) { resolver->resolve(dstData); return promise; } GLuint queryID; context->contextGL()->GenQueriesEXT(1, &queryID); context->contextGL()->BeginQueryEXT(GL_COMMANDS_ISSUED_CHROMIUM, queryID); void* mappedData = context->contextGL()->GetBufferSubDataAsyncCHROMIUM( target, srcByteOffset, destinationByteLength); context->contextGL()->EndQueryEXT(GL_COMMANDS_ISSUED_CHROMIUM); if (!mappedData) { DOMException* exception = DOMException::create(InvalidStateError, "Out of memory"); resolver->reject(exception); return promise; } auto callbackObject = new WebGLGetBufferSubDataAsyncCallback( context, resolver, mappedData, queryID, dstData, destinationDataPtr, destinationByteLength); context->registerGetBufferSubDataAsyncCallback(callbackObject); auto callback = WTF::bind(&WebGLGetBufferSubDataAsyncCallback::resolve, wrapPersistent(callbackObject)); context->drawingBuffer()->contextProvider()->signalQuery( queryID, convertToBaseCallback(std::move(callback))); return promise; } WebGLGetBufferSubDataAsyncCallback::WebGLGetBufferSubDataAsyncCallback( WebGL2RenderingContextBase* context, ScriptPromiseResolver* promiseResolver, void* shmReadbackResultData, GLuint commandsIssuedQueryID, DOMArrayBufferView* destinationArrayBufferView, void* destinationDataPtr, long long destinationByteLength) : m_context(context), m_promiseResolver(promiseResolver), m_shmReadbackResultData(shmReadbackResultData), m_commandsIssuedQueryID(commandsIssuedQueryID), m_destinationArrayBufferView(destinationArrayBufferView), m_destinationDataPtr(destinationDataPtr), m_destinationByteLength(destinationByteLength) { DCHECK(shmReadbackResultData); DCHECK(destinationDataPtr); } void WebGLGetBufferSubDataAsyncCallback::destroy() { DCHECK(m_shmReadbackResultData); m_context->contextGL()->FreeSharedMemory(m_shmReadbackResultData); m_shmReadbackResultData = nullptr; DOMException* exception = DOMException::create(InvalidStateError, "Context lost or destroyed"); m_promiseResolver->reject(exception); } void WebGLGetBufferSubDataAsyncCallback::resolve() { if (!m_context || !m_shmReadbackResultData) { DOMException* exception = DOMException::create(InvalidStateError, "Context lost or destroyed"); m_promiseResolver->reject(exception); return; } if (m_destinationArrayBufferView->buffer()->isNeutered()) { DOMException* exception = DOMException::create( InvalidStateError, "ArrayBufferView became invalid asynchronously"); m_promiseResolver->reject(exception); return; } memcpy(m_destinationDataPtr, m_shmReadbackResultData, m_destinationByteLength); // TODO(kainino): What would happen if the DOM was suspended when the // promise became resolved? Could another JS task happen between the memcpy // and the promise resolution task, which would see the wrong data? m_promiseResolver->resolve(m_destinationArrayBufferView); m_context->contextGL()->DeleteQueriesEXT(1, &m_commandsIssuedQueryID); this->destroy(); m_context->unregisterGetBufferSubDataAsyncCallback(this); } DEFINE_TRACE(WebGLGetBufferSubDataAsyncCallback) { visitor->trace(m_context); visitor->trace(m_promiseResolver); visitor->trace(m_destinationArrayBufferView); } } // namespace blink
6,313
1,876
// Copyright 2016 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/allocator/allocator_shim.h" #include <stdlib.h> #include <string.h> #include <atomic> #include <iomanip> #include <memory> #include <new> #include <sstream> #include <vector> #include "base/allocator/buildflags.h" #include "base/allocator/partition_allocator/partition_alloc.h" #include "base/memory/page_size.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" #include "base/threading/thread_local.h" #include "build/build_config.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_WIN) #include <malloc.h> #include <windows.h> #elif defined(OS_APPLE) #include <malloc/malloc.h> #include "base/allocator/allocator_interception_mac.h" #include "base/mac/mac_util.h" #include "third_party/apple_apsl/malloc.h" #else #include <malloc.h> #endif #if !defined(OS_WIN) #include <unistd.h> #endif #if defined(LIBC_GLIBC) extern "C" void* __libc_memalign(size_t align, size_t s); #endif namespace base { namespace allocator { namespace { using testing::_; using testing::MockFunction; // Special sentinel values used for testing GetSizeEstimate() interception. const char kTestSizeEstimateData[] = "test_value"; constexpr void* kTestSizeEstimateAddress = (void*)kTestSizeEstimateData; constexpr size_t kTestSizeEstimate = 1234; class AllocatorShimTest : public testing::Test { public: AllocatorShimTest() : testing::Test() {} static size_t Hash(const void* ptr) { return reinterpret_cast<uintptr_t>(ptr) % MaxSizeTracked(); } static void* MockAlloc(const AllocatorDispatch* self, size_t size, void* context) { if (instance_ && size < MaxSizeTracked()) ++(instance_->allocs_intercepted_by_size[size]); return self->next->alloc_function(self->next, size, context); } static void* MockAllocUnchecked(const AllocatorDispatch* self, size_t size, void* context) { if (instance_ && size < MaxSizeTracked()) ++(instance_->allocs_intercepted_by_size[size]); return self->next->alloc_unchecked_function(self->next, size, context); } static void* MockAllocZeroInit(const AllocatorDispatch* self, size_t n, size_t size, void* context) { const size_t real_size = n * size; if (instance_ && real_size < MaxSizeTracked()) ++(instance_->zero_allocs_intercepted_by_size[real_size]); return self->next->alloc_zero_initialized_function(self->next, n, size, context); } static void* MockAllocAligned(const AllocatorDispatch* self, size_t alignment, size_t size, void* context) { if (instance_) { if (size < MaxSizeTracked()) ++(instance_->aligned_allocs_intercepted_by_size[size]); if (alignment < MaxSizeTracked()) ++(instance_->aligned_allocs_intercepted_by_alignment[alignment]); } return self->next->alloc_aligned_function(self->next, alignment, size, context); } static void* MockRealloc(const AllocatorDispatch* self, void* address, size_t size, void* context) { if (instance_) { // Size 0xFEED a special sentinel for the NewHandlerConcurrency test. // Hitting it for the first time will cause a failure, causing the // invocation of the std::new_handler. if (size == 0xFEED) { if (!instance_->did_fail_realloc_0xfeed_once->Get()) { instance_->did_fail_realloc_0xfeed_once->Set(true); return nullptr; } return address; } if (size < MaxSizeTracked()) ++(instance_->reallocs_intercepted_by_size[size]); ++instance_->reallocs_intercepted_by_addr[Hash(address)]; } return self->next->realloc_function(self->next, address, size, context); } static void MockFree(const AllocatorDispatch* self, void* address, void* context) { if (instance_) { ++instance_->frees_intercepted_by_addr[Hash(address)]; } self->next->free_function(self->next, address, context); } static size_t MockGetSizeEstimate(const AllocatorDispatch* self, void* address, void* context) { // Special testing values for GetSizeEstimate() interception. if (address == kTestSizeEstimateAddress) return kTestSizeEstimate; return self->next->get_size_estimate_function(self->next, address, context); } static unsigned MockBatchMalloc(const AllocatorDispatch* self, size_t size, void** results, unsigned num_requested, void* context) { if (instance_) { instance_->batch_mallocs_intercepted_by_size[size] = instance_->batch_mallocs_intercepted_by_size[size] + num_requested; } return self->next->batch_malloc_function(self->next, size, results, num_requested, context); } static void MockBatchFree(const AllocatorDispatch* self, void** to_be_freed, unsigned num_to_be_freed, void* context) { if (instance_) { for (unsigned i = 0; i < num_to_be_freed; ++i) { ++instance_->batch_frees_intercepted_by_addr[Hash(to_be_freed[i])]; } } self->next->batch_free_function(self->next, to_be_freed, num_to_be_freed, context); } static void MockFreeDefiniteSize(const AllocatorDispatch* self, void* ptr, size_t size, void* context) { if (instance_) { ++instance_->frees_intercepted_by_addr[Hash(ptr)]; ++instance_->free_definite_sizes_intercepted_by_size[size]; } self->next->free_definite_size_function(self->next, ptr, size, context); } static void* MockAlignedMalloc(const AllocatorDispatch* self, size_t size, size_t alignment, void* context) { if (instance_ && size < MaxSizeTracked()) { ++instance_->aligned_mallocs_intercepted_by_size[size]; } return self->next->aligned_malloc_function(self->next, size, alignment, context); } static void* MockAlignedRealloc(const AllocatorDispatch* self, void* address, size_t size, size_t alignment, void* context) { if (instance_) { if (size < MaxSizeTracked()) ++instance_->aligned_reallocs_intercepted_by_size[size]; ++instance_->aligned_reallocs_intercepted_by_addr[Hash(address)]; } return self->next->aligned_realloc_function(self->next, address, size, alignment, context); } static void MockAlignedFree(const AllocatorDispatch* self, void* address, void* context) { if (instance_) { ++instance_->aligned_frees_intercepted_by_addr[Hash(address)]; } self->next->aligned_free_function(self->next, address, context); } static void NewHandler() { if (!instance_) return; instance_->num_new_handler_calls.fetch_add(1, std::memory_order_relaxed); } int32_t GetNumberOfNewHandlerCalls() { return instance_->num_new_handler_calls.load(std::memory_order_acquire); } void SetUp() override { allocs_intercepted_by_size.resize(MaxSizeTracked()); zero_allocs_intercepted_by_size.resize(MaxSizeTracked()); aligned_allocs_intercepted_by_size.resize(MaxSizeTracked()); aligned_allocs_intercepted_by_alignment.resize(MaxSizeTracked()); reallocs_intercepted_by_size.resize(MaxSizeTracked()); reallocs_intercepted_by_addr.resize(MaxSizeTracked()); frees_intercepted_by_addr.resize(MaxSizeTracked()); batch_mallocs_intercepted_by_size.resize(MaxSizeTracked()); batch_frees_intercepted_by_addr.resize(MaxSizeTracked()); free_definite_sizes_intercepted_by_size.resize(MaxSizeTracked()); aligned_mallocs_intercepted_by_size.resize(MaxSizeTracked()); aligned_reallocs_intercepted_by_size.resize(MaxSizeTracked()); aligned_reallocs_intercepted_by_addr.resize(MaxSizeTracked()); aligned_frees_intercepted_by_addr.resize(MaxSizeTracked()); did_fail_realloc_0xfeed_once = std::make_unique<ThreadLocalBoolean>(); num_new_handler_calls.store(0, std::memory_order_release); instance_ = this; #if defined(OS_APPLE) InitializeAllocatorShim(); #endif } void TearDown() override { instance_ = nullptr; #if defined(OS_APPLE) UninterceptMallocZonesForTesting(); #endif } static size_t MaxSizeTracked() { #if defined(OS_IOS) // TODO(crbug.com/1077271): 64-bit iOS uses a page size that is larger than // SystemPageSize(), causing this test to make larger allocations, relative // to SystemPageSize(). return 6 * base::SystemPageSize(); #else return 2 * base::SystemPageSize(); #endif } protected: std::vector<size_t> allocs_intercepted_by_size; std::vector<size_t> zero_allocs_intercepted_by_size; std::vector<size_t> aligned_allocs_intercepted_by_size; std::vector<size_t> aligned_allocs_intercepted_by_alignment; std::vector<size_t> reallocs_intercepted_by_size; std::vector<size_t> reallocs_intercepted_by_addr; std::vector<size_t> frees_intercepted_by_addr; std::vector<size_t> batch_mallocs_intercepted_by_size; std::vector<size_t> batch_frees_intercepted_by_addr; std::vector<size_t> free_definite_sizes_intercepted_by_size; std::vector<size_t> aligned_mallocs_intercepted_by_size; std::vector<size_t> aligned_reallocs_intercepted_by_size; std::vector<size_t> aligned_reallocs_intercepted_by_addr; std::vector<size_t> aligned_frees_intercepted_by_addr; std::unique_ptr<ThreadLocalBoolean> did_fail_realloc_0xfeed_once; std::atomic<uint32_t> num_new_handler_calls; private: static AllocatorShimTest* instance_; }; struct TestStruct1 { uint32_t ignored; uint8_t ignored_2; }; struct TestStruct2 { uint64_t ignored; uint8_t ignored_3; }; class ThreadDelegateForNewHandlerTest : public PlatformThread::Delegate { public: explicit ThreadDelegateForNewHandlerTest(WaitableEvent* event) : event_(event) {} void ThreadMain() override { event_->Wait(); void* temp = malloc(1); void* res = realloc(temp, 0xFEED); EXPECT_EQ(temp, res); } private: WaitableEvent* event_; }; AllocatorShimTest* AllocatorShimTest::instance_ = nullptr; AllocatorDispatch g_mock_dispatch = { &AllocatorShimTest::MockAlloc, /* alloc_function */ &AllocatorShimTest::MockAllocUnchecked, /* alloc_unchecked_function */ &AllocatorShimTest::MockAllocZeroInit, /* alloc_zero_initialized_function */ &AllocatorShimTest::MockAllocAligned, /* alloc_aligned_function */ &AllocatorShimTest::MockRealloc, /* realloc_function */ &AllocatorShimTest::MockFree, /* free_function */ &AllocatorShimTest::MockGetSizeEstimate, /* get_size_estimate_function */ &AllocatorShimTest::MockBatchMalloc, /* batch_malloc_function */ &AllocatorShimTest::MockBatchFree, /* batch_free_function */ &AllocatorShimTest::MockFreeDefiniteSize, /* free_definite_size_function */ &AllocatorShimTest::MockAlignedMalloc, /* aligned_malloc_function */ &AllocatorShimTest::MockAlignedRealloc, /* aligned_realloc_function */ &AllocatorShimTest::MockAlignedFree, /* aligned_free_function */ nullptr, /* next */ }; TEST_F(AllocatorShimTest, InterceptLibcSymbols) { InsertAllocatorDispatch(&g_mock_dispatch); void* alloc_ptr = malloc(19); ASSERT_NE(nullptr, alloc_ptr); ASSERT_GE(allocs_intercepted_by_size[19], 1u); void* zero_alloc_ptr = calloc(2, 23); ASSERT_NE(nullptr, zero_alloc_ptr); ASSERT_GE(zero_allocs_intercepted_by_size[2 * 23], 1u); #if !defined(OS_WIN) void* posix_memalign_ptr = nullptr; int res = posix_memalign(&posix_memalign_ptr, 256, 59); ASSERT_EQ(0, res); ASSERT_NE(nullptr, posix_memalign_ptr); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(posix_memalign_ptr) % 256); ASSERT_GE(aligned_allocs_intercepted_by_alignment[256], 1u); ASSERT_GE(aligned_allocs_intercepted_by_size[59], 1u); // (p)valloc() are not defined on Android. pvalloc() is a GNU extension, // valloc() is not in POSIX. #if !defined(OS_ANDROID) const size_t kPageSize = base::GetPageSize(); void* valloc_ptr = valloc(61); ASSERT_NE(nullptr, valloc_ptr); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(valloc_ptr) % kPageSize); ASSERT_GE(aligned_allocs_intercepted_by_alignment[kPageSize], 1u); ASSERT_GE(aligned_allocs_intercepted_by_size[61], 1u); #endif // !defined(OS_ANDROID) #endif // !OS_WIN #if !defined(OS_WIN) && !defined(OS_APPLE) void* memalign_ptr = memalign(128, 53); ASSERT_NE(nullptr, memalign_ptr); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(memalign_ptr) % 128); ASSERT_GE(aligned_allocs_intercepted_by_alignment[128], 1u); ASSERT_GE(aligned_allocs_intercepted_by_size[53], 1u); #if defined(OS_POSIX) && !defined(OS_ANDROID) void* pvalloc_ptr = pvalloc(67); ASSERT_NE(nullptr, pvalloc_ptr); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(pvalloc_ptr) % kPageSize); ASSERT_GE(aligned_allocs_intercepted_by_alignment[kPageSize], 1u); // pvalloc rounds the size up to the next page. ASSERT_GE(aligned_allocs_intercepted_by_size[kPageSize], 1u); #endif // defined(OS_POSIX) && !defined(OS_ANDROID) #endif // !OS_WIN && !OS_APPLE // See allocator_shim_override_glibc_weak_symbols.h for why we intercept // internal libc symbols. #if defined(LIBC_GLIBC) && \ (BUILDFLAG(USE_TCMALLOC) || BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)) void* libc_memalign_ptr = __libc_memalign(512, 56); ASSERT_NE(nullptr, memalign_ptr); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(libc_memalign_ptr) % 512); ASSERT_GE(aligned_allocs_intercepted_by_alignment[512], 1u); ASSERT_GE(aligned_allocs_intercepted_by_size[56], 1u); #endif char* realloc_ptr = static_cast<char*>(malloc(10)); strcpy(realloc_ptr, "foobar"); void* old_realloc_ptr = realloc_ptr; realloc_ptr = static_cast<char*>(realloc(realloc_ptr, 73)); ASSERT_GE(reallocs_intercepted_by_size[73], 1u); ASSERT_GE(reallocs_intercepted_by_addr[Hash(old_realloc_ptr)], 1u); ASSERT_EQ(0, strcmp(realloc_ptr, "foobar")); free(alloc_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(alloc_ptr)], 1u); free(zero_alloc_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(zero_alloc_ptr)], 1u); #if !defined(OS_WIN) && !defined(OS_APPLE) free(memalign_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(memalign_ptr)], 1u); #if defined(OS_POSIX) && !defined(OS_ANDROID) free(pvalloc_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(pvalloc_ptr)], 1u); #endif // defined(OS_POSIX) && !defined(OS_ANDROID) #endif // !OS_WIN && !OS_APPLE #if !defined(OS_WIN) free(posix_memalign_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(posix_memalign_ptr)], 1u); #if !defined(OS_ANDROID) free(valloc_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(valloc_ptr)], 1u); #endif // !defined(OS_ANDROID) #endif // !OS_WIN #if defined(LIBC_GLIBC) && \ (BUILDFLAG(USE_TCMALLOC) || BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)) free(libc_memalign_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(memalign_ptr)], 1u); #endif free(realloc_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(realloc_ptr)], 1u); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); void* non_hooked_ptr = malloc(4095); ASSERT_NE(nullptr, non_hooked_ptr); ASSERT_EQ(0u, allocs_intercepted_by_size[4095]); free(non_hooked_ptr); } // PartitionAlloc-Everywhere does not support batch_malloc / batch_free. #if defined(OS_APPLE) && !BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) TEST_F(AllocatorShimTest, InterceptLibcSymbolsBatchMallocFree) { InsertAllocatorDispatch(&g_mock_dispatch); unsigned count = 13; std::vector<void*> results; results.resize(count); unsigned result_count = malloc_zone_batch_malloc(malloc_default_zone(), 99, results.data(), count); ASSERT_EQ(count, result_count); // TODO(erikchen): On macOS 10.12+, batch_malloc in the default zone may // forward to another zone, which we've also shimmed, resulting in // MockBatchMalloc getting called twice as often as we'd expect. This // re-entrancy into the allocator shim is a bug that needs to be fixed. // https://crbug.com/693237. // ASSERT_EQ(count, batch_mallocs_intercepted_by_size[99]); std::vector<void*> results_copy(results); malloc_zone_batch_free(malloc_default_zone(), results.data(), count); for (void* result : results_copy) { ASSERT_GE(batch_frees_intercepted_by_addr[Hash(result)], 1u); } RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } TEST_F(AllocatorShimTest, InterceptLibcSymbolsFreeDefiniteSize) { InsertAllocatorDispatch(&g_mock_dispatch); void* alloc_ptr = malloc(19); ASSERT_NE(nullptr, alloc_ptr); ASSERT_GE(allocs_intercepted_by_size[19], 1u); ChromeMallocZone* default_zone = reinterpret_cast<ChromeMallocZone*>(malloc_default_zone()); default_zone->free_definite_size(malloc_default_zone(), alloc_ptr, 19); ASSERT_GE(free_definite_sizes_intercepted_by_size[19], 1u); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } #endif // defined(OS_APPLE) && !BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #if defined(OS_WIN) TEST_F(AllocatorShimTest, InterceptUcrtAlignedAllocationSymbols) { InsertAllocatorDispatch(&g_mock_dispatch); constexpr size_t kAlignment = 32; void* alloc_ptr = _aligned_malloc(123, kAlignment); EXPECT_GE(aligned_mallocs_intercepted_by_size[123], 1u); void* new_alloc_ptr = _aligned_realloc(alloc_ptr, 1234, kAlignment); EXPECT_GE(aligned_reallocs_intercepted_by_size[1234], 1u); EXPECT_GE(aligned_reallocs_intercepted_by_addr[Hash(alloc_ptr)], 1u); _aligned_free(new_alloc_ptr); EXPECT_GE(aligned_frees_intercepted_by_addr[Hash(new_alloc_ptr)], 1u); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } TEST_F(AllocatorShimTest, AlignedReallocSizeZeroFrees) { void* alloc_ptr = _aligned_malloc(123, 16); CHECK(alloc_ptr); alloc_ptr = _aligned_realloc(alloc_ptr, 0, 16); CHECK(!alloc_ptr); } #endif // defined(OS_WIN) TEST_F(AllocatorShimTest, InterceptCppSymbols) { InsertAllocatorDispatch(&g_mock_dispatch); TestStruct1* new_ptr = new TestStruct1; ASSERT_NE(nullptr, new_ptr); ASSERT_GE(allocs_intercepted_by_size[sizeof(TestStruct1)], 1u); TestStruct1* new_array_ptr = new TestStruct1[3]; ASSERT_NE(nullptr, new_array_ptr); ASSERT_GE(allocs_intercepted_by_size[sizeof(TestStruct1) * 3], 1u); TestStruct2* new_nt_ptr = new (std::nothrow) TestStruct2; ASSERT_NE(nullptr, new_nt_ptr); ASSERT_GE(allocs_intercepted_by_size[sizeof(TestStruct2)], 1u); TestStruct2* new_array_nt_ptr = new TestStruct2[3]; ASSERT_NE(nullptr, new_array_nt_ptr); ASSERT_GE(allocs_intercepted_by_size[sizeof(TestStruct2) * 3], 1u); delete new_ptr; ASSERT_GE(frees_intercepted_by_addr[Hash(new_ptr)], 1u); delete[] new_array_ptr; ASSERT_GE(frees_intercepted_by_addr[Hash(new_array_ptr)], 1u); delete new_nt_ptr; ASSERT_GE(frees_intercepted_by_addr[Hash(new_nt_ptr)], 1u); delete[] new_array_nt_ptr; ASSERT_GE(frees_intercepted_by_addr[Hash(new_array_nt_ptr)], 1u); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } // PartitionAlloc disallows large allocations to avoid errors with int // overflows. #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) struct TooLarge { char padding1[1UL << 31]; int padding2; }; TEST_F(AllocatorShimTest, NewNoThrowTooLarge) { char* too_large_array = new (std::nothrow) char[(1UL << 31) + 100]; EXPECT_EQ(nullptr, too_large_array); TooLarge* too_large_struct = new (std::nothrow) TooLarge; EXPECT_EQ(nullptr, too_large_struct); } #endif // This test exercises the case of concurrent OOM failure, which would end up // invoking std::new_handler concurrently. This is to cover the CallNewHandler() // paths of allocator_shim.cc and smoke-test its thread safey. // The test creates kNumThreads threads. Each of them mallocs some memory, and // then does a realloc(<new memory>, 0xFEED). // The shim intercepts such realloc and makes it fail only once on each thread. // We expect to see excactly kNumThreads invocations of the new_handler. TEST_F(AllocatorShimTest, NewHandlerConcurrency) { const int kNumThreads = 32; PlatformThreadHandle threads[kNumThreads]; // The WaitableEvent here is used to attempt to trigger all the threads at // the same time, after they have been initialized. WaitableEvent event(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); ThreadDelegateForNewHandlerTest mock_thread_main(&event); for (int i = 0; i < kNumThreads; ++i) PlatformThread::Create(0, &mock_thread_main, &threads[i]); std::set_new_handler(&AllocatorShimTest::NewHandler); SetCallNewHandlerOnMallocFailure(true); // It's going to fail on realloc(). InsertAllocatorDispatch(&g_mock_dispatch); event.Signal(); for (int i = 0; i < kNumThreads; ++i) PlatformThread::Join(threads[i]); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); ASSERT_EQ(kNumThreads, GetNumberOfNewHandlerCalls()); } #if defined(OS_WIN) TEST_F(AllocatorShimTest, ShimReplacesCRTHeapWhenEnabled) { ASSERT_EQ(::GetProcessHeap(), reinterpret_cast<HANDLE>(_get_heap_handle())); } #endif // defined(OS_WIN) #if defined(OS_WIN) static size_t GetUsableSize(void* ptr) { return _msize(ptr); } #elif defined(OS_APPLE) static size_t GetUsableSize(void* ptr) { return malloc_size(ptr); } #elif defined(OS_LINUX) || defined(OS_CHROMEOS) static size_t GetUsableSize(void* ptr) { return malloc_usable_size(ptr); } #else #define NO_MALLOC_SIZE #endif #if !defined(NO_MALLOC_SIZE) TEST_F(AllocatorShimTest, ShimReplacesMallocSizeWhenEnabled) { InsertAllocatorDispatch(&g_mock_dispatch); EXPECT_EQ(GetUsableSize(kTestSizeEstimateAddress), kTestSizeEstimate); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } TEST_F(AllocatorShimTest, ShimDoesntChangeMallocSizeWhenEnabled) { void* alloc = malloc(16); size_t sz = GetUsableSize(alloc); EXPECT_GE(sz, 16U); InsertAllocatorDispatch(&g_mock_dispatch); EXPECT_EQ(GetUsableSize(alloc), sz); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); free(alloc); } #endif // !defined(NO_MALLOC_SIZE) #if defined(OS_ANDROID) TEST_F(AllocatorShimTest, InterceptCLibraryFunctions) { auto total_counts = [](const std::vector<size_t>& counts) { size_t total = 0; for (const auto count : counts) total += count; return total; }; size_t counts_before; size_t counts_after = total_counts(allocs_intercepted_by_size); void* ptr; InsertAllocatorDispatch(&g_mock_dispatch); // <stdlib.h> counts_before = counts_after; ptr = realpath(".", nullptr); EXPECT_NE(nullptr, ptr); free(ptr); counts_after = total_counts(allocs_intercepted_by_size); EXPECT_GT(counts_after, counts_before); // <string.h> counts_before = counts_after; ptr = strdup("hello, world"); EXPECT_NE(nullptr, ptr); free(ptr); counts_after = total_counts(allocs_intercepted_by_size); EXPECT_GT(counts_after, counts_before); counts_before = counts_after; ptr = strndup("hello, world", 5); EXPECT_NE(nullptr, ptr); free(ptr); counts_after = total_counts(allocs_intercepted_by_size); EXPECT_GT(counts_after, counts_before); // <unistd.h> counts_before = counts_after; ptr = getcwd(nullptr, 0); EXPECT_NE(nullptr, ptr); free(ptr); counts_after = total_counts(allocs_intercepted_by_size); EXPECT_GT(counts_after, counts_before); // Calls vasprintf() indirectly, see below. counts_before = counts_after; std::stringstream stream; stream << std::setprecision(1) << std::showpoint << std::fixed << 1.e38; EXPECT_GT(stream.str().size(), 30u); counts_after = total_counts(allocs_intercepted_by_size); EXPECT_GT(counts_after, counts_before); RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // Non-regression test for crbug.com/1166558. TEST_F(AllocatorShimTest, InterceptVasprintf) { // Printing a float which expands to >=30 characters calls vasprintf() in // libc, which we should intercept. std::stringstream stream; stream << std::setprecision(1) << std::showpoint << std::fixed << 1.e38; EXPECT_GT(stream.str().size(), 30u); // Should not crash. } #endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #endif // defined(OS_ANDROID) } // namespace } // namespace allocator } // namespace base
25,577
9,269
#include "../.././Image/Processing/Filters/Convolve/GaussConvolve.hh"
72
32
#ifndef GAMETRAINER_WINDOW_ENUMERATOR_MOCK_HPP #define GAMETRAINER_WINDOW_ENUMERATOR_MOCK_HPP #include <gt_os/window-enumerator.i.hpp> class WindowEnumeratorMock : public gt::os::IWindowEnumerator { public: MOCK_METHOD1(setTitle, gt::os::IWindowEnumerator*(const std::string&)); MOCK_METHOD0(enumerate, gt::os::IWindowEnumerator*()); MOCK_CONST_METHOD0(getWindow, HWND()); }; #endif // GAMETRAINER_WINDOW_ENUMERATOR_MOCK_HPP
440
199
#include "KdTree.h" namespace ZIRAN { /** add an eigenvec point to the tree */ template <int dim> template <class TV_IN> void KdTree<dim>::addPoint(const int i, const TV_IN& new_p) { TV p; for (int i = 0; i < dim; i++) p(i) = (double)(new_p(i)); tree.insert(KdTreeHelper<dim>(i, p)); } template <int dim> void KdTree<dim>::optimize() { tree.optimise(); } /** find the closest point to p in the tree */ template <int dim> template <class TV_IN, class T_IN> void KdTree<dim>::findNearest(const TV_IN& new_p, int& id, TV_IN& pos, T_IN& distance) { TV p; for (int i = 0; i < dim; i++) p(i) = (double)(new_p(i)); auto found = tree.find_nearest(KdTreeHelper<dim>(-1, p)); id = found.first->id; for (int i = 0; i < dim; i++) pos(i) = (T_IN)((found.first->pos)(i)); distance = (T_IN)found.second; } /** erase point erase_p from the tree */ template <int dim> template <class TV_IN> void KdTree<dim>::erasePoint(const int i, const TV_IN& erase_p) { TV p; for (int i = 0; i < dim; i++) p(i) = (double)(erase_p(i)); tree.erase(KdTreeHelper<dim>(i, p)); } template class KdTree<2>; template class KdTree<3>; template void KdTree<2>::addPoint<Eigen::Matrix<float, 2, 1, 0, 2, 1>>(int, Eigen::Matrix<float, 2, 1, 0, 2, 1> const&); template void KdTree<2>::addPoint<Eigen::Matrix<double, 2, 1, 0, 2, 1>>(int, Eigen::Matrix<double, 2, 1, 0, 2, 1> const&); template void KdTree<2>::findNearest<Eigen::Matrix<float, 2, 1, 0, 2, 1>, float>(Eigen::Matrix<float, 2, 1, 0, 2, 1> const&, int&, Eigen::Matrix<float, 2, 1, 0, 2, 1>&, float&); template void KdTree<2>::findNearest<Eigen::Matrix<double, 2, 1, 0, 2, 1>, double>(Eigen::Matrix<double, 2, 1, 0, 2, 1> const&, int&, Eigen::Matrix<double, 2, 1, 0, 2, 1>&, double&); template void KdTree<3>::addPoint<Eigen::Matrix<double, 3, 1, 0, 3, 1>>(int, Eigen::Matrix<double, 3, 1, 0, 3, 1> const&); template void KdTree<3>::addPoint<Eigen::Matrix<float, 3, 1, 0, 3, 1>>(int, Eigen::Matrix<float, 3, 1, 0, 3, 1> const&); template void KdTree<3>::erasePoint<Eigen::Matrix<double, 3, 1, 0, 3, 1>>(int, Eigen::Matrix<double, 3, 1, 0, 3, 1> const&); template void KdTree<3>::findNearest<Eigen::Matrix<double, 3, 1, 0, 3, 1>, double>(Eigen::Matrix<double, 3, 1, 0, 3, 1> const&, int&, Eigen::Matrix<double, 3, 1, 0, 3, 1>&, double&); template void KdTree<3>::findNearest<Eigen::Matrix<float, 3, 1, 0, 3, 1>, float>(Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, int&, Eigen::Matrix<float, 3, 1, 0, 3, 1>&, float&); } // namespace ZIRAN
2,553
1,180
/** * \file include/geombd/CRTP/DJointBase.hxx * \author Alvaro Paz, Gustavo Arechavaleta * \version 1.0 * \date 2021 * * Class to implement the CRTP base (interface) * Copyright (c) 2021 Cinvestav * This library is distributed under the MIT License. */ #ifdef EIGEN_VECTORIZE #endif #ifndef GEOMBD_JOINT_BASE_DIFFERENTIATION_CRTP_HXX #define GEOMBD_JOINT_BASE_DIFFERENTIATION_CRTP_HXX //! Include Eigen Library //!--------------------------------------------------------------------------------!// #define EIGEN_NO_DEBUG #define EIGEN_MPL2_ONLY #define EIGEN_UNROLLING_LIMIT 30 #include "Eigen/Core" //#include "Eigen/../unsupported/Eigen/KroneckerProduct" //!--------------------------------------------------------------------------------!// namespace geo { //! Joint Type Base //!------------------------------------------------------------------------------!// template<typename Derived> struct D_CRTPInterface{ public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW //! Recurring Pattern for the Forward Kinematics. template<typename ScalarType, typename Vector3Type, typename Matrix3Type> EIGEN_ALWAYS_INLINE void D_FwdKin(const ScalarType & qi, const Eigen::MatrixBase<Vector3Type> & S_, typename Eigen::MatrixBase<Matrix3Type> & R) { static_cast<Derived*>(this)->runD_FK(qi, S_, R); // static_cast<Derived&>(*this).runD_FK(qi, S_, R); } //! Recurring Pattern for Twist, C bias and P bias at root. template<typename ScalarType, typename Vector3Type, typename Vector6Type, typename Matrix6Type, typename D_Vector6Type> EIGEN_ALWAYS_INLINE void D_TCP_root(const ScalarType & vi, const Eigen::MatrixBase<Vector3Type> & S_, Eigen::MatrixBase<Vector6Type> & S_i, Eigen::MatrixBase<Vector6Type> & p_, const Eigen::MatrixBase<Matrix6Type> & M_, Eigen::MatrixBase<D_Vector6Type> & D_dq_p_) { static_cast<Derived*>(this)->runD_TCP_root(vi, S_, S_i, p_.derived(), M_.derived(), D_dq_p_.derived()); } //! Recurring Pattern for Twist, C bias and P bias. template<typename ScalarType, typename Matrix3Type, typename Matrix6Type, typename Vector3Type, typename Vector6Type, typename D_Vector6Type> EIGEN_ALWAYS_INLINE void D_TwCbPb(bool zeroFlag, const ScalarType & vi, const Eigen::MatrixBase<Vector3Type> & S_, const Eigen::MatrixBase<Matrix3Type> & R_, const Eigen::MatrixBase<Vector3Type> & P_, const Eigen::MatrixBase<Vector6Type> & S_l, const Eigen::MatrixBase<Matrix6Type> & M_, Eigen::MatrixBase<Vector6Type> & S_i, Eigen::MatrixBase<Vector6Type> & c_, Eigen::MatrixBase<Vector6Type> & p_, Eigen::MatrixBase<D_Vector6Type> & D_q_V_, Eigen::MatrixBase<D_Vector6Type> & D_dq_V_, const Eigen::MatrixBase<D_Vector6Type> & D_q_Vj_, const Eigen::MatrixBase<D_Vector6Type> & D_dq_Vj_, Eigen::MatrixBase<D_Vector6Type> & D_q_c_, Eigen::MatrixBase<D_Vector6Type> & D_dq_c_, Eigen::MatrixBase<D_Vector6Type> & D_q_p_, Eigen::MatrixBase<D_Vector6Type> & D_dq_p_) { static_cast<Derived*>(this)->runD_TwCbPb(zeroFlag, vi, S_.derived(), R_.derived(), P_.derived(), S_l.derived(), M_.derived(), S_i.derived(), c_.derived(), p_.derived(), D_q_V_.derived(), D_dq_V_.derived(), D_q_Vj_.derived(), D_dq_Vj_.derived(), D_q_c_.derived(), D_dq_c_.derived(), D_q_p_.derived(), D_dq_p_.derived()); } //! Recurring pattern for inertial expressions at leaf. template<typename ScalarType, typename Vector3Type, typename Matrix3Type, typename Vector6Type, typename Matrix6Type, typename RowVectorXType, typename D_Vector6Type, typename D_Matrix6Type> EIGEN_ALWAYS_INLINE void D_InertiaLeaf(ScalarType & u, ScalarType & iD, const ScalarType tau, const Eigen::MatrixBase<Vector3Type> & S_, Eigen::MatrixBase<Vector6Type> & U_, Eigen::MatrixBase<Vector6Type> & c_, Eigen::MatrixBase<Vector6Type> & P_a_, Eigen::MatrixBase<Matrix6Type> & M_a_, Eigen::MatrixBase<Vector6Type> & P_A_, Eigen::MatrixBase<Matrix6Type> & M_A_, bool P_z, Eigen::MatrixBase<Vector3Type> & P_, Eigen::MatrixBase<Matrix3Type> & R_, Eigen::MatrixBase<Vector6Type> & P_Aj_, Eigen::MatrixBase<Matrix6Type> & M_Aj_, Eigen::MatrixBase<D_Matrix6Type> & D_M_Aj_, Eigen::MatrixBase<RowVectorXType> & D_q_u_, Eigen::MatrixBase<RowVectorXType> & D_dq_u_, Eigen::MatrixBase<D_Vector6Type> & D_q_p_, Eigen::MatrixBase<D_Vector6Type> & D_dq_p_, Eigen::MatrixBase<D_Vector6Type> & D_q_Pa_, Eigen::MatrixBase<D_Vector6Type> & D_dq_Pa_, Eigen::MatrixBase<D_Vector6Type> & D_q_PA_, Eigen::MatrixBase<D_Vector6Type> & D_dq_PA_, Eigen::MatrixBase<D_Vector6Type> & D_q_PAj_, Eigen::MatrixBase<D_Vector6Type> & D_dq_PAj_, Eigen::MatrixBase<D_Vector6Type> & D_q_c_, Eigen::MatrixBase<D_Vector6Type> & D_dq_c_) { static_cast<Derived*>(this)->runD_InertiaLeaf(u, iD, tau, S_, U_, c_, P_a_, M_a_, P_A_, M_A_, P_z, P_, R_, P_Aj_, M_Aj_, D_M_Aj_, D_q_u_, D_dq_u_, D_q_p_, D_dq_p_, D_q_Pa_, D_dq_Pa_, D_q_PA_, D_dq_PA_, D_q_PAj_, D_dq_PAj_, D_q_c_, D_dq_c_); } //! Recurring pattern for inertial expressions. template<typename ScalarType, typename Vector6iType, typename Vector3Type, typename Matrix3Type, typename Vector6Type, typename Matrix6Type, typename VectorXType, typename RowVectorXType, typename D_Vector6Type, typename D_Matrix6Type> EIGEN_ALWAYS_INLINE void D_Inertial(bool rootFlag, Eigen::MatrixBase<Vector6iType> & indexVec, ScalarType & u, ScalarType & iD, const ScalarType tau, const Eigen::MatrixBase<Vector3Type> & S_, Eigen::MatrixBase<Vector6Type> & U_, Eigen::MatrixBase<Vector6Type> & c_, Eigen::MatrixBase<Vector6Type> & P_a_, Eigen::MatrixBase<Matrix6Type> & M_a_, Eigen::MatrixBase<Vector6Type> & P_A_, Eigen::MatrixBase<Matrix6Type> & M_A_, bool P_z, Eigen::MatrixBase<Vector3Type> & P_, Eigen::MatrixBase<Matrix3Type> & R_, Eigen::MatrixBase<Vector6Type> & P_Aj_, Eigen::MatrixBase<Matrix6Type> & M_Aj_, Eigen::MatrixBase<D_Vector6Type> & D_U_h_, Eigen::MatrixBase<VectorXType> & D_U_v_, Eigen::MatrixBase<RowVectorXType> & D_invD_, Eigen::MatrixBase<D_Matrix6Type> & D_M_A_, Eigen::MatrixBase<D_Matrix6Type> & D_M_Aj_, Eigen::MatrixBase<RowVectorXType> & D_q_u_, Eigen::MatrixBase<RowVectorXType> & D_dq_u_, Eigen::MatrixBase<D_Vector6Type> & D_q_Pa_, Eigen::MatrixBase<D_Vector6Type> & D_dq_Pa_, Eigen::MatrixBase<D_Vector6Type> & D_q_PA_, Eigen::MatrixBase<D_Vector6Type> & D_dq_PA_, Eigen::MatrixBase<D_Vector6Type> & D_q_PAj_, Eigen::MatrixBase<D_Vector6Type> & D_dq_PAj_, Eigen::MatrixBase<D_Vector6Type> & D_q_c_, Eigen::MatrixBase<D_Vector6Type> & D_dq_c_) { static_cast<Derived*>(this)->runD_Inertial(rootFlag, indexVec, u, iD, tau, S_, U_, c_, P_a_, M_a_, P_A_, M_A_, P_z, P_, R_, P_Aj_, M_Aj_, D_U_h_, D_U_v_, D_invD_, D_M_A_, D_M_Aj_, D_q_u_, D_dq_u_, D_q_Pa_, D_dq_Pa_, D_q_PA_, D_dq_PA_, D_q_PAj_, D_dq_PAj_, D_q_c_, D_dq_c_); } //! Recurring pattern for acceleration expression at root. template<typename ScalarType, typename Vector3Type, typename Matrix3Type, typename Vector6Type, typename D_Vector6Type, typename RowVectorXType, typename MatrixXType> EIGEN_ALWAYS_INLINE void D_AccelRoot(ScalarType u, ScalarType iD, ScalarType* ddq, const Eigen::MatrixBase<Vector3Type> & S, const Eigen::MatrixBase<Vector3Type> & P_r, const Eigen::MatrixBase<Matrix3Type> & R_r, const Eigen::MatrixBase<Vector6Type> & U_r, Eigen::MatrixBase<Vector6Type> & Acc_i_r, Eigen::MatrixBase<D_Vector6Type> & D_U_h_, Eigen::MatrixBase<RowVectorXType> & D_invD_, Eigen::MatrixBase<RowVectorXType> & D_q_u_, Eigen::MatrixBase<RowVectorXType> & D_dq_u_, Eigen::MatrixBase<D_Vector6Type> & D_q_A_, Eigen::MatrixBase<D_Vector6Type> & D_dq_A_, Eigen::MatrixBase<MatrixXType> & D_ddq_) { static_cast<Derived*>(this)->runD_AccelRoot(u, iD, ddq, S, P_r, R_r, U_r, Acc_i_r, D_U_h_, D_invD_, D_q_u_, D_dq_u_, D_q_A_, D_dq_A_, D_ddq_); } //! Recurring pattern for acceleration expression. template<typename ScalarType, typename IndexType, typename Vector3Type, typename Matrix3Type, typename Vector6Type, typename D_Vector6Type, typename RowVectorXType, typename MatrixXType> EIGEN_ALWAYS_INLINE void D_Accel(IndexType ID, bool zeroFlag, ScalarType u, ScalarType iD, ScalarType* ddq, const Eigen::MatrixBase<Vector3Type> & S, const Eigen::MatrixBase<Vector3Type> & P_, const Eigen::MatrixBase<Matrix3Type> & R_, const Eigen::MatrixBase<Vector6Type> & c_, const Eigen::MatrixBase<Vector6Type> & U_, Eigen::MatrixBase<Vector6Type> & A_, const Eigen::MatrixBase<Vector6Type> & Aj_, bool isLeaf, std::vector< IndexType >* Pre_, std::vector< IndexType >* Suc_, std::vector< IndexType >* PreSuc_, Eigen::MatrixBase<D_Vector6Type> & D_U_h_, Eigen::MatrixBase<RowVectorXType> & D_invD_, Eigen::MatrixBase<MatrixXType> & D_ddq_, Eigen::MatrixBase<RowVectorXType> & D_q_u_, Eigen::MatrixBase<RowVectorXType> & D_dq_u_, Eigen::MatrixBase<D_Vector6Type> & D_q_c_, Eigen::MatrixBase<D_Vector6Type> & D_dq_c_, Eigen::MatrixBase<D_Vector6Type> & D_q_A_, Eigen::MatrixBase<D_Vector6Type> & D_dq_A_, Eigen::MatrixBase<D_Vector6Type> & D_q_Aj_, Eigen::MatrixBase<D_Vector6Type> & D_dq_Aj_) { static_cast<Derived*>(this)->runD_Accel(ID, zeroFlag, u, iD, ddq, S, P_, R_, c_, U_, A_, Aj_, isLeaf, Pre_, Suc_, PreSuc_, D_U_h_, D_invD_, D_ddq_, D_q_u_, D_dq_u_, D_q_c_, D_dq_c_, D_q_A_, D_dq_A_, D_q_Aj_, D_dq_Aj_); } }; } #include "DJointDerived/DJointDerived.hpp" #include "DJointDerived/DVisitors.hxx" #endif // GEOMBD_JOINT_BASE_DIFFERENTIATION_CRTP_HXX
11,768
4,105
// Filename: parasiteBuffer.cxx // Created by: drose (27Feb04) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "parasiteBuffer.h" #include "texture.h" TypeHandle ParasiteBuffer::_type_handle; //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::Constructor // Access: Public // Description: Normally, the ParasiteBuffer constructor is not // called directly; these are created instead via the // GraphicsEngine::make_parasite() function. //////////////////////////////////////////////////////////////////// ParasiteBuffer:: ParasiteBuffer(GraphicsOutput *host, const string &name, int x_size, int y_size, int flags) : GraphicsOutput(host->get_engine(), host->get_pipe(), name, host->get_fb_properties(), WindowProperties::size(x_size, y_size), flags, host->get_gsg(), host, false) { #ifdef DO_MEMORY_USAGE MemoryUsage::update_type(this, this); #endif if (display_cat.is_debug()) { display_cat.debug() << "Creating new parasite buffer " << get_name() << " on " << _host->get_name() << "\n"; } _creation_flags = flags; if (flags & GraphicsPipe::BF_size_track_host) { _size = host->get_size(); } else { _size.set(x_size, y_size); } _has_size = true; _overlay_display_region->compute_pixels(_size.get_x(), _size.get_y()); _is_valid = true; set_inverted(host->get_gsg()->get_copy_texture_inverted()); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::Destructor // Access: Published, Virtual // Description: //////////////////////////////////////////////////////////////////// ParasiteBuffer:: ~ParasiteBuffer() { _is_valid = false; } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::is_active // Access: Published, Virtual // Description: Returns true if the window is ready to be rendered // into, false otherwise. //////////////////////////////////////////////////////////////////// bool ParasiteBuffer:: is_active() const { return GraphicsOutput::is_active() && _host->is_active(); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::set_size // Access: Public, Virtual // Description: This is called by the GraphicsEngine to request that // the buffer resize itself. Although calls to get the // size will return the new value, much of the actual // resizing work doesn't take place until the next // begin_frame. Not all buffers are resizeable. //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: set_size(int x, int y) { if ((_creation_flags & GraphicsPipe::BF_resizeable) == 0) { nassert_raise("Cannot resize buffer unless it is created with BF_resizeable flag"); return; } set_size_and_recalc(x, y); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::set_size_and_recalc // Access: Public // Description: //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: set_size_and_recalc(int x, int y) { if (!(_creation_flags & GraphicsPipe::BF_size_track_host)) { if (_creation_flags & GraphicsPipe::BF_size_power_2) { x = Texture::down_to_power_2(x); y = Texture::down_to_power_2(y); } if (_creation_flags & GraphicsPipe::BF_size_square) { x = y = min(x, y); } } GraphicsOutput::set_size_and_recalc(x, y); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::flip_ready // Access: Public, Virtual // Description: Returns true if a frame has been rendered and needs // to be flipped, false otherwise. //////////////////////////////////////////////////////////////////// bool ParasiteBuffer:: flip_ready() const { nassertr(_host != NULL, false); return _host->flip_ready(); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::begin_flip // Access: Public, Virtual // Description: This function will be called within the draw thread // after end_frame() has been called on all windows, to // initiate the exchange of the front and back buffers. // // This should instruct the window to prepare for the // flip at the next video sync, but it should not wait. // // We have the two separate functions, begin_flip() and // end_flip(), to make it easier to flip all of the // windows at the same time. //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: begin_flip() { nassertv(_host != NULL); _host->begin_flip(); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::ready_flip // Access: Public, Virtual // Description: This function will be called within the draw thread // after end_frame() has been called on all windows, to // initiate the exchange of the front and back buffers. // // This should instruct the window to prepare for the // flip when it is command but not actually flip // //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: ready_flip() { nassertv(_host != NULL); _host->ready_flip(); } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::end_flip // Access: Public, Virtual // Description: This function will be called within the draw thread // after begin_flip() has been called on all windows, to // finish the exchange of the front and back buffers. // // This should cause the window to wait for the flip, if // necessary. //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: end_flip() { nassertv(_host != NULL); _host->end_flip(); _flip_ready = false; } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::begin_frame // Access: Public, Virtual // Description: This function will be called within the draw thread // before beginning rendering for a given frame. It // should do whatever setup is required, and return true // if the frame should be rendered, or false if it // should be skipped. //////////////////////////////////////////////////////////////////// bool ParasiteBuffer:: begin_frame(FrameMode mode, Thread *current_thread) { begin_frame_spam(mode); if (!_host->begin_frame(FM_parasite, current_thread)) { return false; } if (_creation_flags & GraphicsPipe::BF_size_track_host) { if (_host->get_size() != _size) { set_size_and_recalc(_host->get_x_size(), _host->get_y_size()); } } else { if (_host->get_x_size() < get_x_size() || _host->get_y_size() < get_y_size()) { set_size_and_recalc(min(get_x_size(), _host->get_x_size()), min(get_y_size(), _host->get_y_size())); } } clear_cube_map_selection(); return true; } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::end_frame // Access: Public, Virtual // Description: This function will be called within the draw thread // after rendering is completed for a given frame. It // should do whatever finalization is required. //////////////////////////////////////////////////////////////////// void ParasiteBuffer:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); nassertv(_gsg != (GraphicsStateGuardian *)NULL); _host->end_frame(FM_parasite, current_thread); if (mode == FM_refresh) { return; } if (mode == FM_render) { promote_to_copy_texture(); copy_to_textures(); clear_cube_map_selection(); } } //////////////////////////////////////////////////////////////////// // Function: ParasiteBuffer::get_host // Access: Public, Virtual // Description: This is normally called only from within // make_texture_buffer(). When called on a // ParasiteBuffer, it returns the host of that buffer; // but when called on some other buffer, it returns the // buffer itself. //////////////////////////////////////////////////////////////////// GraphicsOutput *ParasiteBuffer:: get_host() { return _host; }
9,167
2,401
#include <bits/stdc++.h> using namespace std; class Solution { public: string simplifyPath(string path) { if (path.back() != '/') path += '/'; string res, s; for (auto &c : path) { if (res.empty()) res += c; else if (c == '/') { if (s == "..") { if (res.size() > 1) { res.pop_back(); while (res.back() != '/') res.pop_back(); } } else if (s != "" && s != ".") { res += s + '/'; } s = ""; } else { s += c; } } if (res.size() > 1) res.pop_back(); return res; } }; int main(){ assert(Solution().simplifyPath("/home//foo/") == "/home/foo"); return 0; }
963
276
#include "FirstPersonCameraController.h" #include "Core/Transform.h" #include "Misc/Hardware/Mouse.h" #include "Misc/Hardware/Time.h" #include "XPlatform/typename.h" namespace Tristeon { namespace Standard { DerivedRegister<FirstPersonCameraController> FirstPersonCameraController::reg; nlohmann::json FirstPersonCameraController::serialize() { nlohmann::json j; j["typeID"] = TRISTEON_TYPENAME(FirstPersonCameraController); j["sensitivity"] = sensitivity; return j; } void FirstPersonCameraController::deserialize(nlohmann::json json) { sensitivity = json["sensitivity"]; } void FirstPersonCameraController::start() { } void FirstPersonCameraController::update() { float const x = Misc::Mouse::getMouseDelta().x * sensitivity * Misc::Time::getDeltaTime(); float const y = Misc::Mouse::getMouseDelta().y * sensitivity * Misc::Time::getDeltaTime(); xRot -= y; yRot -= x; transform.get()->rotation = Math::Quaternion::euler(xRot, yRot, 0); } } }
1,010
380
/***************************************************************************** * \file * \brief This header detects features for Windows platforms * * \note This is an internal header file, included by other library headers. * Do not attempt to use it directly. *****************************************************************************/ /* The MIT License (MIT) Bit Standard Template Library. https://github.com/bitwizeshift/bit-stl Copyright (c) 2018 Matthew Rodusek 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 BIT_STL_UTILITIES_DETAIL_COMPILER_TRAITS_PLATFORM_WIN32_HPP #define BIT_STL_UTILITIES_DETAIL_COMPILER_TRAITS_PLATFORM_WIN32_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) //----------------------------------------------------------------------------- // Platform Detection //----------------------------------------------------------------------------- #define BIT_PLATFORM_WINDOWS 1 #if defined(__MINGW32__) || defined(__MINGW64__) # include <_mingw.h> // Include for version information # define BIT_PLATFORM_MINGW 1 #endif #if defined(_WIN64) # define BIT_PLATFORM_WIN64 1 # define BIT_PLATFORM_STRING "Windows (64-bit)" #else # define BIT_PLATFORM_WIN32 1 # define BIT_PLATFORM_STRING "Windows (32-bit)" #endif //----------------------------------------------------------------------------- // Platform Specifics Detection //----------------------------------------------------------------------------- // MinGW has some added headers not present in MSVC #if defined(__MINGW32__) && ((__MINGW32_MAJOR_VERSION > 2) || ((__MINGW32_MAJOR_VERSION == 2) && (__MINGW32_MINOR_VERSION >= 0))) # ifndef BIT_PLATFORM_HAS_STDINT_H # define BIT_PLATFORM_HAS_STDINT_H 1 # endif # ifndef BIT_PLATFORM_HAS_DIRENT_H # define BIT_PLATFORM_HAS_DIRENT_H 1 # endif # ifndef BIT_PLATFORM_HAS_UNISTD_H # define BIT_PLATFORM_HAS_UNISTD_H 1 # endif #endif // Mingw configuration specific #if !defined(BIT_PLATFORM_HAS_PTHREADS) # define BIT_PLATFORM_HAS_WINTHREADS 1 #endif #define BIT_PLATFORM_HAS_WINSOCKS 1 #define BIT_PLATFORM_HAS_ALIGNED_MALLOC 1 #define BIT_PLATFORM_HAS_ALIGNED_OFFSET_MALLOC 1 // Determine API from defined compiler args #ifdef BIT_USE_VULKAN_API # define VK_USE_PLATFORM_WIN32_KHR 1 #elif !defined(BIT_USE_OGL_API) # define BIT_USE_OGL_API 1 #endif #endif /* BIT_STL_UTILITIES_DETAIL_COMPILER_TRAITS_PLATFORM_WIN32_HPP */
3,496
1,250
#include "CombinedHitPairGeneratorForPhotonConversion.h" #include <memory> #include "DataFormats/Common/interface/Handle.h" #include "FWCore/Framework/interface/ConsumesCollector.h" #include "FWCore/Framework/interface/Event.h" #include "HitPairGeneratorFromLayerPairForPhotonConversion.h" #include "FWCore/Utilities/interface/RunningAverage.h" namespace { edm::RunningAverage localRA; } CombinedHitPairGeneratorForPhotonConversion::CombinedHitPairGeneratorForPhotonConversion(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC) : theSeedingLayerToken(iC.consumes<SeedingLayerSetsHits>(cfg.getParameter<edm::InputTag>("SeedingLayers"))) { theMaxElement = cfg.getParameter<unsigned int>("maxElement"); maxHitPairsPerTrackAndGenerator = cfg.getParameter<unsigned int>("maxHitPairsPerTrackAndGenerator"); theGenerator = std::make_unique<HitPairGeneratorFromLayerPairForPhotonConversion>( 0, 1, &theLayerCache, 0, maxHitPairsPerTrackAndGenerator); } const OrderedHitPairs& CombinedHitPairGeneratorForPhotonConversion::run(const ConversionRegion& convRegion, const TrackingRegion& region, const edm::Event& ev, const edm::EventSetup& es) { if (thePairs.capacity() == 0) thePairs.reserve(localRA.upper()); thePairs.clear(); hitPairs(convRegion, region, thePairs, ev, es); return thePairs; } void CombinedHitPairGeneratorForPhotonConversion::hitPairs(const ConversionRegion& convRegion, const TrackingRegion& region, OrderedHitPairs& result, const edm::Event& ev, const edm::EventSetup& es) { edm::Handle<SeedingLayerSetsHits> hlayers; ev.getByToken(theSeedingLayerToken, hlayers); const SeedingLayerSetsHits& layers = *hlayers; assert(layers.numberOfLayersInSet() == 2); for (SeedingLayerSetsHits::LayerSetIndex i = 0; i < layers.size(); ++i) { theGenerator->hitPairs(convRegion, region, result, layers[i], ev, es); } } void CombinedHitPairGeneratorForPhotonConversion::clearCache() { theLayerCache.clear(); localRA.update(thePairs.size()); thePairs.clear(); thePairs.shrink_to_fit(); }
2,590
762
/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // char_properties.cc - define is_X() tests for various character properties // // See char_properties.h for how to write a character property. // // References for the char sets below: // // . http://www.unicode.org/Public/UNIDATA/PropList.txt // // Large (but not exhaustive) list of Unicode chars and their "properties" // (e.g., the property "Pi" = an initial quote punctuation char). // // . http://www.unicode.org/Public/UNIDATA/PropertyValueAliases.txt // // Defines the list of properties, such as "Pi", used in the above list. // // . http://www.unipad.org/unimap/index.php?param_char=XXXX&page=detail // // Gives detail about a particular character code. // XXXX is a 4-hex-digit Unicode character code. // // . http://www.unicode.org/Public/UNIDATA/UCD.html // // General reference for Unicode characters. // #include "syntaxnet/char_properties.h" #include <ctype.h> // for ispunct, isspace #include <memory> #include <utility> #include <vector> // for vector #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "third_party/utf/utf.h" // for runetochar, ::UTFmax, Rune #include "util/utf8/unilib.h" // for IsValidCodepoint, etc #include "util/utf8/unilib_utf8_utils.h" //============================================================ // CharPropertyImplementation // // A CharPropertyImplementation stores a set of Unicode characters, // encoded in UTF-8, as a trie. The trie is represented as a vector // of nodes. Each node is a 256-element array that specifies what to // do with one byte of the UTF-8 sequence. Each element n of a node // is one of: // n = 0, indicating that the Property is not true of any // character whose UTF-8 encoding includes this byte at // this position // n = -1, indicating that the Property is true for the UTF-8 sequence // that ends with this byte. // n > 0, indicating the index of the row that describes the // remaining bytes in the UTF-8 sequence. // // The only operation that needs to be fast is HoldsFor, which tests // whether a character has a given property. We use each byte of the // character's UTF-8 encoding to index into a row. If the value is 0, // then the property is not true for the character. (We might discover // this even before getting to the end of the sequence.) If the value // is -1, then the property is true for this character. Otherwise, // the value is the index of another row, which we index using the next // byte in the sequence, and so on. The design of UTF-8 prevents // ambiguities here; no prefix of a UTF-8 sequence is a valid UTF-8 // sequence. // // While it is possible to implement an iterator for this representation, // it is much easier to use set<char32> for this purpose. In fact, we // would use that as the entire representation, were it not for concerns // that HoldsFor might be slower. namespace syntaxnet { struct CharPropertyImplementation { unordered_set<char32> chars; std::vector<std::vector<int> > rows; CharPropertyImplementation() { rows.reserve(10); rows.resize(1); rows[0].resize(256, 0); } void AddChar(char *buf, int len) { int n = 0; // row index for (int i = 0; i < len; ++i) { int ch = reinterpret_cast<unsigned char *>(buf)[i]; int m = rows[n][ch]; if (m > 0) { CHECK_LT(i, len - 1) << " : " << (i + 1) << "-byte UTF-8 sequence " << "(" << tensorflow::str_util::CEscape(string(buf, i + 1)) << ")" << " is prefix of previously-seen UTF-8 sequence(s)"; n = m; } else if (i == len - 1) { rows[n][ch] = -1; } else { CHECK_EQ(m, 0) << " : UTF-8 sequence is extension of previously-seen " << (i + 1) << "-byte UTF-8 sequence " << "(" << tensorflow::str_util::CEscape(string(buf, i + 1)) << ")"; int a = rows.size(); rows.resize(a + 1); rows[a].resize(256, 0); rows[n][ch] = a; n = a; } } } bool HoldsFor(const char *buf) const { const unsigned char *bytes = reinterpret_cast<const unsigned char *>(buf); // Lookup each byte of the UTF-8 sequence, starting in row 0. int n = rows[0][*bytes]; if (n == 0) return false; if (n == -1) return true; // If the value is not 0 or -1, then it is the index of the row for the // second byte in the sequence. n = rows[n][*++bytes]; if (n == 0) return false; if (n == -1) return true; n = rows[n][*++bytes]; // Likewise for the third byte. if (n == 0) return false; if (n == -1) return true; n = rows[n][*++bytes]; // Likewise for the fourth byte. if (n == 0) return false; // Since there can be at most 4 bytes in the sequence, n must be -1. return true; // Implementation note: it is possible (and perhaps clearer) to write this // code as a loop, "for (int i = 0; i < 4; ++i) ...", but the TestHoldsFor // benchmark results indicate that doing so produces slower code for // anything other than short 7-bit ASCII strings (< 512 bytes). This is // mysterious, since the compiler unrolls the loop, producing code that // is almost the same as what we have here, except for the shortcut on // the 4th byte. } }; //============================================================ // CharProperty - a property that holds for selected Unicode chars // CharProperty::CharProperty(const char *name, const int *unicodes, int num_unicodes) : name_(name), impl_(new CharPropertyImplementation) { // Initialize CharProperty to its char set. AddCharSpec(unicodes, num_unicodes); } CharProperty::CharProperty(const char *name, CharPropertyInitializer *init_fn) : name_(name), impl_(new CharPropertyImplementation) { (*init_fn)(this); } CharProperty::~CharProperty() { delete impl_; } void CharProperty::AddChar(int c) { CheckUnicodeVal(c); impl_->chars.insert(c); char buf[UTFmax]; Rune r = c; int len = runetochar(buf, &r); impl_->AddChar(buf, len); } void CharProperty::AddCharRange(int c1, int c2) { for (int c = c1; c <= c2; ++c) { AddChar(c); } } void CharProperty::AddAsciiPredicate(AsciiPredicate *pred) { for (int c = 0; c < 256; ++c) { if ((*pred)(c)) { AddChar(c); } } } void CharProperty::AddCharProperty(const char *propname) { const CharProperty *prop = CharProperty::Lookup(propname); CHECK(prop != nullptr) << ": unknown char property \"" << propname << "\" in " << name_; int c = -1; while ((c = prop->NextElementAfter(c)) >= 0) { AddChar(c); } } void CharProperty::AddCharSpec(const int *unicodes, int num_unicodes) { for (int i = 0; i < num_unicodes; ++i) { if (i + 3 < num_unicodes && unicodes[i] == kPreUnicodeRange && unicodes[i + 3] == kPostUnicodeRange) { // Range of unicode values int lower = unicodes[i + 1]; int upper = unicodes[i + 2]; i += 3; // i will be incremented once more at top of loop CHECK(lower <= upper) << ": invalid char range in " << name_ << ": [" << UnicodeToString(lower) << ", " << UnicodeToString(upper) << "]"; AddCharRange(lower, upper); } else { AddChar(unicodes[i]); } } } bool CharProperty::HoldsFor(int c) const { if (!UniLib::IsValidCodepoint(c)) return false; char buf[UTFmax]; Rune r = c; runetochar(buf, &r); return impl_->HoldsFor(buf); } bool CharProperty::HoldsFor(const char *str, int len) const { // UniLib::IsUTF8ValidCodepoint also checks for structural validity. return len > 0 && UniLib::IsUTF8ValidCodepoint(StringPiece(str, len)) && impl_->HoldsFor(str); } // Return -1 or the smallest Unicode char greater than c for which // the CharProperty holds. Expects c == -1 or HoldsFor(c). int CharProperty::NextElementAfter(int c) const { DCHECK(c == -1 || HoldsFor(c)); unordered_set<char32>::const_iterator end = impl_->chars.end(); if (c < 0) { unordered_set<char32>::const_iterator it = impl_->chars.begin(); if (it == end) return -1; return *it; } char32 r = c; unordered_set<char32>::const_iterator it = impl_->chars.find(r); if (it == end) return -1; it++; if (it == end) return -1; return *it; } REGISTER_SYNTAXNET_CLASS_REGISTRY("char property wrapper", CharPropertyWrapper); const CharProperty *CharProperty::Lookup(const char *subclass) { // Create a CharPropertyWrapper object and delete it. We only care about // the CharProperty it provides. std::unique_ptr<CharPropertyWrapper> wrapper( CharPropertyWrapper::Create(subclass)); if (wrapper == nullptr) { LOG(ERROR) << "CharPropertyWrapper not found for subclass: " << "\"" << subclass << "\""; return nullptr; } return wrapper->GetCharProperty(); } // Check that a given Unicode value is in range. void CharProperty::CheckUnicodeVal(int c) const { CHECK(UniLib::IsValidCodepoint(c)) << "Unicode in " << name_ << " out of range: " << UnicodeToString(c); } // Converts a Unicode value to a string (for error messages). string CharProperty::UnicodeToString(int c) { const char *fmt; if (c < 0) { fmt = "%d"; // out-of-range } else if (c <= 0x7f) { fmt = "'%c'"; // ascii } else if (c <= 0xffff) { fmt = "0x%04X"; // 4 hex digits } else { fmt = "0x%X"; // also out-of-range } return tensorflow::strings::Printf(fmt, c); } //====================================================================== // Expression-level punctuation // // Punctuation that starts a sentence. DEFINE_CHAR_PROPERTY_AS_SET(start_sentence_punc, 0x00A1, // Spanish inverted exclamation mark 0x00BF, // Spanish inverted question mark ) // Punctuation that ends a sentence. // Based on: http://www.unicode.org/unicode/reports/tr29/#Sentence_Boundaries DEFINE_CHAR_PROPERTY_AS_SET(end_sentence_punc, '.', '!', '?', 0x055C, // Armenian exclamation mark 0x055E, // Armenian question mark 0x0589, // Armenian full stop 0x061F, // Arabic question mark 0x06D4, // Arabic full stop 0x0700, // Syriac end of paragraph 0x0701, // Syriac supralinear full stop 0x0702, // Syriac sublinear full stop RANGE(0x0964, 0x0965), // Devanagari danda..Devanagari double danda 0x1362, // Ethiopic full stop 0x1367, // Ethiopic question mark 0x1368, // Ethiopic paragraph separator 0x104A, // Myanmar sign little section 0x104B, // Myanmar sign section 0x166E, // Canadian syllabics full stop 0x17d4, // Khmer sign khan 0x1803, // Mongolian full stop 0x1809, // Mongolian Manchu full stop 0x1944, // Limbu exclamation mark 0x1945, // Limbu question mark 0x203C, // double exclamation mark 0x203D, // interrobang 0x2047, // double question mark 0x2048, // question exclamation mark 0x2049, // exclamation question mark 0x3002, // ideographic full stop 0x037E, // Greek question mark 0xFE52, // small full stop 0xFE56, // small question mark 0xFE57, // small exclamation mark 0xFF01, // fullwidth exclamation mark 0xFF0E, // fullwidth full stop 0xFF1F, // fullwidth question mark 0xFF61, // halfwidth ideographic full stop 0x2026, // ellipsis ) // Punctuation, such as parens, that opens a "nested expression" of text. DEFINE_CHAR_PROPERTY_AS_SET(open_expr_punc, '(', '[', '<', '{', 0x207D, // superscript left parenthesis 0x208D, // subscript left parenthesis 0x27E6, // mathematical left white square bracket 0x27E8, // mathematical left angle bracket 0x27EA, // mathematical left double angle bracket 0x2983, // left white curly bracket 0x2985, // left white parenthesis 0x2987, // Z notation left image bracket 0x2989, // Z notation left binding bracket 0x298B, // left square bracket with underbar 0x298D, // left square bracket with tick in top corner 0x298F, // left square bracket with tick in bottom corner 0x2991, // left angle bracket with dot 0x2993, // left arc less-than bracket 0x2995, // double left arc greater-than bracket 0x2997, // left black tortoise shell bracket 0x29D8, // left wiggly fence 0x29DA, // left double wiggly fence 0x29FC, // left-pointing curved angle bracket 0x3008, // CJK left angle bracket 0x300A, // CJK left double angle bracket 0x3010, // CJK left black lenticular bracket 0x3014, // CJK left tortoise shell bracket 0x3016, // CJK left white lenticular bracket 0x3018, // CJK left white tortoise shell bracket 0x301A, // CJK left white square bracket 0xFD3E, // Ornate left parenthesis 0xFE59, // small left parenthesis 0xFE5B, // small left curly bracket 0xFF08, // fullwidth left parenthesis 0xFF3B, // fullwidth left square bracket 0xFF5B, // fullwidth left curly bracket ) // Punctuation, such as parens, that closes a "nested expression" of text. DEFINE_CHAR_PROPERTY_AS_SET(close_expr_punc, ')', ']', '>', '}', 0x207E, // superscript right parenthesis 0x208E, // subscript right parenthesis 0x27E7, // mathematical right white square bracket 0x27E9, // mathematical right angle bracket 0x27EB, // mathematical right double angle bracket 0x2984, // right white curly bracket 0x2986, // right white parenthesis 0x2988, // Z notation right image bracket 0x298A, // Z notation right binding bracket 0x298C, // right square bracket with underbar 0x298E, // right square bracket with tick in top corner 0x2990, // right square bracket with tick in bottom corner 0x2992, // right angle bracket with dot 0x2994, // right arc greater-than bracket 0x2996, // double right arc less-than bracket 0x2998, // right black tortoise shell bracket 0x29D9, // right wiggly fence 0x29DB, // right double wiggly fence 0x29FD, // right-pointing curved angle bracket 0x3009, // CJK right angle bracket 0x300B, // CJK right double angle bracket 0x3011, // CJK right black lenticular bracket 0x3015, // CJK right tortoise shell bracket 0x3017, // CJK right white lenticular bracket 0x3019, // CJK right white tortoise shell bracket 0x301B, // CJK right white square bracket 0xFD3F, // Ornate right parenthesis 0xFE5A, // small right parenthesis 0xFE5C, // small right curly bracket 0xFF09, // fullwidth right parenthesis 0xFF3D, // fullwidth right square bracket 0xFF5D, // fullwidth right curly bracket ) // Chars that open a quotation. // Based on: http://www.unicode.org/uni2book/ch06.pdf DEFINE_CHAR_PROPERTY_AS_SET(open_quote, '"', '\'', '`', 0xFF07, // fullwidth apostrophe 0xFF02, // fullwidth quotation mark 0x2018, // left single quotation mark (English, others) 0x201C, // left double quotation mark (English, others) 0x201B, // single high-reveresed-9 quotation mark (PropList.txt) 0x201A, // single low-9 quotation mark (Czech, German, Slovak) 0x201E, // double low-9 quotation mark (Czech, German, Slovak) 0x201F, // double high-reversed-9 quotation mark (PropList.txt) 0x2019, // right single quotation mark (Danish, Finnish, Swedish, Norw.) 0x201D, // right double quotation mark (Danish, Finnish, Swedish, Norw.) 0x2039, // single left-pointing angle quotation mark (French, others) 0x00AB, // left-pointing double angle quotation mark (French, others) 0x203A, // single right-pointing angle quotation mark (Slovenian, others) 0x00BB, // right-pointing double angle quotation mark (Slovenian, others) 0x300C, // left corner bracket (East Asian languages) 0xFE41, // presentation form for vertical left corner bracket 0xFF62, // halfwidth left corner bracket (East Asian languages) 0x300E, // left white corner bracket (East Asian languages) 0xFE43, // presentation form for vertical left white corner bracket 0x301D, // reversed double prime quotation mark (East Asian langs, horiz.) ) // Chars that close a quotation. // Based on: http://www.unicode.org/uni2book/ch06.pdf DEFINE_CHAR_PROPERTY_AS_SET(close_quote, '\'', '"', '`', 0xFF07, // fullwidth apostrophe 0xFF02, // fullwidth quotation mark 0x2019, // right single quotation mark (English, others) 0x201D, // right double quotation mark (English, others) 0x2018, // left single quotation mark (Czech, German, Slovak) 0x201C, // left double quotation mark (Czech, German, Slovak) 0x203A, // single right-pointing angle quotation mark (French, others) 0x00BB, // right-pointing double angle quotation mark (French, others) 0x2039, // single left-pointing angle quotation mark (Slovenian, others) 0x00AB, // left-pointing double angle quotation mark (Slovenian, others) 0x300D, // right corner bracket (East Asian languages) 0xfe42, // presentation form for vertical right corner bracket 0xFF63, // halfwidth right corner bracket (East Asian languages) 0x300F, // right white corner bracket (East Asian languages) 0xfe44, // presentation form for vertical right white corner bracket 0x301F, // low double prime quotation mark (East Asian languages) 0x301E, // close double prime (East Asian languages written horizontally) ) // Punctuation chars that open an expression or a quotation. DEFINE_CHAR_PROPERTY(open_punc, prop) { prop->AddCharProperty("open_expr_punc"); prop->AddCharProperty("open_quote"); } // Punctuation chars that close an expression or a quotation. DEFINE_CHAR_PROPERTY(close_punc, prop) { prop->AddCharProperty("close_expr_punc"); prop->AddCharProperty("close_quote"); } // Punctuation chars that can come at the beginning of a sentence. DEFINE_CHAR_PROPERTY(leading_sentence_punc, prop) { prop->AddCharProperty("open_punc"); prop->AddCharProperty("start_sentence_punc"); } // Punctuation chars that can come at the end of a sentence. DEFINE_CHAR_PROPERTY(trailing_sentence_punc, prop) { prop->AddCharProperty("close_punc"); prop->AddCharProperty("end_sentence_punc"); } //====================================================================== // Special symbols // // Currency symbols. // From: http://www.unicode.org/charts/PDF/U20A0.pdf DEFINE_CHAR_PROPERTY_AS_SET(currency_symbol, '$', // 0x00A2, // cents (NB: typically FOLLOWS the amount) 0x00A3, // pounds and liras 0x00A4, // general currency sign 0x00A5, // yen or yuan 0x0192, // Dutch florin (latin small letter "f" with hook) 0x09F2, // Bengali rupee mark 0x09F3, // Bengali rupee sign 0x0AF1, // Guajarati rupee sign 0x0BF9, // Tamil rupee sign 0x0E3F, // Thai baht 0x17DB, // Khmer riel 0x20A0, // alternative euro sign 0x20A1, // Costa Rica, El Salvador (colon sign) 0x20A2, // Brazilian cruzeiro 0x20A3, // French Franc 0x20A4, // alternative lira sign 0x20A5, // mill sign (USA 1/10 cent) 0x20A6, // Nigerian Naira 0x20A7, // Spanish peseta 0x20A8, // Indian rupee 0x20A9, // Korean won 0x20AA, // Israeli new sheqel 0x20AB, // Vietnam dong 0x20AC, // euro sign 0x20AD, // Laotian kip 0x20AE, // Mongolian tugrik 0x20AF, // Greek drachma 0x20B0, // German penny 0x20B1, // Philippine peso (Mexican peso uses "$") 0x2133, // Old German mark (script capital M) 0xFDFC, // rial sign 0xFFE0, // fullwidth cents 0xFFE1, // fullwidth pounds 0xFFE5, // fullwidth Japanese yen 0xFFE6, // fullwidth Korean won ) // Chinese bookquotes. // They look like "<<" and ">>" except that they are single UTF8 chars // (U+300A, U+300B). These are used in chinese as special // punctuation, refering to the title of a book, an article, a movie, // etc. For example: "cellphone" means cellphone, but <<cellphone>> // means (exclusively) the movie. DEFINE_CHAR_PROPERTY_AS_SET(open_bookquote, 0x300A ) DEFINE_CHAR_PROPERTY_AS_SET(close_bookquote, 0x300B ) //====================================================================== // Token-level punctuation // // Token-prefix symbols, excluding currency symbols -- glom on // to following token (esp. if no space after) DEFINE_CHAR_PROPERTY_AS_SET(noncurrency_token_prefix_symbol, '#', 0x2116, // numero sign ("No") ) // Token-prefix symbols -- glom on to following token (esp. if no space after) DEFINE_CHAR_PROPERTY(token_prefix_symbol, prop) { prop->AddCharProperty("currency_symbol"); prop->AddCharProperty("noncurrency_token_prefix_symbol"); } // Token-suffix symbols -- glom on to preceding token (esp. if no space before) DEFINE_CHAR_PROPERTY_AS_SET(token_suffix_symbol, '%', 0x066A, // Arabic percent sign 0x2030, // per mille 0x2031, // per ten thousand 0x00A2, // cents sign 0x2125, // ounces sign 0x00AA, // feminine ordinal indicator (Spanish) 0x00BA, // masculine ordinal indicator (Spanish) 0x00B0, // degrees 0x2109, // degrees Fahrenheit 0x2103, // degrees Celsius 0x2126, // ohms 0x212A, // Kelvin 0x212B, // Angstroms ("A" with circle on top) 0x00A9, // copyright 0x2117, // sound recording copyright (circled "P") 0x2122, // trade mark 0x00AE, // registered trade mark 0x2120, // service mark 0x2106, // cada una ("c/a" == "each" in Spanish) 0x2020, // dagger (can be used for footnotes) 0x2021, // double dagger (can be used for footnotes) ) // Subscripts DEFINE_CHAR_PROPERTY_AS_SET(subscript_symbol, 0x2080, // subscript 0 0x2081, // subscript 1 0x2082, // subscript 2 0x2083, // subscript 3 0x2084, // subscript 4 0x2085, // subscript 5 0x2086, // subscript 6 0x2087, // subscript 7 0x2088, // subscript 8 0x2089, // subscript 9 0x208A, // subscript "+" 0x208B, // subscript "-" 0x208C, // subscript "=" 0x208D, // subscript "(" 0x208E, // subscript ")" ) // Superscripts DEFINE_CHAR_PROPERTY_AS_SET(superscript_symbol, 0x2070, // superscript 0 0x00B9, // superscript 1 0x00B2, // superscript 2 0x00B3, // superscript 3 0x2074, // superscript 4 0x2075, // superscript 5 0x2076, // superscript 6 0x2077, // superscript 7 0x2078, // superscript 8 0x2079, // superscript 9 0x2071, // superscript Latin small "i" 0x207A, // superscript "+" 0x207B, // superscript "-" 0x207C, // superscript "=" 0x207D, // superscript "(" 0x207E, // superscript ")" 0x207F, // superscript Latin small "n" ) //====================================================================== // General punctuation // // Connector punctuation // Code Pc from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(connector_punc, 0x30fb, // Katakana middle dot 0xff65, // halfwidth Katakana middle dot 0x2040, // character tie ) // Dashes // Code Pd from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(dash_punc, '-', '~', 0x058a, // Armenian hyphen 0x1806, // Mongolian todo soft hyphen RANGE(0x2010, 0x2015), // hyphen..horizontal bar 0x2053, // swung dash -- from Table 6-3 of Unicode book 0x207b, // superscript minus 0x208b, // subscript minus 0x2212, // minus sign 0x301c, // wave dash 0x3030, // wavy dash RANGE(0xfe31, 0xfe32), // presentation form for vertical em dash..en dash 0xfe58, // small em dash 0xfe63, // small hyphen-minus 0xff0d, // fullwidth hyphen-minus ) // Other punctuation // Code Po from http://www.unicode.org/Public/UNIDATA/UnicodeData.txt // NB: This list is not exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(other_punc, ',', ':', ';', 0x00b7, // middle dot 0x0387, // Greek ano teleia 0x05c3, // Hebrew punctuation sof pasuq 0x060c, // Arabic comma 0x061b, // Arabic semicolon 0x066b, // Arabic decimal separator 0x066c, // Arabic thousands separator RANGE(0x0703, 0x70a), // Syriac contraction and others 0x070c, // Syric harklean metobelus 0x0e5a, // Thai character angkhankhu 0x0e5b, // Thai character khomut 0x0f08, // Tibetan mark sbrul shad RANGE(0x0f0d, 0x0f12), // Tibetan mark shad..Tibetan mark rgya gram shad 0x1361, // Ethiopic wordspace RANGE(0x1363, 0x1366), // other Ethiopic chars 0x166d, // Canadian syllabics chi sign RANGE(0x16eb, 0x16ed), // Runic single punctuation..Runic cross punctuation RANGE(0x17d5, 0x17d6), // Khmer sign camnuc pii huuh and other 0x17da, // Khmer sign koomut 0x1802, // Mongolian comma RANGE(0x1804, 0x1805), // Mongolian four dots and other 0x1808, // Mongolian manchu comma 0x3001, // ideographic comma RANGE(0xfe50, 0xfe51), // small comma and others RANGE(0xfe54, 0xfe55), // small semicolon and other 0xff0c, // fullwidth comma RANGE(0xff0e, 0xff0f), // fullwidth stop..fullwidth solidus RANGE(0xff1a, 0xff1b), // fullwidth colon..fullwidth semicolon 0xff64, // halfwidth ideographic comma 0x2016, // double vertical line RANGE(0x2032, 0x2034), // prime..triple prime 0xfe61, // small asterisk 0xfe68, // small reverse solidus 0xff3c, // fullwidth reverse solidus ) // All punctuation. // Code P from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY(punctuation, prop) { prop->AddCharProperty("open_punc"); prop->AddCharProperty("close_punc"); prop->AddCharProperty("leading_sentence_punc"); prop->AddCharProperty("trailing_sentence_punc"); prop->AddCharProperty("connector_punc"); prop->AddCharProperty("dash_punc"); prop->AddCharProperty("other_punc"); prop->AddAsciiPredicate(&ispunct); } //====================================================================== // Separators // // Line separators // Code Zl from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(line_separator, 0x2028, // line separator ) // Paragraph separators // Code Zp from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(paragraph_separator, 0x2029, // paragraph separator ) // Space separators // Code Zs from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY_AS_SET(space_separator, 0x0020, // space 0x00a0, // no-break space 0x1680, // Ogham space mark 0x180e, // Mongolian vowel separator RANGE(0x2000, 0x200a), // en quad..hair space 0x202f, // narrow no-break space 0x205f, // medium mathematical space 0x3000, // ideographic space // Google additions 0xe5e5, // "private" char used as space in Chinese ) // Separators -- all line, paragraph, and space separators. // Code Z from http://www.unicode.org/Public/UNIDATA/PropList.txt // NB: This list is not necessarily exhaustive. DEFINE_CHAR_PROPERTY(separator, prop) { prop->AddCharProperty("line_separator"); prop->AddCharProperty("paragraph_separator"); prop->AddCharProperty("space_separator"); prop->AddAsciiPredicate(&isspace); } //====================================================================== // Alphanumeric Characters // // Digits DEFINE_CHAR_PROPERTY_AS_SET(digit, RANGE('0', '9'), RANGE(0x0660, 0x0669), // Arabic-Indic digits RANGE(0x06F0, 0x06F9), // Eastern Arabic-Indic digits ) //====================================================================== // Japanese Katakana // DEFINE_CHAR_PROPERTY_AS_SET(katakana, 0x3099, // COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK 0x309A, // COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK 0x309B, // KATAKANA-HIRAGANA VOICED SOUND MARK 0x309C, // KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK RANGE(0x30A0, 0x30FF), // Fullwidth Katakana RANGE(0xFF65, 0xFF9F), // Halfwidth Katakana ) //====================================================================== // BiDi Directional Formatting Codes // // See http://www.unicode.org/reports/tr9/ for a description of Bidi // and http://www.unicode.org/charts/PDF/U2000.pdf for the character codes. DEFINE_CHAR_PROPERTY_AS_SET(directional_formatting_code, 0x200E, // LRM (Left-to-Right Mark) 0x200F, // RLM (Right-to-Left Mark) 0x202A, // LRE (Left-to-Right Embedding) 0x202B, // RLE (Right-to-Left Embedding) 0x202C, // PDF (Pop Directional Format) 0x202D, // LRO (Left-to-Right Override) 0x202E, // RLO (Right-to-Left Override) ) //====================================================================== // Special collections // // NB: This does not check for all punctuation and symbols in the // standard; just those listed in our code. See the definitions in // char_properties.cc DEFINE_CHAR_PROPERTY(punctuation_or_symbol, prop) { prop->AddCharProperty("punctuation"); prop->AddCharProperty("subscript_symbol"); prop->AddCharProperty("superscript_symbol"); prop->AddCharProperty("token_prefix_symbol"); prop->AddCharProperty("token_suffix_symbol"); } } // namespace syntaxnet
29,991
11,154
#include "Common.h" #include "Polygon.h" #include "Vector2.h" Polygon::Polygon() { _vertices.reset(new std::vector<Vector2>()); _perpendiculars.reset(new std::vector<Vector2>()); } void Polygon::operator=(const Polygon& source) { if (this == &source) return; _vertices->clear(); _perpendiculars->clear(); _vertices->insert(_vertices->end(), source._vertices->cbegin(), source._vertices->cend()); _perpendiculars->insert(_perpendiculars->end(), source._perpendiculars->cbegin(), source._perpendiculars->cend()); } void Polygon::AddVertexPoint(float x, float y) { AddVertexPoint(Vector2(x, y)); } void Polygon::AddVertexPoint(const Vector2& vertex) { _vertices->push_back(vertex); _numOfVertices++; _dirtyPerpendiculars = true; //New vertex means a new edge has been added. Perpendiculars need to be recalculated RecalculateCenterPoint(); } void Polygon::AddVertexPoint(const std::vector<Vector2>& vertices) { for (auto it = vertices.begin(); it != vertices.end(); it++) { AddVertexPoint(*it); } } /* Description: A getter which can trigger a Perpendicular recalculation if marked as dirty Returns: shared_ptr<vector<Vector2>> - Pointer to the cached perpendiculars for this Collider */ const std::shared_ptr<const std::vector<Vector2>> Polygon::GetPerpendiculars() const { if (_dirtyPerpendiculars) { RecalculatePerpendicularVectors(); } return _perpendiculars; } /* Description: Rotates each vertex point by "degrees" degrees clockwise. Sets the dirty flag for perpendiculars. Arguments: degrees - Clockwise rotatation */ void Polygon::Rotate(float degrees) { const float radians = CommonHelpers::DegToRad(degrees); for (int i = 0; i < _vertices->size(); i++) { float newX = (_vertices->at(i).x * cos(radians)) + (_vertices->at(i).y * sin(radians) * -1); float newY = (_vertices->at(i).x * sin(radians)) + (_vertices->at(i).y * cos(radians)); _vertices->at(i).x = newX; _vertices->at(i).y = newY; } if (degrees != 0) _dirtyPerpendiculars = true; } /* Description: Resets the current Perpendicular list. Goes through each edge in the polygon and calculates a clockwise perpendicular vector. Adds that vector to _perpendiculars. Clears the dirty flag */ void Polygon::RecalculatePerpendicularVectors() const { _perpendiculars->clear(); if (_vertices->size() >= 2) { for (int i = 0; i < _vertices->size() - 1; i++) { _perpendiculars->push_back(ClockwisePerpendicularVector(_vertices->at(i), _vertices->at(i + 1))); } //Wrap the last vertex to the first for the final polygon perpendicular _perpendiculars->push_back(ClockwisePerpendicularVector(_vertices->at(_vertices->size() - 1), _vertices->at(0))); } _dirtyPerpendiculars = false; } void Polygon::RecalculateCenterPoint() { float minX = INT_MAX, minY = INT_MAX; float maxX = INT_MIN, maxY = INT_MIN; for (int i = 0; i < _vertices->size(); i++) { Vector2 vertex(_vertices->at(i)); if (vertex.x < minX) minX = vertex.x; if (vertex.x > maxX) maxX = vertex.x; if (vertex.y < minY) minY = vertex.y; if (vertex.y > maxY) maxY = vertex.y; } Vector2 sizeVector(maxX - minX, maxY - minY); _center.x = (sizeVector.x / 2) + minX; _center.y = (sizeVector.y / 2) + minY; } Vector2 ClockwisePerpendicularVector(const Vector2& pointA, const Vector2& pointB) { const Vector2 clockwiseVector(pointB.x - pointA.x, pointB.y - pointA.y); return ClockwisePerpendicularVector(clockwiseVector); } Vector2 ClockwisePerpendicularVector(const Vector2& vector) { return Vector2(vector.y, -1 * vector.x); } Vector2 CounterClockwisePerpendicularVector(const Vector2& pointA, const Vector2& pointB) { const Vector2 counterClockwiseVector(pointB.x - pointA.x, pointB.y - pointA.y); return CounterClockwisePerpendicularVector(counterClockwiseVector); } Vector2 CounterClockwisePerpendicularVector(const Vector2& vector) { return Vector2(-1 * vector.y, vector.x); }
3,924
1,500
#include "libs.hh" #include "classes.hh" #include "headers.hh" namespace FractalSpace { void force_at_particle(Group& group, Fractal& fractal,const bool& conserve) { fractal.timing(-1,8); ofstream& FileFractal=fractal.p_file->DUMPS; vector <double> dens(8); vector <double> weights(8); vector <double> pott(8); vector <double> f_x(8); vector <double> f_y(8); vector <double> f_z(8); vector <double> sum_pf(4); Group* p_group=&group; double d_x,d_y,d_z; vector <double> pos(3); double d_inv=pow(2.0,group.get_level()-fractal.get_level_max()); const double scale=(double)(fractal.get_grid_length()*Misc::pow(2,fractal.get_level_max())); // for(auto &p : group.list_points) { Point& point=*p; if(point.list_particles.empty()) continue; bool not_yet=true; for(auto &part : point.list_particles) { Particle& particle=*part; if(!particle.get_real_particle()) continue; if(particle.get_p_highest_level_group() != 0) { if(conserve || p_group == particle.get_p_highest_level_group()) { if(not_yet) { point.get_field_values(pott,f_x,f_y,f_z); not_yet=false; } // particle.get_pos(pos); point.get_deltas(pos,d_x,d_y,d_z,scale,d_inv); Misc::set_weights(weights,d_x,d_y,d_z); Misc::sum_prod<double>(0,7,1,sum_pf,weights,pott,f_x,f_y,f_z); particle.set_field_pf(sum_pf); if(sum_pf[0]*sum_pf[1]*sum_pf[2]*sum_pf[3] ==0.0) particle.dump(FileFractal,pott,f_x,f_y,f_z); } } else { particle.dump(FileFractal); particle.set_field_pf(0.0); } } } fractal.timing(1,8); } }
1,695
772
// Copyright 2014 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/chromeos/login/easy_unlock/easy_unlock_user_login_flow.h" #include "base/metrics/histogram_macros.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" namespace chromeos { EasyUnlockUserLoginFlow::EasyUnlockUserLoginFlow(const AccountId& account_id) : ExtendedUserFlow(account_id) {} EasyUnlockUserLoginFlow::~EasyUnlockUserLoginFlow() {} bool EasyUnlockUserLoginFlow::CanLockScreen() { return true; } bool EasyUnlockUserLoginFlow::CanStartArc() { return true; } bool EasyUnlockUserLoginFlow::ShouldLaunchBrowser() { return true; } bool EasyUnlockUserLoginFlow::ShouldSkipPostLoginScreens() { return false; } bool EasyUnlockUserLoginFlow::HandleLoginFailure(const AuthFailure& failure) { SmartLockMetricsRecorder::RecordAuthResultSignInFailure( SmartLockMetricsRecorder::SmartLockAuthResultFailureReason:: kUserControllerSignInFailure); UMA_HISTOGRAM_ENUMERATION( "SmartLock.AuthResult.SignIn.Failure.UserControllerAuth", failure.reason(), AuthFailure::FailureReason::NUM_FAILURE_REASONS); Profile* profile = ProfileHelper::GetSigninProfile(); EasyUnlockService* service = EasyUnlockService::Get(profile); if (!service) return false; service->HandleAuthFailure(account_id()); service->RecordEasySignInOutcome(account_id(), false); UnregisterFlowSoon(); return true; } void EasyUnlockUserLoginFlow::HandleLoginSuccess(const UserContext& context) { Profile* profile = ProfileHelper::GetSigninProfile(); EasyUnlockService* service = EasyUnlockService::Get(profile); if (!service) return; service->RecordEasySignInOutcome(account_id(), true); } void EasyUnlockUserLoginFlow::HandleOAuthTokenStatusChange( user_manager::User::OAuthTokenStatus status) {} void EasyUnlockUserLoginFlow::LaunchExtraSteps(Profile* profile) {} bool EasyUnlockUserLoginFlow::SupportsEarlyRestartToApplyFlags() { return true; } } // namespace chromeos
2,195
711
#include <cstdio> #include <cstring> #include <stack> #include <vector> #include <algorithm> #include <unordered_map> using namespace std; #define NMAX 200000 #define MEMSIZE 1800000 struct Pair { int u, v; bool operator==(const Pair &z) const { return u == z.u && v == z.v; } }; namespace std { template <> struct hash<Pair> { size_t operator()(const Pair &z) const { static hash<int> H; return H(z.u) ^ H(z.v); } }; } int n, m; vector<int> G[NMAX + 10], T[NMAX + 10]; bool marked[NMAX + 10]; int in[NMAX + 10], low[NMAX + 10], cur, cnt; void bcc(int u, int f = 0) { static stack<Pair> stk; in[u] = low[u] = ++cur; for (int v : G[u]) { if (v == f) f = 0; else if (in[v]) low[u] = min(low[u], in[v]); else { stk.push(Pair{u, v}); bcc(v, u); low[u] = min(low[u], low[v]); if (low[v] > in[u]) { T[u].push_back(v); T[v].push_back(u); stk.pop(); } else if (low[v] >= in[u]) { cnt++; int linked = 0, p = n + cnt; auto add = [p, &linked](int x) { if (!marked[x]) { marked[x] = true; T[p].push_back(x); T[x].push_back(p); linked++; } }; while (!stk.empty()) { Pair x = stk.top(); stk.pop(); add(x.u); add(x.v); if (x.u == u && x.v == v) break; } for (int v : T[p]) { marked[v] = false; } if (linked == 0) cnt--; } } } } struct Node { int sum; Node *lch, *rch; Node() { memset(this, 0, sizeof(Node)); } }; // Node mem[MEMSIZE]; // size_t mempos; // Node *allocate() { // auto r = mem + mempos; // mempos++; // memset(r, 0, sizeof(Node)); // return r; // } Node *single(int p, int xl, int xr) { // Node *x = allocate(); Node *x = new Node; x->sum = 1; Node *y = x; while (xl < xr) { int mi = (xl + xr) / 2; // Node *z = allocate(); Node *z = new Node; z->sum = 1; if (p <= mi) { y->lch = z; xr = mi; } else { y->rch = z; xl = mi + 1; } y = z; } return x; } Node *meld(Node *x, Node *y) { if (!x) return y; if (!y) return x; x->sum += y->sum; // assume disjoint x->lch = meld(x->lch, y->lch); x->rch = meld(x->rch, y->rch); delete y; return x; } void release(Node *x) { if (!x) return; release(x->lch); release(x->rch); delete x; } int maxp(Node *x, int xl, int xr) { // present if (xl == xr) return xl; int mi = (xl + xr) / 2; if (x->rch) return maxp(x->rch, mi + 1, xr); return maxp(x->lch, xl, mi); } int maxnp(Node *x, int xl, int xr) { // not present if (!x) return xr; int mi = (xl + xr) / 2; if (!x->rch || x->rch->sum < (xr - mi)) return maxnp(x->rch, mi + 1, xr); return maxnp(x->lch, xl, mi); } unordered_map<Pair, Pair> ans; Node *dfs(int u, int pa = 0) { Node *tr = NULL; for (int v : T[u]) if (v != pa) { auto t = dfs(v, u); tr = meld(tr, t); } tr = meld(tr, single(u, 1, n)); if (pa && pa <= n && u <= n) { Pair key = {u, pa}; if (key.u > key.v) swap(key.u, key.v); int mp = maxp(tr, 1, n); if (mp == n) mp = maxnp(tr, 1, n); ans[key] = {mp, mp + 1}; } return tr; } Pair key[NMAX + 10]; void initialize() { // mempos = 0; scanf("%d%d", &n, &m); memset(marked + 1, 0, 2 * n); memset(in + 1, 0, sizeof(int) * 2 * n); memset(low + 1, 0, sizeof(int) * 2 * n); cur = cnt = 0; for (int i = 1; i <= 2 * n; i++) { G[i].clear(); T[i].clear(); } ans.clear(); for (int i = 0; i < m; i++) { int u, v; scanf("%d%d", &u, &v); if (u > v) swap(u, v); key[i] = {u, v}; G[u].push_back(v); G[v].push_back(u); } bcc(1); auto t = dfs(1); release(t); for (int i = 0; i < m; i++) { auto it = ans.find(key[i]); if (it != ans.end()) printf("%d %d\n", it->second.u, it->second.v); else puts("0 0"); } } void _main() { initialize(); } int main() { int T; scanf("%d", &T); while (T--) { _main(); // fprintf(stderr, "mempos = %zu\n", mempos); } return 0; }
4,900
1,975
#pragma once #include <cstddef> #include <functional> #include <iostream> #include <vector> #include <realm/util/identifier.hpp> #include <realm/util/type_traits.hpp> namespace realm { /** * @brief Memory layout * Describes a particular layout of memory. Inspired by Rust's alloc::Layout. * @ref https://doc.rust-lang.org/std/alloc/struct.Layout.html */ struct memory_layout { const unsigned size{ 0 }; const unsigned align{ 0 }; constexpr memory_layout() = default; constexpr memory_layout(const unsigned size, const unsigned align) : size{ size } , align{ align } { /** * TODO: add some necessary checks, eg. align has to be power of 2 * see Rust impl. for examples */ } /** * Create a memory layout of a specified type * @tparam T * @return */ template<typename T> static constexpr memory_layout of() { return { sizeof(T), alignof(T) }; } /** * @brief Returns the amount of padding that has to be added to size to satisfy the * layouts alignment * @param size * @param align * @return Padding to insert */ static constexpr int align_up(const int size, const int align) noexcept { return (size + (align - 1)) & !(align - 1); } [[nodiscard]] constexpr int align_up(const int size) const noexcept { return align_up(size, align); } }; /** * @brief Component meta * Describes component metadata of a specified type. */ struct component_meta { const u64 hash{ 0 }; const u64 mask{ 0 }; constexpr component_meta() = default; constexpr component_meta(const u64 hash, const u64 mask) : hash{ hash } , mask{ mask } {}; /** * Create component meta of a type. * @tparam T * @return */ template<typename T> static constexpr internal::enable_if_component<T, component_meta> of() { return component_meta{ internal::identifier_hash_v<internal::pure_t<T>>, internal::identifier_mask_v<internal::pure_t<T>> }; } }; /** * @brief Component * Describes a component (metadata, memory layout & functions for construction and * destruction). */ struct component { using constructor_t = void(void*); const component_meta meta; const memory_layout layout; constructor_t* alloc{ nullptr }; constructor_t* destroy{ nullptr }; constexpr component() = default; constexpr component( component_meta meta, memory_layout layout, constructor_t* alloc, constructor_t* destroy) : meta{ meta } , layout{ layout } , alloc{ alloc } , destroy{ destroy } {} constexpr bool operator==(const component& other) const { return other.meta.hash == meta.hash; } /** * Create a component of a specified type * @tparam T * @return */ template<typename T> static constexpr internal::enable_if_component<T, component> of() { return { component_meta::of<T>(), memory_layout::of<T>(), [](void* ptr) { new (ptr) T{}; }, [](void* ptr) { static_cast<T*>(ptr)->~T(); } }; } }; /** * @brief Singleton component * Singleton component base class */ struct singleton_component { singleton_component() = default; singleton_component(component&& comp) : component_info{ comp } {}; virtual ~singleton_component() = default; const component component_info; }; /** * @brief Singleton instance * Stores a single component using a unique_ptr. * Currently used in world to store singleton components. * @tparam T */ template<typename T> struct singleton_instance final : singleton_component { explicit singleton_instance(T& t) : singleton_component{ component::of<T>() } , instance_{ std::unique_ptr<T>(std::move(t)) } {} template<typename... Args> explicit singleton_instance(Args&&... args) : singleton_component{ component::of<T>() } , instance_{ std::make_unique<T>(std::forward<Args>(args)...) } {} /** * Get the underlying component instance * @return Pointer to component instance */ T* get() { return static_cast<T*>(instance_.get()); } private: const std::unique_ptr<T> instance_; }; } // namespace realm /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace std { template<> struct hash<realm::component> { size_t operator()(const realm::component& c) const noexcept { return (hash<size_t>{}(c.meta.hash)); } }; } // namespace std
4,596
1,379
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // 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 "schema-parser.h" #include "message.h" #include <capnp/compiler/compiler.h> #include <capnp/compiler/lexer.capnp.h> #include <capnp/compiler/lexer.h> #include <capnp/compiler/grammar.capnp.h> #include <capnp/compiler/parser.h> #include <unordered_map> #include <kj/mutex.h> #include <kj/vector.h> #include <kj/debug.h> #include <kj/io.h> #include <map> namespace capnp { namespace { template <typename T> size_t findLargestElementBefore(const kj::Vector<T>& vec, const T& key) { KJ_REQUIRE(vec.size() > 0 && vec[0] <= key); size_t lower = 0; size_t upper = vec.size(); while (upper - lower > 1) { size_t mid = (lower + upper) / 2; if (vec[mid] > key) { upper = mid; } else { lower = mid; } } return lower; } } // namespace // ======================================================================================= class SchemaParser::ModuleImpl final: public compiler::Module { public: ModuleImpl(const SchemaParser& parser, kj::Own<const SchemaFile>&& file) : parser(parser), file(kj::mv(file)) {} kj::StringPtr getSourceName() override { return file->getDisplayName(); } Orphan<compiler::ParsedFile> loadContent(Orphanage orphanage) override { kj::Array<const char> content = file->readContent(); lineBreaks.get([&](kj::SpaceFor<kj::Vector<uint>>& space) { auto vec = space.construct(content.size() / 40); vec->add(0); for (const char* pos = content.begin(); pos < content.end(); ++pos) { if (*pos == '\n') { vec->add(pos + 1 - content.begin()); } } return vec; }); MallocMessageBuilder lexedBuilder; auto statements = lexedBuilder.initRoot<compiler::LexedStatements>(); compiler::lex(content, statements, *this); auto parsed = orphanage.newOrphan<compiler::ParsedFile>(); compiler::parseFile(statements.getStatements(), parsed.get(), *this); return parsed; } kj::Maybe<Module&> importRelative(kj::StringPtr importPath) override { KJ_IF_MAYBE(importedFile, file->import(importPath)) { return parser.getModuleImpl(kj::mv(*importedFile)); } else { return nullptr; } } kj::Maybe<kj::Array<const byte>> embedRelative(kj::StringPtr embedPath) override { KJ_IF_MAYBE(importedFile, file->import(embedPath)) { return importedFile->get()->readContent().releaseAsBytes(); } else { return nullptr; } } void addError(uint32_t startByte, uint32_t endByte, kj::StringPtr message) override { auto& lines = lineBreaks.get( [](kj::SpaceFor<kj::Vector<uint>>& space) { KJ_FAIL_REQUIRE("Can't report errors until loadContent() is called."); return space.construct(); }); // TODO(someday): This counts tabs as single characters. Do we care? uint startLine = findLargestElementBefore(lines, startByte); uint startCol = startByte - lines[startLine]; uint endLine = findLargestElementBefore(lines, endByte); uint endCol = endByte - lines[endLine]; file->reportError( SchemaFile::SourcePos { startByte, startLine, startCol }, SchemaFile::SourcePos { endByte, endLine, endCol }, message); // We intentionally only set hadErrors true if reportError() didn't throw. parser.hadErrors = true; } bool hadErrors() override { return parser.hadErrors; } private: const SchemaParser& parser; kj::Own<const SchemaFile> file; kj::Lazy<kj::Vector<uint>> lineBreaks; // Byte offsets of the first byte in each source line. The first element is always zero. // Initialized the first time the module is loaded. }; // ======================================================================================= namespace { struct SchemaFileHash { inline bool operator()(const SchemaFile* f) const { return f->hashCode(); } }; struct SchemaFileEq { inline bool operator()(const SchemaFile* a, const SchemaFile* b) const { return *a == *b; } }; } // namespace struct SchemaParser::DiskFileCompat { // Stuff we only create if parseDiskFile() is ever called, in order to translate that call into // KJ filesystem API calls. kj::Own<kj::Filesystem> ownFs; kj::Filesystem& fs; struct ImportDir { kj::String pathStr; kj::Path path; kj::Own<const kj::ReadableDirectory> dir; }; std::map<kj::StringPtr, ImportDir> cachedImportDirs; std::map<std::pair<const kj::StringPtr*, size_t>, kj::Array<const kj::ReadableDirectory*>> cachedImportPaths; DiskFileCompat(): ownFs(kj::newDiskFilesystem()), fs(*ownFs) {} DiskFileCompat(kj::Filesystem& fs): fs(fs) {} }; struct SchemaParser::Impl { typedef std::unordered_map< const SchemaFile*, kj::Own<ModuleImpl>, SchemaFileHash, SchemaFileEq> FileMap; kj::MutexGuarded<FileMap> fileMap; compiler::Compiler compiler; kj::MutexGuarded<kj::Maybe<DiskFileCompat>> compat; }; SchemaParser::SchemaParser(): impl(kj::heap<Impl>()) {} SchemaParser::~SchemaParser() noexcept(false) {} ParsedSchema SchemaParser::parseFromDirectory( const kj::ReadableDirectory& baseDir, kj::Path path, kj::ArrayPtr<const kj::ReadableDirectory* const> importPath) const { return parseFile(SchemaFile::newFromDirectory(baseDir, kj::mv(path), importPath)); } ParsedSchema SchemaParser::parseDiskFile( kj::StringPtr displayName, kj::StringPtr diskPath, kj::ArrayPtr<const kj::StringPtr> importPath) const { auto lock = impl->compat.lockExclusive(); DiskFileCompat* compat; KJ_IF_MAYBE(c, *lock) { compat = c; } else { compat = &lock->emplace(); } auto& root = compat->fs.getRoot(); auto cwd = compat->fs.getCurrentPath(); const kj::ReadableDirectory* baseDir = &root; kj::Path path = cwd.evalNative(diskPath); kj::ArrayPtr<const kj::ReadableDirectory* const> translatedImportPath = nullptr; if (importPath.size() > 0) { auto importPathKey = std::make_pair(importPath.begin(), importPath.size()); auto& slot = compat->cachedImportPaths[importPathKey]; if (slot == nullptr) { slot = KJ_MAP(path, importPath) -> const kj::ReadableDirectory* { auto iter = compat->cachedImportDirs.find(path); if (iter != compat->cachedImportDirs.end()) { return iter->second.dir; } auto parsed = cwd.evalNative(path); kj::Own<const kj::ReadableDirectory> dir; KJ_IF_MAYBE(d, root.tryOpenSubdir(parsed)) { dir = kj::mv(*d); } else { // Ignore paths that don't exist. dir = kj::newInMemoryDirectory(kj::nullClock()); } const kj::ReadableDirectory* result = dir; kj::StringPtr pathRef = path; KJ_ASSERT(compat->cachedImportDirs.insert(std::make_pair(pathRef, DiskFileCompat::ImportDir { kj::str(path), kj::mv(parsed), kj::mv(dir) })).second); return result; }; } translatedImportPath = slot; // Check if `path` appears to be inside any of the import path directories. If so, adjust // to be relative to that directory rather than absolute. kj::Maybe<DiskFileCompat::ImportDir&> matchedImportDir; size_t bestMatchLength = 0; for (auto importDir: importPath) { auto iter = compat->cachedImportDirs.find(importDir); KJ_ASSERT(iter != compat->cachedImportDirs.end()); if (path.startsWith(iter->second.path)) { // Looks like we're trying to load a file from inside this import path. Treat the import // path as the base directory. if (iter->second.path.size() > bestMatchLength) { bestMatchLength = iter->second.path.size(); matchedImportDir = iter->second; } } } KJ_IF_MAYBE(match, matchedImportDir) { baseDir = match->dir; path = path.slice(match->path.size(), path.size()).clone(); } } return parseFile(SchemaFile::newFromDirectory( *baseDir, kj::mv(path), translatedImportPath, kj::str(displayName))); } void SchemaParser::setDiskFilesystem(kj::Filesystem& fs) { auto lock = impl->compat.lockExclusive(); KJ_REQUIRE(*lock == nullptr, "already called parseDiskFile() or setDiskFilesystem()"); lock->emplace(fs); } ParsedSchema SchemaParser::parseFile(kj::Own<SchemaFile>&& file) const { KJ_DEFER(impl->compiler.clearWorkspace()); uint64_t id = impl->compiler.add(getModuleImpl(kj::mv(file))).getId(); impl->compiler.eagerlyCompile(id, compiler::Compiler::NODE | compiler::Compiler::CHILDREN | compiler::Compiler::DEPENDENCIES | compiler::Compiler::DEPENDENCY_DEPENDENCIES); return ParsedSchema(impl->compiler.getLoader().get(id), *this); } kj::Maybe<schema::Node::SourceInfo::Reader> SchemaParser::getSourceInfo(Schema schema) const { return impl->compiler.getSourceInfo(schema.getProto().getId()); } SchemaParser::ModuleImpl& SchemaParser::getModuleImpl(kj::Own<SchemaFile>&& file) const { auto lock = impl->fileMap.lockExclusive(); auto insertResult = lock->insert(std::make_pair(file.get(), kj::Own<ModuleImpl>())); if (insertResult.second) { // This is a newly-inserted entry. Construct the ModuleImpl. insertResult.first->second = kj::heap<ModuleImpl>(*this, kj::mv(file)); } return *insertResult.first->second; } SchemaLoader& SchemaParser::getLoader() { return impl->compiler.getLoader(); } const SchemaLoader& SchemaParser::getLoader() const { return impl->compiler.getLoader(); } kj::Maybe<ParsedSchema> ParsedSchema::findNested(kj::StringPtr name) const { // TODO(someday): lookup() doesn't handle generics correctly. Use the ModuleScope/CompiledType // interface instead. We can also add an applybrand() method to ParsedSchema using those // interfaces, which would allow us to expose generics more explicitly to e.g. Python. return parser->impl->compiler.lookup(getProto().getId(), name).map( [this](uint64_t childId) { return ParsedSchema(parser->impl->compiler.getLoader().get(childId), *parser); }); } ParsedSchema ParsedSchema::getNested(kj::StringPtr nestedName) const { KJ_IF_MAYBE(nested, findNested(nestedName)) { return *nested; } else { KJ_FAIL_REQUIRE("no such nested declaration", getProto().getDisplayName(), nestedName); } } ParsedSchema::ParsedSchemaList ParsedSchema::getAllNested() const { return ParsedSchemaList(*this, getProto().getNestedNodes()); } schema::Node::SourceInfo::Reader ParsedSchema::getSourceInfo() const { return KJ_ASSERT_NONNULL(parser->getSourceInfo(*this)); } // ------------------------------------------------------------------- ParsedSchema ParsedSchema::ParsedSchemaList::operator[](uint index) const { return ParsedSchema( parent.parser->impl->compiler.getLoader().get(list[index].getId()), *parent.parser); } // ------------------------------------------------------------------- class SchemaFile::DiskSchemaFile final: public SchemaFile { public: DiskSchemaFile(const kj::ReadableDirectory& baseDir, kj::Path pathParam, kj::ArrayPtr<const kj::ReadableDirectory* const> importPath, kj::Own<const kj::ReadableFile> file, kj::Maybe<kj::String> displayNameOverride) : baseDir(baseDir), path(kj::mv(pathParam)), importPath(importPath), file(kj::mv(file)) { KJ_IF_MAYBE(dn, displayNameOverride) { displayName = kj::mv(*dn); displayNameOverridden = true; } else { displayName = path.toString(); displayNameOverridden = false; } } kj::StringPtr getDisplayName() const override { return displayName; } kj::Array<const char> readContent() const override { return file->mmap(0, file->stat().size).releaseAsChars(); } kj::Maybe<kj::Own<SchemaFile>> import(kj::StringPtr target) const override { if (target.startsWith("/")) { auto parsed = kj::Path::parse(target.slice(1)); for (auto candidate: importPath) { KJ_IF_MAYBE(newFile, candidate->tryOpenFile(parsed)) { return kj::implicitCast<kj::Own<SchemaFile>>(kj::heap<DiskSchemaFile>( *candidate, kj::mv(parsed), importPath, kj::mv(*newFile), nullptr)); } } return nullptr; } else { auto parsed = path.parent().eval(target); kj::Maybe<kj::String> displayNameOverride; if (displayNameOverridden) { // Try to create a consistent display name override for the imported file. This is for // backwards-compatibility only -- display names are only overridden when using the // deprecated parseDiskFile() interface. kj::runCatchingExceptions([&]() { displayNameOverride = kj::Path::parse(displayName).parent().eval(target).toString(); }); } KJ_IF_MAYBE(newFile, baseDir.tryOpenFile(parsed)) { return kj::implicitCast<kj::Own<SchemaFile>>(kj::heap<DiskSchemaFile>( baseDir, kj::mv(parsed), importPath, kj::mv(*newFile), kj::mv(displayNameOverride))); } else { return nullptr; } } } bool operator==(const SchemaFile& other) const override { auto& other2 = kj::downcast<const DiskSchemaFile>(other); return &baseDir == &other2.baseDir && path == other2.path; } bool operator!=(const SchemaFile& other) const override { return !operator==(other); } size_t hashCode() const override { // djb hash with xor // TODO(someday): Add hashing library to KJ. size_t result = reinterpret_cast<uintptr_t>(&baseDir); for (auto& part: path) { for (char c: part) { result = (result * 33) ^ c; } result = (result * 33) ^ '/'; } return result; } void reportError(SourcePos start, SourcePos end, kj::StringPtr message) const override { kj::getExceptionCallback().onRecoverableException(kj::Exception( kj::Exception::Type::FAILED, path.toString(), start.line, kj::heapString(message))); } private: const kj::ReadableDirectory& baseDir; kj::Path path; kj::ArrayPtr<const kj::ReadableDirectory* const> importPath; kj::Own<const kj::ReadableFile> file; kj::String displayName; bool displayNameOverridden; }; kj::Own<SchemaFile> SchemaFile::newFromDirectory( const kj::ReadableDirectory& baseDir, kj::Path path, kj::ArrayPtr<const kj::ReadableDirectory* const> importPath, kj::Maybe<kj::String> displayNameOverride) { return kj::heap<DiskSchemaFile>(baseDir, kj::mv(path), importPath, baseDir.openFile(path), kj::mv(displayNameOverride)); } } // namespace capnp
15,669
5,124
#ifndef SimPPS_PPSPixelDigiProducer_PPSPixelDigiProducer_h #define SimPPS_PPSPixelDigiProducer_PPSPixelDigiProducer_h // -*- C++ -*- // // Package: PPSPixelDigiProducer // Class: CTPPSPixelDigiProducer // /**\class CTPPSPixelDigiProducer PPSPixelDigiProducer.cc SimPPS/PPSPixelDigiProducer/plugins/PPSPixelDigiProducer.cc Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: F.Ferro // // system include files #include <memory> #include <vector> #include <map> #include <string> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" // **** CTPPS #include "DataFormats/CTPPSDigi/interface/CTPPSPixelDigi.h" #include "DataFormats/CTPPSDigi/interface/CTPPSPixelDigiCollection.h" #include "SimPPS/PPSPixelDigiProducer/interface/RPixDetDigitizer.h" #include "SimDataFormats/CrossingFrame/interface/MixCollection.h" #include "DataFormats/Common/interface/DetSet.h" // DB #include "CondFormats/DataRecord/interface/CTPPSPixelDAQMappingRcd.h" #include "CondFormats/DataRecord/interface/CTPPSPixelAnalysisMaskRcd.h" #include "CondFormats/DataRecord/interface/CTPPSPixelGainCalibrationsRcd.h" #include "CondFormats/PPSObjects/interface/CTPPSPixelDAQMapping.h" #include "CondFormats/PPSObjects/interface/CTPPSPixelAnalysisMask.h" #include "CondFormats/PPSObjects/interface/CTPPSPixelGainCalibrations.h" // user include files #include "SimDataFormats/TrackingHit/interface/PSimHitContainer.h" #include "SimDataFormats/TrackingHit/interface/PSimHit.h" #include "SimDataFormats/CrossingFrame/interface/CrossingFrame.h" #include "SimDataFormats/CrossingFrame/interface/MixCollection.h" #include <cstdlib> // I need it for random numbers //needed for the geometry: #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "DataFormats/Common/interface/DetSetVector.h" //Random Number #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/Utilities/interface/RandomNumberGenerator.h" #include "FWCore/Utilities/interface/Exception.h" #include "CLHEP/Random/RandomEngine.h" namespace CLHEP { class HepRandomEngine; } class CTPPSPixelDigiProducer : public edm::stream::EDProducer<> { public: explicit CTPPSPixelDigiProducer(const edm::ParameterSet&); ~CTPPSPixelDigiProducer() override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void produce(edm::Event&, const edm::EventSetup&) override; // ----------member data --------------------------- std::vector<std::string> RPix_hit_containers_; typedef std::map<unsigned int, std::vector<PSimHit>> simhit_map; typedef simhit_map::iterator simhit_map_iterator; edm::ParameterSet conf_; std::map<uint32_t, std::unique_ptr<RPixDetDigitizer>> theAlgoMap; //DetId = uint32_t CLHEP::HepRandomEngine* rndEngine_ = nullptr; int verbosity_; edm::EDGetTokenT<CrossingFrame<PSimHit>> tokenCrossingFramePPSPixel; edm::ESGetToken<CTPPSPixelGainCalibrations, CTPPSPixelGainCalibrationsRcd> gainCalibESToken_; }; CTPPSPixelDigiProducer::CTPPSPixelDigiProducer(const edm::ParameterSet& conf) : conf_(conf), gainCalibESToken_(esConsumes()) { produces<edm::DetSetVector<CTPPSPixelDigi>>(); // register data to consume tokenCrossingFramePPSPixel = consumes<CrossingFrame<PSimHit>>(edm::InputTag("mix", "g4SimHitsCTPPSPixelHits")); RPix_hit_containers_.clear(); RPix_hit_containers_ = conf.getParameter<std::vector<std::string>>("ROUList"); verbosity_ = conf.getParameter<int>("RPixVerbosity"); } CTPPSPixelDigiProducer::~CTPPSPixelDigiProducer() {} void CTPPSPixelDigiProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; // all distances in [mm] // RPDigiProducer desc.add<std::vector<std::string>>("ROUList", {"CTPPSPixelHits"}); desc.add<int>("RPixVerbosity", 0); desc.add<bool>("CTPPSPixelDigiSimHitRelationsPersistence", false); // save links betweend digi, clusters and OSCAR/Geant4 hits // RPDetDigitizer desc.add<double>("RPixEquivalentNoiseCharge", 1000.0); desc.add<bool>("RPixNoNoise", false); // RPDisplacementGenerator desc.add<double>("RPixGeVPerElectron", 3.61e-09); desc.add<std::vector<double>>("RPixInterSmearing", {0.011}); desc.add<bool>("RPixLandauFluctuations", true); desc.add<int>("RPixChargeDivisions", 20); desc.add<double>("RPixDeltaProductionCut", 0.120425); // [MeV] // RPixChargeShare desc.add<std::string>("ChargeMapFile2E", "SimPPS/PPSPixelDigiProducer/data/PixelChargeMap.txt"); desc.add<std::string>("ChargeMapFile2E_2X", "SimPPS/PPSPixelDigiProducer/data/PixelChargeMap_2X.txt"); desc.add<std::string>("ChargeMapFile2E_2Y", "SimPPS/PPSPixelDigiProducer/data/PixelChargeMap_2Y.txt"); desc.add<std::string>("ChargeMapFile2E_2X2Y", "SimPPS/PPSPixelDigiProducer/data/PixelChargeMap_2X2Y.txt"); desc.add<double>( "RPixCoupling", 0.250); // fraction of the remaining charge going to the closer neighbour pixel. Value = 0.135, Value = 0.0 bypass the charge map and the charge sharing approach // RPixDummyROCSimulator desc.add<double>("RPixDummyROCThreshold", 1900.0); desc.add<double>("RPixDummyROCElectronPerADC", 135.0); // 210.0 to be verified desc.add<int>("VCaltoElectronGain", 50); // same values as in RPixDetClusterizer desc.add<int>("VCaltoElectronOffset", -411); // desc.add<bool>("doSingleCalibration", false); // desc.add<double>("RPixDeadPixelProbability", 0.001); desc.add<bool>("RPixDeadPixelSimulationOn", true); // CTPPSPixelSimTopology desc.add<double>("RPixActiveEdgeSmearing", 0.020); desc.add<double>("RPixActiveEdgePosition", 0.150); desc.add<std::string>("mixLabel", "mix"); desc.add<std::string>("InputCollection", "g4SimHitsCTPPSPixelHits"); descriptions.add("RPixDetDigitizer", desc); } // // member functions // // ------------ method called to produce the data ------------ void CTPPSPixelDigiProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; if (!rndEngine_) { Service<RandomNumberGenerator> rng; if (!rng.isAvailable()) { throw cms::Exception("Configuration") << "This class requires the RandomNumberGeneratorService\n" "which is not present in the configuration file. You must add the service\n" "in the configuration file or remove the modules that require it."; } rndEngine_ = &(rng->getEngine(iEvent.streamID())); } // get calibration DB const auto& gainCalibration = iSetup.getData(gainCalibESToken_); // Step A: Get Inputs edm::Handle<CrossingFrame<PSimHit>> cf; iEvent.getByToken(tokenCrossingFramePPSPixel, cf); if (verbosity_) { edm::LogInfo("PPSPixelDigiProducer") << "\n\n=================== Starting SimHit access" << " ==================="; MixCollection<PSimHit> col{cf.product(), std::pair(-0, 0)}; edm::LogInfo("PPSPixelDigiProducer") << col; MixCollection<PSimHit>::iterator cfi; int count = 0; for (cfi = col.begin(); cfi != col.end(); cfi++) { edm::LogInfo("PPSPixelDigiProducer") << " Hit " << count << " has tof " << cfi->timeOfFlight() << " trackid " << cfi->trackId() << " bunchcr " << cfi.bunch() << " trigger " << cfi.getTrigger() << ", from EncodedEventId: " << cfi->eventId().bunchCrossing() << " " << cfi->eventId().event() << " bcr from MixCol " << cfi.bunch(); edm::LogInfo("PPSPixelDigiProducer") << " Hit: " << (*cfi) << " " << cfi->exitPoint(); count++; } } MixCollection<PSimHit> allRPixHits{cf.product(), std::pair(0, 0)}; if (verbosity_) edm::LogInfo("PPSPixelDigiProducer") << "Input MixCollection size = " << allRPixHits.size(); //Loop on PSimHit simhit_map SimHitMap; SimHitMap.clear(); MixCollection<PSimHit>::iterator isim; for (isim = allRPixHits.begin(); isim != allRPixHits.end(); ++isim) { SimHitMap[(*isim).detUnitId()].push_back((*isim)); } // Step B: LOOP on hits in event std::vector<edm::DetSet<CTPPSPixelDigi>> theDigiVector; theDigiVector.reserve(400); theDigiVector.clear(); for (simhit_map_iterator it = SimHitMap.begin(); it != SimHitMap.end(); ++it) { edm::DetSet<CTPPSPixelDigi> digi_collector(it->first); if (theAlgoMap.find(it->first) == theAlgoMap.end()) { theAlgoMap[it->first] = std::make_unique<RPixDetDigitizer>(conf_, *rndEngine_, it->first, iSetup); //a digitizer for eny detector } std::vector<int> input_links; std::vector<std::vector<std::pair<int, double>>> output_digi_links; // links to simhits theAlgoMap.at(it->first)->run( SimHitMap[it->first], input_links, digi_collector.data, output_digi_links, &gainCalibration); if (!digi_collector.data.empty()) { theDigiVector.push_back(digi_collector); } } std::unique_ptr<edm::DetSetVector<CTPPSPixelDigi>> digi_output(new edm::DetSetVector<CTPPSPixelDigi>(theDigiVector)); if (verbosity_) { edm::LogInfo("PPSPixelDigiProducer") << "digi_output->size()=" << digi_output->size(); } iEvent.put(std::move(digi_output)); } DEFINE_FWK_MODULE(CTPPSPixelDigiProducer); #endif
9,716
3,632
#include <ros/ros.h> #include "GpsKalmanFilter.h" int main(int argc, char** argv) { ros::init(argc, argv, "gps_kalman_filter"); ros::NodeHandle n; ros::NodeHandle pn("~"); gps_kalman_filter::GpsKalmanFilter node(n, pn); ros::spin(); }
251
115
/*ckwg +29 * Copyright 2012-2018 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <test_common.h> #include <sprokit/pipeline_util/pipeline_builder.h> #include <sprokit/pipeline_util/pipe_bakery.h> #include <sprokit/pipeline_util/pipe_bakery_exception.h> #include <sprokit/pipeline_util/load_pipe_exception.h> #include <sprokit/pipeline/pipeline.h> #include <sprokit/pipeline/process_cluster.h> #include <sprokit/pipeline/process_factory.h> #include <sprokit/pipeline/scheduler.h> #include <sprokit/pipeline/scheduler_factory.h> #include <kwiversys/SystemTools.hxx> #include <exception> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <memory> #include <cstdlib> #define TEST_ARGS (kwiver::vital::path_t const& pipe_file) DECLARE_TEST_MAP(); /// \todo Add tests for clusters without ports or processes. static std::string const pipe_ext = ".pipe"; int main( int argc, char* argv[] ) { CHECK_ARGS( 2 ); std::string const testname = argv[1]; kwiver::vital::path_t const pipe_dir = argv[2]; kwiver::vital::path_t const pipe_file = pipe_dir + "/" + testname + pipe_ext; RUN_TEST( testname, pipe_file ); } // ---------------------------------------------------------------------------- sprokit::pipe_blocks load_pipe_blocks_from_file( kwiver::vital::path_t const& pipe_file ) { sprokit::pipeline_builder builder; builder.load_pipeline( pipe_file ); return builder.pipeline_blocks(); } // ---------------------------------------------------------------------------- sprokit::cluster_blocks load_cluster_blocks_from_file( kwiver::vital::path_t const& pipe_file ) { sprokit::pipeline_builder builder; builder.load_pipeline( pipe_file ); return builder.cluster_blocks(); } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block_block ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); { const auto mykey = kwiver::vital::config_block_key_t( "myblock:foo:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } { const auto mykey = kwiver::vital::config_block_key_t( "myblock:foo:oldkey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "oldvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block_relativepath ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:otherkey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const std::string cwd = kwiversys::SystemTools::GetFilenamePath( pipe_file ); const auto expected = cwd + "/" + "value"; if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block_long_block ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:foo:a:b:c:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block_nested_block ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:foo:bar:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_block_notalnum ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "my_block:my-key" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } const auto myotherkey = kwiver::vital::config_block_key_t( "my-block:my_key" ); const auto myothervalue = conf->get_value< kwiver::vital::config_block_value_t > ( myotherkey ); const auto otherexpected = kwiver::vital::config_block_value_t( "myothervalue" ); if ( myothervalue != otherexpected ) { TEST_ERROR( "Configuration was not correct: Expected: " << otherexpected << " Received: " << myothervalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_value_spaces ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "my value with spaces" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not correct: Expected: " << expected << " Received: " << myvalue ); } const auto mytabkey = kwiver::vital::config_block_key_t( "myblock:mytabs" ); const auto mytabvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mytabkey ); const auto tabexpected = kwiver::vital::config_block_value_t( "my value with tabs"); if ( mytabvalue != tabexpected ) { TEST_ERROR( "Configuration was not correct: Expected: " << tabexpected << " Received: " << mytabvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_overrides ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myothervalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not overridden: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_read_only ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const config = sprokit::extract_configuration( blocks ); const auto rokey = kwiver::vital::config_block_key_t( "myblock:mykey" ); if ( ! config->is_read_only( rokey ) ) { TEST_ERROR( "The configuration value was not marked as read only" ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_not_a_flag ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( sprokit::unrecognized_config_flag_exception, sprokit::extract_configuration( blocks ), "using an unknown flag" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_read_only_override ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( kwiver::vital::set_on_read_only_value_exception, sprokit::extract_configuration( blocks ), "setting a read-only value" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_ro ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was not appended: Expected: " << expected << " Received: " << myvalue ); } if ( ! conf->is_read_only( mykey ) ) { TEST_ERROR( "The configuration value was not marked as read only" ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_provided ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was not appended: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_provided_ro ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was not appended: Expected: " << expected << " Received: " << myvalue ); } if ( ! conf->is_read_only( mykey ) ) { TEST_ERROR( "The configuration value was not marked as read only" ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_comma ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue,othervalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was not appended with a comma separator: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_space_empty ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "othervalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was created with a space separator: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_append_path ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); kwiver::vital::path_t const expected = kwiver::vital::path_t( "myvalue" ) + "/" + kwiver::vital::path_t( "othervalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration value was not appended with a path separator: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_dotted_key ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:dotted.key" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "value" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not read properly: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_dotted_nested_key ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:dotted:nested.key:subkey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "value" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not read properly: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_provider_conf ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const conf = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myotherblock:mykey" ); const auto myvalue = conf->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "myvalue" ); if ( myvalue != expected ) { TEST_ERROR( "Configuration was not overridden: Expected: " << expected << " Received: " << myvalue ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_provider_conf_dep ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( sprokit::provider_error_exception, sprokit::extract_configuration( blocks ), "Referencing config key not defined yet" ); } // ------------------------------------------------------------------ TEST_PROPERTY( ENVIRONMENT, TEST_ENV = expected ) IMPLEMENT_TEST( config_provider_env ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const config = sprokit::extract_configuration( blocks ); const auto mykey = kwiver::vital::config_block_key_t( "myblock:myenv" ); const auto value = config->get_value< kwiver::vital::config_block_value_t > ( mykey ); const auto expected = kwiver::vital::config_block_value_t( "expected" ); if ( value != expected ) { TEST_ERROR( "Environment was not read properly: Expected: " << expected << " Received: " << value ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_provider_read_only ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); kwiver::vital::config_block_sptr const config = sprokit::extract_configuration( blocks ); const auto rokey = kwiver::vital::config_block_key_t( "myblock:mykey" ); if ( ! config->is_read_only( rokey ) ) { TEST_ERROR( "The configuration value was not marked as read only" ); } } // ------------------------------------------------------------------ IMPLEMENT_TEST( config_provider_read_only_override ) { sprokit::pipe_blocks const blocks = load_pipe_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( kwiver::vital::set_on_read_only_value_exception, sprokit::extract_configuration( blocks ), "setting a read-only provided value" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( pipeline_multiplier ) { kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::pipeline_builder builder; builder.load_pipeline( pipe_file ); sprokit::pipeline_t const pipeline = builder.pipeline(); if ( ! pipeline ) { TEST_ERROR( "A pipeline was not created" ); return; } pipeline->process_by_name( "gen_numbers1" ); pipeline->process_by_name( "gen_numbers2" ); pipeline->process_by_name( "multiply" ); pipeline->process_by_name( "print" ); /// \todo Verify the connections are done properly. } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_multiplier ) { kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::pipeline_builder builder; builder.load_cluster( pipe_file ); sprokit::cluster_info_t const info = builder.cluster_info(); const auto ctor = info->ctor; const auto config = kwiver::vital::config_block::empty_config(); std::stringstream str; str << int(30); config->set_value( "factor", str.str() ); sprokit::process_t const proc = ctor( config ); sprokit::process_cluster_t const cluster = std::dynamic_pointer_cast< sprokit::process_cluster > ( proc ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } /// \todo Verify the configuration. /// \todo Verify the input mapping. /// \todo Verify the output mapping. /// \todo Verify the connections are done properly. } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_missing_cluster ) { (void)pipe_file; sprokit::cluster_blocks blocks; sprokit::process_pipe_block const pipe_block = sprokit::process_pipe_block(); sprokit::cluster_block const block = pipe_block; blocks.push_back( block ); EXPECT_EXCEPTION( sprokit::missing_cluster_block_exception, sprokit::bake_cluster_blocks( blocks ), "baking a set of cluster blocks without a cluster" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_missing_processes ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( sprokit::cluster_without_processes_exception, sprokit::bake_cluster_blocks( blocks ), "baking a cluster without processes" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_missing_ports ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); EXPECT_EXCEPTION( sprokit::cluster_without_ports_exception, sprokit::bake_cluster_blocks( blocks ), "baking a cluster without ports" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_multiple_cluster ) { (void)pipe_file; sprokit::cluster_blocks blocks; sprokit::cluster_pipe_block const cluster_pipe_block = sprokit::cluster_pipe_block(); sprokit::cluster_block const cluster_block = cluster_pipe_block; blocks.push_back( cluster_block ); blocks.push_back( cluster_block ); EXPECT_EXCEPTION( sprokit::multiple_cluster_blocks_exception, sprokit::bake_cluster_blocks( blocks ), "baking a set of cluster blocks without multiple clusters" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_duplicate_input ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); EXPECT_EXCEPTION( sprokit::duplicate_cluster_input_port_exception, sprokit::bake_cluster_blocks( blocks ), "baking a cluster with duplicate input ports" ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_duplicate_output ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); EXPECT_EXCEPTION( sprokit::duplicate_cluster_output_port_exception, sprokit::bake_cluster_blocks( blocks ), "baking a cluster with duplicate output ports" ); } static void test_cluster( sprokit::process_t const& cluster, std::string const& path ); // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_configuration_default ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::cluster_info_t const info = sprokit::bake_cluster_blocks( blocks ); const auto ctor = info->ctor; const auto config = kwiver::vital::config_block::empty_config(); sprokit::process_t const cluster = ctor( config ); std::string const output_path = "test-pipe_bakery-configuration_default.txt"; test_cluster( cluster, output_path ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_configuration_provide ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::cluster_info_t const info = sprokit::bake_cluster_blocks( blocks ); const auto ctor = info->ctor; const auto config = kwiver::vital::config_block::empty_config(); sprokit::process_t const cluster = ctor( config ); std::string const output_path = "test-pipe_bakery-configuration_provide.txt"; test_cluster( cluster, output_path ); } static sprokit::process_cluster_t setup_map_config_cluster( sprokit::process::name_t const& name, kwiver::vital::path_t const& pipe_file ); // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config ) { /// \todo This test is poorly designed in that it tests for mapping by /// leveraging the fact that only mapped configuration get pushed through when /// reconfiguring a cluster. sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config_tunable ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); pipeline->reconfigure( new_conf ); } #if 0 // disable incomplete tests //+ Need to mangle the macro name so the CMake tooling does not //+ register these tests even though they are not active //------------------------------------------------------------------ DONT_IMPLEMENT_TEST( cluster_map_config_redirect ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ DONT_IMPLEMENT_TEST( cluster_map_config_modified ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } #endif // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config_not_read_only ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "unexpected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config_only_provided ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "unexpected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ TEST_PROPERTY( ENVIRONMENT, TEST_ENV = expected ) IMPLEMENT_TEST( cluster_map_config_only_conf_provided ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "unexpected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config_to_non_process ) { /// \todo This test is poorly designed because there's no check that / the /// mapping wasn't actually created. sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + key, tuned_value ); sprokit::process::name_t const proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_map_config_not_from_cluster ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); sprokit::process_cluster_t const cluster = setup_map_config_cluster( cluster_name, pipe_file ); if ( ! cluster ) { TEST_ERROR( "A cluster was not created" ); return; } sprokit::pipeline_t const pipeline = std::make_shared< sprokit::pipeline > ( kwiver::vital::config_block::empty_config() ); pipeline->add_process( cluster ); pipeline->setup_pipeline(); const auto new_conf = kwiver::vital::config_block::empty_config(); const auto proc_name = sprokit::process::name_t( "expect" ); const auto new_key = kwiver::vital::config_block_key_t( "new_key" ); const auto tuned_value = kwiver::vital::config_block_key_t( "expected" ); // Fill a block so that the expect process gets reconfigured to do its check; // if the block for it is empty, the check won't happen. new_conf->set_value( cluster_name + kwiver::vital::config_block::block_sep + proc_name + kwiver::vital::config_block::block_sep + new_key, tuned_value ); pipeline->reconfigure( new_conf ); } // ------------------------------------------------------------------ IMPLEMENT_TEST( cluster_override_mapped ) { sprokit::process::name_t const cluster_name = sprokit::process::name_t( "cluster" ); const auto conf = kwiver::vital::config_block::empty_config(); const auto proc_name = sprokit::process::name_t( "expect" ); const auto key = kwiver::vital::config_block_key_t( "tunable" ); const auto full_key = proc_name + kwiver::vital::config_block::block_sep + key; const auto value = kwiver::vital::config_block_value_t( "unexpected" ); // The problem here is that the expect:tunable parameter is meant to be mapped // with the map_config call within the cluster. Due to the implementation, // the lines which cause the linking are removed, so if we try to sneak in an // invalid parameter, we should get an error about overriding a read-only // variable. conf->set_value( full_key, value ); sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::cluster_info_t const info = sprokit::bake_cluster_blocks( blocks ); const auto ctor = info->ctor; EXPECT_EXCEPTION( kwiver::vital::set_on_read_only_value_exception, ctor( conf ), "manually setting a parameter which is mapped in a cluster" ); } static sprokit::process_t create_process( sprokit::process::type_t const& type, sprokit::process::name_t const& name, kwiver::vital::config_block_sptr config = kwiver::vital::config_block::empty_config() ); static sprokit::pipeline_t create_pipeline(); // ------------------------------------------------------------------ void test_cluster( sprokit::process_t const& cluster, std::string const& path ) { sprokit::process::type_t const proc_typeu = sprokit::process::type_t( "numbers" ); sprokit::process::type_t const proc_typet = sprokit::process::type_t( "print_number" ); sprokit::process::name_t const proc_nameu = sprokit::process::name_t( "upstream" ); sprokit::process::name_t const proc_named = cluster->name(); sprokit::process::name_t const proc_namet = sprokit::process::name_t( "terminal" ); int32_t const start_value = 10; int32_t const end_value = 20; { const auto configu = kwiver::vital::config_block::empty_config(); const auto start_key = kwiver::vital::config_block_key_t( "start" ); const auto end_key = kwiver::vital::config_block_key_t( "end" ); std::stringstream str; str << start_value; const auto start_num = str.str(); str.clear(); str << end_value; const auto end_num = str.str(); configu->set_value( start_key, start_num ); configu->set_value( end_key, end_num ); const auto configt = kwiver::vital::config_block::empty_config(); const auto output_key = kwiver::vital::config_block_key_t( "output" ); const auto output_value = kwiver::vital::config_block_value_t( path ); configt->set_value( output_key, output_value ); sprokit::process_t const processu = create_process( proc_typeu, proc_nameu, configu ); sprokit::process_t const processt = create_process( proc_typet, proc_namet, configt ); sprokit::pipeline_t const pipeline = create_pipeline(); pipeline->add_process( processu ); pipeline->add_process( cluster ); pipeline->add_process( processt ); const auto port_nameu = sprokit::process::port_t( "number" ); const auto port_namedi = sprokit::process::port_t( "factor" ); const auto port_namedo = sprokit::process::port_t( "product" ); const auto port_namet = sprokit::process::port_t( "number" ); pipeline->connect( proc_nameu, port_nameu, proc_named, port_namedi ); pipeline->connect( proc_named, port_namedo, proc_namet, port_namet ); pipeline->setup_pipeline(); sprokit::scheduler_t const scheduler = sprokit::create_scheduler( sprokit::scheduler_factory::default_type, pipeline ); scheduler->start(); scheduler->wait(); } std::ifstream fin( path.c_str() ); if ( ! fin.good() ) { TEST_ERROR( "Could not open the output file" ); } std::string line; // From the input cluster. static const int32_t factor = 20; for ( int32_t i = start_value; i < end_value; ++i ) { if ( ! std::getline( fin, line ) ) { TEST_ERROR( "Failed to read a line from the file" ); } std::stringstream str; str << ( i * factor ); if ( kwiver::vital::config_block_value_t( line ) != str.str() ) { TEST_ERROR( "Did not get expected value: Expected: " << (i * factor) << " Received: " << line ); } } if ( std::getline( fin, line ) ) { TEST_ERROR( "More results than expected in the file" ); } if ( ! fin.eof() ) { TEST_ERROR( "Not at end of file" ); } } // test_cluster sprokit::process_t create_process( sprokit::process::type_t const& type, sprokit::process::name_t const& name, kwiver::vital::config_block_sptr config ) { static bool const modules_loaded = ( kwiver::vital::plugin_manager::instance().load_all_plugins(), true ); (void)modules_loaded; return sprokit::create_process( type, name, config ); } sprokit::pipeline_t create_pipeline() { return std::make_shared< sprokit::pipeline > (); } sprokit::process_cluster_t setup_map_config_cluster( sprokit::process::name_t const& name, kwiver::vital::path_t const& pipe_file ) { sprokit::cluster_blocks const blocks = load_cluster_blocks_from_file( pipe_file ); kwiver::vital::plugin_manager::instance().load_all_plugins(); sprokit::cluster_info_t const info = sprokit::bake_cluster_blocks( blocks ); const auto ctor = info->ctor; const auto config = kwiver::vital::config_block::empty_config(); config->set_value( sprokit::process::config_name, name ); sprokit::process_t const proc = ctor( config ); sprokit::process_cluster_t const cluster = std::dynamic_pointer_cast< sprokit::process_cluster > ( proc ); return cluster; }
44,101
14,276
/**************************************************************************** ** ** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Script Generator project on Qt Labs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "preprocessor.h" #include <string> // register callback for include hooks static void includeFileHook(const std::string &, const std::string &, FILE *); #define PP_HOOK_ON_FILE_INCLUDED(A, B, C) includeFileHook(A, B, C) #include "pp.h" using namespace rpp; #include <QtCore/QtCore> class PreprocessorPrivate { public: QByteArray result; pp_environment env; QStringList includePaths; void initPP(pp &proc) { foreach(QString path, includePaths) proc.push_include_path(path.toStdString()); } }; QHash<QString, QStringList> includedFiles; void includeFileHook(const std::string &fileName, const std::string &filePath, FILE *) { includedFiles[QString::fromStdString(fileName)].append(QString::fromStdString(filePath)); } Preprocessor::Preprocessor() { d = new PreprocessorPrivate; includedFiles.clear(); } Preprocessor::~Preprocessor() { delete d; } void Preprocessor::processFile(const QString &fileName) { pp proc(d->env); d->initPP(proc); d->result.reserve(d->result.size() + 20 * 1024); d->result += "# 1 \"" + fileName.toLatin1() + "\"\n"; // ### REMOVE ME proc.file(fileName.toLocal8Bit().constData(), std::back_inserter(d->result)); } void Preprocessor::processString(const QByteArray &str) { pp proc(d->env); d->initPP(proc); proc(str.begin(), str.end(), std::back_inserter(d->result)); } QByteArray Preprocessor::result() const { return d->result; } void Preprocessor::addIncludePaths(const QStringList &includePaths) { d->includePaths += includePaths; } QStringList Preprocessor::macroNames() const { QStringList macros; pp_environment::const_iterator it = d->env.first_macro(); while (it != d->env.last_macro()) { const pp_macro *m = *it; macros += QString::fromLatin1(m->name->begin(), m->name->size()); ++it; } return macros; } QList<Preprocessor::MacroItem> Preprocessor::macros() const { QList<MacroItem> items; pp_environment::const_iterator it = d->env.first_macro(); while (it != d->env.last_macro()) { const pp_macro *m = *it; MacroItem item; item.name = QString::fromLatin1(m->name->begin(), m->name->size()); item.definition = QString::fromLatin1(m->definition->begin(), m->definition->size()); for (size_t i = 0; i < m->formals.size(); ++i) { item.parameters += QString::fromLatin1(m->formals[i]->begin(), m->formals[i]->size()); } item.isFunctionLike = m->function_like; #ifdef PP_WITH_MACRO_POSITION item.fileName = QString::fromLatin1(m->file->begin(), m->file->size()); #endif items += item; ++it; } return items; } /* int main() { Preprocessor pp; QStringList paths; paths << "/usr/include"; pp.addIncludePaths(paths); pp.processFile("pp-configuration"); pp.processFile("/usr/include/stdio.h"); qDebug() << pp.result(); return 0; } */
4,558
1,476
#include <torch/csrc/lazy/python/init.h> #include <torch/csrc/lazy/core/debug_util.h> #include <torch/csrc/lazy/python/python_util.h> namespace torch { namespace lazy { void initLazyBindings(PyObject* /* module */){ #ifndef USE_DEPLOY // When libtorch_python is loaded, we register the python frame getter // otherwise, debug util simply omits python frames // TODO(whc) can we make this work inside torch deploy interpreter? // it doesn't work as-is, possibly becuase GetPythonFrames resolves to external // cpython rather than embedded cpython GetPythonFramesFunction() = GetPythonFrames; #endif } } // namespace lazy } // namespace torch
659
218
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim:set ts=2 sw=2 sts=2 et cindent: */ /* 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 "nsError.h" #include "nsDOMNotifyAudioAvailableEvent.h" #include "nsDOMClassInfoID.h" // DOMCI_DATA, NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO #include "nsContentUtils.h" // NS_DROP_JS_OBJECTS #include "jsfriendapi.h" nsDOMNotifyAudioAvailableEvent::nsDOMNotifyAudioAvailableEvent(nsPresContext* aPresContext, nsEvent* aEvent, uint32_t aEventType, float* aFrameBuffer, uint32_t aFrameBufferLength, float aTime) : nsDOMEvent(aPresContext, aEvent), mFrameBuffer(aFrameBuffer), mFrameBufferLength(aFrameBufferLength), mTime(aTime), mCachedArray(nullptr), mAllowAudioData(false) { MOZ_COUNT_CTOR(nsDOMNotifyAudioAvailableEvent); if (mEvent) { mEvent->message = aEventType; } } DOMCI_DATA(NotifyAudioAvailableEvent, nsDOMNotifyAudioAvailableEvent) NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMNotifyAudioAvailableEvent) NS_IMPL_ADDREF_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent) NS_IMPL_RELEASE_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent) NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent) if (tmp->mCachedArray) { tmp->mCachedArray = nullptr; NS_DROP_JS_OBJECTS(tmp, nsDOMNotifyAudioAvailableEvent); } NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsDOMNotifyAudioAvailableEvent) NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mCachedArray) NS_IMPL_CYCLE_COLLECTION_TRACE_END NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMNotifyAudioAvailableEvent) NS_INTERFACE_MAP_ENTRY(nsIDOMNotifyAudioAvailableEvent) NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(NotifyAudioAvailableEvent) NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent) nsDOMNotifyAudioAvailableEvent::~nsDOMNotifyAudioAvailableEvent() { MOZ_COUNT_DTOR(nsDOMNotifyAudioAvailableEvent); if (mCachedArray) { mCachedArray = nullptr; NS_DROP_JS_OBJECTS(this, nsDOMNotifyAudioAvailableEvent); } } NS_IMETHODIMP nsDOMNotifyAudioAvailableEvent::GetFrameBuffer(JSContext* aCx, jsval* aResult) { if (!mAllowAudioData) { // Media is not same-origin, don't allow the data out. return NS_ERROR_DOM_SECURITY_ERR; } if (mCachedArray) { *aResult = OBJECT_TO_JSVAL(mCachedArray); return NS_OK; } // Cache this array so we don't recreate on next call. NS_HOLD_JS_OBJECTS(this, nsDOMNotifyAudioAvailableEvent); mCachedArray = JS_NewFloat32Array(aCx, mFrameBufferLength); if (!mCachedArray) { NS_DROP_JS_OBJECTS(this, nsDOMNotifyAudioAvailableEvent); return NS_ERROR_FAILURE; } memcpy(JS_GetFloat32ArrayData(mCachedArray, aCx), mFrameBuffer.get(), mFrameBufferLength * sizeof(float)); *aResult = OBJECT_TO_JSVAL(mCachedArray); return NS_OK; } NS_IMETHODIMP nsDOMNotifyAudioAvailableEvent::GetTime(float *aRetVal) { *aRetVal = mTime; return NS_OK; } NS_IMETHODIMP nsDOMNotifyAudioAvailableEvent::InitAudioAvailableEvent(const nsAString& aType, bool aCanBubble, bool aCancelable, float* aFrameBuffer, uint32_t aFrameBufferLength, float aTime, bool aAllowAudioData) { // Auto manage the memory which stores the frame buffer. This ensures // that if we exit due to some error, the memory will be freed. Otherwise, // the framebuffer's memory will be freed when this event is destroyed. nsAutoArrayPtr<float> frameBuffer(aFrameBuffer); nsresult rv = nsDOMEvent::InitEvent(aType, aCanBubble, aCancelable); NS_ENSURE_SUCCESS(rv, rv); mFrameBuffer = frameBuffer.forget(); mFrameBufferLength = aFrameBufferLength; mTime = aTime; mAllowAudioData = aAllowAudioData; return NS_OK; } nsresult NS_NewDOMAudioAvailableEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, nsEvent *aEvent, uint32_t aEventType, float* aFrameBuffer, uint32_t aFrameBufferLength, float aTime) { nsDOMNotifyAudioAvailableEvent* it = new nsDOMNotifyAudioAvailableEvent(aPresContext, aEvent, aEventType, aFrameBuffer, aFrameBufferLength, aTime); return CallQueryInterface(it, aInstancePtrResult); }
5,384
1,775
// @formatter:off // // Balau core C++ library // // Copyright (C) 2008 Bora Software (contact@borasoftware.com) // // 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 Assert.hpp /// /// Assertion utilities for development purposes. /// #ifndef COM_BORA_SOFTWARE__BALAU_DEV__ASSERT #define COM_BORA_SOFTWARE__BALAU_DEV__ASSERT #include <boost/core/ignore_unused.hpp> #include <string> #ifdef BALAU_ENABLE_STACKTRACES #include <boost/stacktrace.hpp> #endif #include <iostream> #include <sstream> namespace Balau { /// /// An assertion class for development purposes. /// class Assert { /// /// Abort after logging the message. /// public: static void fail(const char * fatalMessage) { performAssertion(false, fatalMessage, "Fail called"); } /////////////////////////////////////////////////////////////////////////// /// /// If the bug test assertion fails, abort after logging the message supplied by the function. /// public: template <typename StringFunctionT> static void assertion(bool test, StringFunctionT function) { performAssertion(test, function, "Bug found"); } /// /// If the bug test assertion fails, abort after logging the message. /// public: static void assertion(bool test, const char * fatalMessage) { performAssertion(test, fatalMessage, "Bug found"); } /// /// Abort if the bug test fails. /// public: static void assertion(bool test) { performAssertion(test, "", "Bug found"); } /// /// If the bug test assertion predicate function fails, abort after logging the message supplied by the function. /// public: template <typename TestFunctionT, typename StringFunctionT> static void assertion(TestFunctionT test, StringFunctionT function) { performAssertion(test, function, "Bug found"); } /// /// If the bug test assertion predicate function fails, abort after logging the message. /// public: template <typename TestFunctionT> static void assertion(TestFunctionT test, const char * fatalMessage) { performAssertion(test, fatalMessage, "Bug found"); } /// /// Abort if the bug test assertion predicate function fails. /// public: template <typename TestFunctionT> static void assertion(TestFunctionT test) { performAssertion(test, "", "Bug found"); } /////////////////////////////////////////////////////////////////////////// private: template <typename FunctionT> static void performAssertion(bool test, FunctionT function, const char * testType) { boost::ignore_unused(test); boost::ignore_unused(function); boost::ignore_unused(testType); #ifdef BALAU_DEBUG if (!test) { const std::string message = function(); abortProcess(message.c_str(), testType); } #endif } private: template <typename TestT, typename FunctionT> static void performAssertion(TestT test, FunctionT function, const char * testType) { boost::ignore_unused(test); boost::ignore_unused(function); boost::ignore_unused(testType); #ifdef BALAU_DEBUG if (!test()) { const std::string message = function(); abortProcess(message.c_str(), testType); } #endif } private: static void performAssertion(bool test, const char * fatalMessage, const char * testType) { boost::ignore_unused(test); boost::ignore_unused(fatalMessage); boost::ignore_unused(testType); #ifdef BALAU_DEBUG if (!test) { abortProcess(fatalMessage, testType); } #endif } private: template <typename TestT> static void performAssertion(TestT test, const char * fatalMessage, const char * testType) { boost::ignore_unused(test); boost::ignore_unused(fatalMessage); boost::ignore_unused(testType); #ifdef BALAU_DEBUG if (!test()) { abortProcess(fatalMessage, testType); } #endif } private: static void abortProcess(const char * fatalMessage, const char * testType) { std::ostringstream str; if (fatalMessage != nullptr) { str << testType << ": " << fatalMessage << "\n"; } else { str << testType << "\n"; } #ifdef BALAU_ENABLE_STACKTRACES str << "Stack trace: " << boost::stacktrace::stacktrace() << "\n"; #endif str << "Program will abort now\n"; std::cerr << str.str(); abort(); } }; } // namespace Balau #endif // COM_BORA_SOFTWARE__BALAU_DEV__ASSERT
4,738
1,554
/* * DigiBoosterEcho.cpp * ------------------- * Purpose: Implementation of the DigiBooster Pro Echo DSP * Notes : (currently none) * Authors: OpenMPT Devs, based on original code by Grzegorz Kraszewski (BSD 2-clause) * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #ifndef NO_PLUGINS #include "../Sndfile.h" #include "DigiBoosterEcho.h" OPENMPT_NAMESPACE_BEGIN IMixPlugin* DigiBoosterEcho::Create(VSTPluginLib &factory, CSoundFile &sndFile, SNDMIXPLUGIN *mixStruct) //------------------------------------------------------------------------------------------------------ { return new (std::nothrow) DigiBoosterEcho(factory, sndFile, mixStruct); } DigiBoosterEcho::DigiBoosterEcho(VSTPluginLib &factory, CSoundFile &sndFile, SNDMIXPLUGIN *mixStruct) : IMixPlugin(factory, sndFile, mixStruct) , m_bufferSize(0) , m_writePos(0) , m_sampleRate(sndFile.GetSampleRate()) //--------------------------------------------------------------------------------------------------- { m_mixBuffer.Initialize(2, 2); InsertIntoFactoryList(); } void DigiBoosterEcho::Process(float *pOutL, float *pOutR, uint32 numFrames) //------------------------------------------------------------------------- { if(!m_bufferSize) return; const float *srcL = m_mixBuffer.GetInputBuffer(0), *srcR = m_mixBuffer.GetInputBuffer(1); float *outL = m_mixBuffer.GetOutputBuffer(0), *outR = m_mixBuffer.GetOutputBuffer(1); for(uint32 i = numFrames; i != 0; i--) { int readPos = m_writePos - m_delayTime; if(readPos < 0) readPos += m_bufferSize; float l = *srcL++, r = *srcR++; float lDelay = m_delayLine[readPos * 2], rDelay = m_delayLine[readPos * 2 + 1]; // Calculate the delay float al = l * m_NCrossNBack; al += r * m_PCrossNBack; al += lDelay * m_NCrossPBack; al += rDelay * m_PCrossPBack; float ar = r * m_NCrossNBack; ar += l * m_PCrossNBack; ar += rDelay * m_NCrossPBack; ar += lDelay * m_PCrossPBack; // Prevent denormals if(mpt::abs(al) < 1e-24f) al = 0.0f; if(mpt::abs(ar) < 1e-24f) ar = 0.0f; m_delayLine[m_writePos * 2] = al; m_delayLine[m_writePos * 2 + 1] = ar; m_writePos++; if(m_writePos == m_bufferSize) m_writePos = 0; // Output samples now *outL++ = (l * m_NMix + lDelay * m_PMix); *outR++ = (r * m_NMix + rDelay * m_PMix); } ProcessMixOps(pOutL, pOutR, m_mixBuffer.GetOutputBuffer(0), m_mixBuffer.GetOutputBuffer(1), numFrames); } void DigiBoosterEcho::SaveAllParameters() //--------------------------------------- { m_pMixStruct->defaultProgram = -1; if(m_pMixStruct->nPluginDataSize != sizeof(chunk) || m_pMixStruct->pPluginData == nullptr) { delete[] m_pMixStruct->pPluginData; m_pMixStruct->nPluginDataSize = sizeof(chunk); m_pMixStruct->pPluginData = new (std::nothrow) char[sizeof(chunk)]; } if(m_pMixStruct->pPluginData != nullptr) { memcpy(m_pMixStruct->pPluginData, &chunk, sizeof(chunk)); } } void DigiBoosterEcho::RestoreAllParameters(int32 program) //------------------------------------------------------- { if(m_pMixStruct->nPluginDataSize == sizeof(chunk) && !memcmp(m_pMixStruct->pPluginData, "Echo", 4)) { memcpy(&chunk, m_pMixStruct->pPluginData, sizeof(chunk)); } else { IMixPlugin::RestoreAllParameters(program); } RecalculateEchoParams(); } PlugParamValue DigiBoosterEcho::GetParameter(PlugParamIndex index) //---------------------------------------------------------------- { if(index < kEchoNumParameters) { return chunk.param[index] / 255.0f; } return 0; } void DigiBoosterEcho::SetParameter(PlugParamIndex index, PlugParamValue value) //---------------------------------------------------------------------------- { if(index < kEchoNumParameters) { chunk.param[index] = Util::Round<uint8>(value * 255.0f); RecalculateEchoParams(); } } void DigiBoosterEcho::Resume() //---------------------------- { m_isResumed = true; m_sampleRate = m_SndFile.GetSampleRate(); m_bufferSize = (m_sampleRate >> 1) + (m_sampleRate >> 6); RecalculateEchoParams(); try { m_delayLine.assign(m_bufferSize * 2, 0); } catch(MPTMemoryException) { m_bufferSize = 0; } m_writePos = 0; } #ifdef MODPLUG_TRACKER CString DigiBoosterEcho::GetParamName(PlugParamIndex param) //--------------------------------------------------------- { switch(param) { case kEchoDelay: return _T("Delay"); case kEchoFeedback: return _T("Feedback"); case kEchoMix: return _T("Wet / Dry Ratio"); case kEchoCross: return _T("Cross Echo"); } return CString(); } CString DigiBoosterEcho::GetParamLabel(PlugParamIndex param) //---------------------------------------------------------- { if(param == kEchoDelay) return _T("ms"); return CString(); } CString DigiBoosterEcho::GetParamDisplay(PlugParamIndex param) //------------------------------------------------------------ { CString s; if(param == kEchoMix) { int wet = (chunk.param[kEchoMix] * 100) / 255; s.Format(_T("%d%% / %d%%"), wet, 100 - wet); } else if(param < kEchoNumParameters) { int val = chunk.param[param]; if(param == kEchoDelay) val *= 2; s.Format(_T("%d"), val); } return s; } #endif // MODPLUG_TRACKER size_t DigiBoosterEcho::GetChunk(char *(&data), bool) //--------------------------------------------------- { data = reinterpret_cast<char *>(&chunk); return sizeof(chunk); } void DigiBoosterEcho::SetChunk(size_t size, char *data, bool) //----------------------------------------------------------- { if(size == sizeof(chunk) && !memcmp(data, "Echo", 4)) { memcpy(&chunk, data, size); RecalculateEchoParams(); } } void DigiBoosterEcho::RecalculateEchoParams() //------------------------------------------- { m_delayTime = (chunk.param[kEchoDelay] * m_sampleRate + 250) / 500; m_PMix = (chunk.param[kEchoMix]) * (1.0f / 256.0f); m_NMix = (256 - chunk.param[kEchoMix]) * (1.0f / 256.0f); m_PCrossPBack = (chunk.param[kEchoCross] * chunk.param[kEchoFeedback]) * (1.0f / 65536.0f); m_PCrossNBack = (chunk.param[kEchoCross] * (256 - chunk.param[kEchoFeedback])) * (1.0f / 65536.0f); m_NCrossPBack = ((chunk.param[kEchoCross] - 256) * chunk.param[kEchoFeedback]) * (1.0f / 65536.0f); m_NCrossNBack = ((chunk.param[kEchoCross] - 256) * (chunk.param[kEchoFeedback] - 256)) * (1.0f / 65536.0f); } OPENMPT_NAMESPACE_END #endif // NO_PLUGINS
6,347
2,553
#include <common/verify.hpp> #include <experimental/filesystem> #include <fstream> #include <unistd.h> #include <common/dir_utils.hpp> #include <common/string_utils.hpp> std::string getFirst(const std::experimental::filesystem::path &cfile) { std::string res; std::ifstream is; is.open(cfile); std::getline(is, res); is.close(); return std::move(res); } void removeFirst(const std::experimental::filesystem::path &cfile) { std::vector<std::string> contents; std::string next; std::ifstream is; is.open(cfile); while(std::getline(is, next)) { if(!next.empty()) { contents.emplace_back(next); } } is.close(); std::ofstream os; os.open(cfile); contents.erase(contents.begin()); for(std::string &line : contents) { os << line << "\n"; } os.close(); } void append(const std::experimental::filesystem::path &cfile, const std::string &next) { std::ofstream os; os.open(cfile, std::ios_base::app); os << next << "\n"; os.close(); } int main(int argc, char **argv) { VERIFY(argc == 3); std::experimental::filesystem::path cfile(argv[1]); std::experimental::filesystem::path dir(argv[2]); ensure_dir_existance(dir); ensure_dir_existance(dir / "logs"); std::experimental::filesystem::path log_path = dir/"log.txt"; size_t max = 0; for(const std::experimental::filesystem::path &p :std::experimental::filesystem::directory_iterator(dir / "logs")){ max = std::max<size_t>(max, std::stoull(p.filename())); } bool slept = false; #pragma clang diagnostic push #pragma ide diagnostic ignored "EndlessLoop" while(true) { std::string command = getFirst(cfile); if(command.empty()) { if(!slept) { std::cout << "No command. Sleeping." << std::endl; slept = true; } sleep(60); } else { slept = false; std::cout << "Running new command: " << command << std::endl; std::experimental::filesystem::path log(dir/"logs"/itos(max + 1)); std::cout << "Printing output to file " << log << std::endl; std::ofstream os; os.open(log_path, std::ios_base::app); os << (max + 1) << " started\n" << command << "\n"; os.close(); int res = system((command + " > " + log.string() + " 2>&1").c_str()); std::cout << "Finished running command: " << command << std::endl; std::cout << "Return code: " << res << "\n\n" << std::endl; std::ofstream os1; os1.open(log_path, std::ios_base::app); os1 << (max + 1) << " finished " << res << "\n\n"; os1.close(); max++; removeFirst(cfile); append(dir / "finished.txt", command); } } #pragma clang diagnostic pop }
2,913
951
// Iostreams base classes -*- C++ -*- // Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 // Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 2, 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline functions from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. // // ISO C++ 14882: 27.4 Iostreams base classes // #include <ios> #include <limits> #include <bits/atomicity.h> namespace std { // Definitions for static const members of ios_base. const ios_base::fmtflags ios_base::boolalpha; const ios_base::fmtflags ios_base::dec; const ios_base::fmtflags ios_base::fixed; const ios_base::fmtflags ios_base::hex; const ios_base::fmtflags ios_base::internal; const ios_base::fmtflags ios_base::left; const ios_base::fmtflags ios_base::oct; const ios_base::fmtflags ios_base::right; const ios_base::fmtflags ios_base::scientific; const ios_base::fmtflags ios_base::showbase; const ios_base::fmtflags ios_base::showpoint; const ios_base::fmtflags ios_base::showpos; const ios_base::fmtflags ios_base::skipws; const ios_base::fmtflags ios_base::unitbuf; const ios_base::fmtflags ios_base::uppercase; const ios_base::fmtflags ios_base::adjustfield; const ios_base::fmtflags ios_base::basefield; const ios_base::fmtflags ios_base::floatfield; const ios_base::iostate ios_base::badbit; const ios_base::iostate ios_base::eofbit; const ios_base::iostate ios_base::failbit; const ios_base::iostate ios_base::goodbit; const ios_base::openmode ios_base::app; const ios_base::openmode ios_base::ate; const ios_base::openmode ios_base::binary; const ios_base::openmode ios_base::in; const ios_base::openmode ios_base::out; const ios_base::openmode ios_base::trunc; const ios_base::seekdir ios_base::beg; const ios_base::seekdir ios_base::cur; const ios_base::seekdir ios_base::end; _Atomic_word ios_base::Init::_S_refcount; bool ios_base::Init::_S_synced_with_stdio = true; ios_base::ios_base() : _M_precision(), _M_width(), _M_flags(), _M_exception(), _M_streambuf_state(), _M_callbacks(0), _M_word_zero(), _M_word_size(_S_local_word_size), _M_word(_M_local_word), _M_ios_locale() { // Do nothing: basic_ios::init() does it. // NB: _M_callbacks and _M_word must be zero for non-initialized // ios_base to go through ~ios_base gracefully. } // 27.4.2.7 ios_base constructors/destructors ios_base::~ios_base() { _M_call_callbacks(erase_event); _M_dispose_callbacks(); if (_M_word != _M_local_word) { delete [] _M_word; _M_word = 0; } } // 27.4.2.5 ios_base storage functions int ios_base::xalloc() throw() { // Implementation note: Initialize top to zero to ensure that // initialization occurs before main() is started. static _Atomic_word _S_top = 0; return __gnu_cxx::__exchange_and_add(&_S_top, 1) + 4; } void ios_base::register_callback(event_callback __fn, int __index) { _M_callbacks = new _Callback_list(__fn, __index, _M_callbacks); } // 27.4.2.5 iword/pword storage ios_base::_Words& ios_base::_M_grow_words(int __ix, bool __iword) { // Precondition: _M_word_size <= __ix int __newsize = _S_local_word_size; _Words* __words = _M_local_word; if (__ix > _S_local_word_size - 1) { if (__ix < numeric_limits<int>::max()) { __newsize = __ix + 1; try { __words = new _Words[__newsize]; } catch (...) { _M_streambuf_state |= badbit; if (_M_streambuf_state & _M_exception) __throw_ios_failure(__N("ios_base::_M_grow_words " "allocation failed")); if (__iword) _M_word_zero._M_iword = 0; else _M_word_zero._M_pword = 0; return _M_word_zero; } for (int __i = 0; __i < _M_word_size; __i++) __words[__i] = _M_word[__i]; if (_M_word && _M_word != _M_local_word) { delete [] _M_word; _M_word = 0; } } else { _M_streambuf_state |= badbit; if (_M_streambuf_state & _M_exception) __throw_ios_failure(__N("ios_base::_M_grow_words is not valid")); if (__iword) _M_word_zero._M_iword = 0; else _M_word_zero._M_pword = 0; return _M_word_zero; } } _M_word = __words; _M_word_size = __newsize; return _M_word[__ix]; } void ios_base::_M_call_callbacks(event __e) throw() { _Callback_list* __p = _M_callbacks; while (__p) { try { (*__p->_M_fn) (__e, *this, __p->_M_index); } catch (...) { } __p = __p->_M_next; } } void ios_base::_M_dispose_callbacks(void) { _Callback_list* __p = _M_callbacks; while (__p && __p->_M_remove_reference() == 0) { _Callback_list* __next = __p->_M_next; delete __p; __p = __next; } _M_callbacks = 0; } } // namespace std
6,017
2,305
// Copyright (c) 2018 Graphcore Ltd. All rights reserved. #ifndef GUARD_NEURALNET_REDUCESUMSQUAREX_HPP #define GUARD_NEURALNET_REDUCESUMSQUAREX_HPP #include <popart/names.hpp> #include <popart/popx/popopx.hpp> namespace popart { namespace popx { class ReduceSumSquareOpx : public PopOpx { public: ReduceSumSquareOpx(Op *, Devicex *); void grow(snap::program::Sequence &) const override; }; class ReduceSumSquareGradOpx : public PopOpx { public: ReduceSumSquareGradOpx(Op *, Devicex *); void grow(snap::program::Sequence &) const override; }; } // namespace popx } // namespace popart #endif
605
237
#ifndef TOUCH_TYPING_TEXT_FILER_HPP #define TOUCH_TYPING_TEXT_FILER_HPP #include <filesystem> #include <string> namespace touch_typing { class TextFile { public: explicit TextFile(const std::filesystem::path& filename); [[nodiscard]] auto asString() const noexcept -> const std::string&; private: std::string m_text; }; } // namespace touch_typing #endif // TOUCH_TYPING_TEXT_FILER_HPP
405
156
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #pragma once #include <eve/module/core.hpp> #include <eve/module/math.hpp> #include <eve/module/bessel/regular/cyl_bessel_i0.hpp> #include <eve/module/bessel/regular/cyl_bessel_i1.hpp> #include <eve/module/bessel/detail/kernel_bessel_ik.hpp> #include <eve/module/bessel/detail/kernel_bessel_ij_small.hpp> ///////////////////////////////////////////////////////////////////////////////// // These routines are detail of the computation of modifiesd cylindrical bessel // fnctions of the first kind. . // They are not meant to be called directly, as their validities depends on // n and x ranges values which are not tested on entry. // The inspiration is from boost math ///////////////////////////////////////////////////////////////////////////////// namespace eve::detail { ///////////////////////////////////////////////////////////////////////// // bessel_i template<floating_real_value T> EVE_FORCEINLINE auto kernel_bessel_i (T n, T x) noexcept { auto br_small = [](auto n, auto x) { return bessel_i_small_z_series(n, x); }; auto br_medium = [](auto n, auto x) { auto [in, ipn, kn, kpn] = kernel_bessel_ik(n, x); return in; }; auto br_half = [](auto x) { if(eve::any(x >= maxlog(as(x)))) { auto ex = eve::exp(x/2); return ex*(ex*rsqrt(x*twopi(as(x)))); } else return rsqrt(x*pio_2(as(x)))*sinh(x); }; if constexpr(scalar_value<T>) { if (is_ngez(x)) return nan(as(x)); if (is_eqz(x)) return (n == 0) ? one(as(x)) : zero(as(x)); if (x == inf(as(x))) return inf(as(x)); if (n == T(0.5)) return br_half(x); //cyl_bessel_i order 0.5 if (n == 0) return cyl_bessel_i0(x); //cyl_bessel_i0(x); if (n == 1) return cyl_bessel_i1(x); //cyl_bessel_i1(x); if (x*4 < n) return br_small(n, x); // serie return br_medium(n, x); // general } else { auto r = nan(as(x)); auto isinfx = x == inf(as(x)); r = if_else(isinfx, inf(as(x)), allbits); x = if_else(isinfx, mone, x); auto iseqzx = is_eqz(x); auto iseqzn = is_eqz(n); if (eve::any(iseqzx)) { r = if_else(iseqzx, if_else(iseqzn, zero, one(as(x))), r); } if (eve::any(iseqzn)) { r = if_else(iseqzn, cyl_bessel_i0(x), r); } auto iseq1n = n == one(as(n)); if (eve::any(iseq1n)) { r = if_else(n == one(as(n)), cyl_bessel_i1(x), r); } auto notdone = is_gez(x) && !(iseqzn || iseq1n) ; x = if_else(notdone, x, allbits); if( eve::any(notdone) ) { notdone = next_interval(br_half, notdone, n == T(0.5), r, x); if( eve::any(notdone) ) { if( eve::any(notdone) ) { notdone = last_interval(br_medium, notdone, r, n, x); } } } return r; } } }
3,534
1,209
#ifndef TDAP_M_LIMITER_HPP #define TDAP_M_LIMITER_HPP /* * tdap/Limiter.hpp * * Added by michel on 2020-02-09 * Copyright (C) 2015-2020 Michel Fleur. * Source https://github.com/emmef/speakerman * Email speakerman@emmef.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include <tdap/Followers.hpp> namespace tdap { template <typename T> class Limiter { public: virtual void setPredictionAndThreshold(size_t prediction, T threshold, T sampleRate) = 0; virtual size_t latency() const noexcept = 0; virtual T getGain(T sample) noexcept = 0; virtual ~Limiter() = default; }; template <typename T> class CheapLimiter : public Limiter<T> { IntegrationCoefficients<T> release_; IntegrationCoefficients<T> attack_; T hold_ = 0; T integrated1_ = 0; T integrated2_ = 0; T threshold_ = 1.0; T adjustedPeakFactor_ = 1.0; size_t holdCount_ = 0; bool inRelease = false; size_t latency_ = 0; static constexpr double predictionFactor = 0.30; public: void setPredictionAndThreshold(size_t prediction, T threshold, T sampleRate) override { double release = sampleRate * 0.04; double thresholdFactor = 1.0 - exp(-1.0 / predictionFactor); latency_ = prediction; attack_.setCharacteristicSamples(predictionFactor * prediction); release_.setCharacteristicSamples(release * M_SQRT1_2); threshold_ = threshold; integrated1_ = integrated2_ = threshold_; adjustedPeakFactor_ = 1.0 / thresholdFactor; } size_t latency() const noexcept override { return latency_; } T getGain(T sample) noexcept override { T peak = std::max(sample, threshold_); if (peak >= hold_) { hold_ = peak * adjustedPeakFactor_; holdCount_ = latency_ + 1; integrated1_ += attack_.inputMultiplier() * (hold_ - integrated1_); integrated2_ = integrated1_; } else if (holdCount_) { holdCount_--; integrated1_ += attack_.inputMultiplier() * (hold_ - integrated1_); integrated2_ = integrated1_; } else { hold_ = peak; integrated1_ += release_.inputMultiplier() * (hold_ - integrated1_); integrated2_ += release_.inputMultiplier() * (integrated1_ - integrated2_); } return threshold_ / integrated2_; } }; template <typename T> class FastLookAheadLimiter : public Limiter<T> { FastSmoothHoldFollower<T> follower; public: void setPredictionAndThreshold(size_t prediction, T threshold, T sampleRate) override { T predictionSeconds = 1.0 * prediction / sampleRate; follower.setPredictionAndThreshold( predictionSeconds, threshold, sampleRate, std::clamp(predictionSeconds * 5, 0.003, 0.02), threshold); } size_t latency() const noexcept override { return follower.latency(); } T getGain(T sample) noexcept override { return follower.getGain(sample); } }; template <typename T> class ZeroPredictionHardAttackLimiter : public Limiter<T> { IntegrationCoefficients<T> release_; T integrated1_ = 0; T integrated2_ = 0; T threshold_ = 1.0; static constexpr double predictionFactor = 0.30; public: void setPredictionAndThreshold(size_t prediction, T threshold, T sampleRate) override { size_t release = Floats::clamp(prediction * 8, sampleRate * 0.010, sampleRate * 0.020); release_.setCharacteristicSamples(release * M_SQRT1_2); threshold_ = threshold; integrated1_ = integrated2_ = threshold_; std::cout << "HARD no prediction limiter" << std::endl; } size_t latency() const noexcept override { return 0; } T getGain(T sample) noexcept override { T peak = std::max(sample, threshold_); if (peak >= integrated1_) { integrated2_ = integrated1_ = peak; } else { integrated1_ += release_.inputMultiplier() * (peak - integrated1_); integrated2_ += release_.inputMultiplier() * (integrated1_ - integrated2_); } return threshold_ / integrated2_; } }; template <typename T> class TriangularLimiter : public Limiter<T> { static constexpr double ATTACK_SMOOTHFACTOR = 0.1; static constexpr double RELEASE_SMOOTHFACTOR = 0.3; static constexpr double TOTAL_TIME_FACTOR = 1.0 + ATTACK_SMOOTHFACTOR; static constexpr double ADJUST_THRESHOLD = 0.99999; TriangularFollower<T> follower_; IntegrationCoefficients<T> release_; T integrated_ = 0; T adjustedThreshold_; size_t latency_ = 0; public: TriangularLimiter() : follower_(1000) {} void setPredictionAndThreshold(size_t prediction, T threshold, T sampleRate) override { size_t attack = prediction; latency_ = prediction; size_t release = Floats::clamp(prediction * 8, sampleRate * 0.010, sampleRate * 0.020); adjustedThreshold_ = threshold * ADJUST_THRESHOLD; follower_.setTimeConstantAndSamples(attack, release, adjustedThreshold_); release_.setCharacteristicSamples(release * RELEASE_SMOOTHFACTOR); integrated_ = adjustedThreshold_; std::cout << "TriangularLimiter" << std::endl; } size_t latency() const noexcept override { return latency_; } T getGain(T input) noexcept override { T followed = follower_.follow(input); T integrationFactor; if (followed > integrated_) { integrationFactor = 1.0; // attack_.inputMultiplier(); } else { integrationFactor = release_.inputMultiplier(); } integrated_ += integrationFactor * (followed - integrated_); return adjustedThreshold_ / integrated_; } }; template <typename sample_t> class PredictiveSmoothEnvelopeLimiter { Array<sample_t> attack_envelope_; Array<sample_t> release_envelope_; Array<sample_t> peaks_; sample_t threshold_; sample_t smoothness_; sample_t current_peak_; size_t release_count_; size_t current_sample; size_t attack_samples_; size_t release_samples_; static void create_smooth_semi_exponential_envelope(sample_t *envelope, const size_t length, size_t periods) { const sample_t periodExponent = exp(-1.0 * periods); size_t i; for (i = 0; i < length; i++) { envelope[i] = limiter_envelope_value(i, length, periods, periodExponent); } } template <typename... A> static void create_smooth_semi_exponential_envelope( ArrayTraits<sample_t, A...> envelope, const size_t length, size_t periods) { create_smooth_semi_exponential_envelope(envelope + 0, length, periods); } static inline double limiter_envelope_value(const size_t i, const size_t length, const double periods, const double periodExponent) { const double angle = M_PI * (i + 1) / length; const double ePower = 0.5 * periods * (cos(angle) - 1.0); const double envelope = (exp(ePower) - periodExponent) / (1.0 - periodExponent); return envelope; } void generate_envelopes_reset(bool recalculate_attack_envelope = true, bool recalculate_release_envelope = true) { if (recalculate_attack_envelope) { PredictiveSmoothEnvelopeLimiter::create_smooth_semi_exponential_envelope( attack_envelope_ + 0, attack_samples_, smoothness_); } if (recalculate_release_envelope) { PredictiveSmoothEnvelopeLimiter::create_smooth_semi_exponential_envelope( release_envelope_ + 0, release_samples_, smoothness_); } release_count_ = 0; current_peak_ = 0; current_sample = 0; } inline const sample_t getAmpAndMoveToNextSample(const sample_t newValue) { const sample_t pk = peaks_[current_sample]; peaks_[current_sample] = newValue; current_sample = (current_sample + attack_samples_ - 1) % attack_samples_; const sample_t threshold = threshold_; return threshold / (threshold + pk); } public: PredictiveSmoothEnvelopeLimiter(sample_t threshold, sample_t smoothness, const size_t max_attack_samples, const size_t max_release_samples) : threshold_(threshold), smoothness_(smoothness), attack_envelope_(max_attack_samples), release_envelope_(max_release_samples), peaks_(max_attack_samples), release_count_(0), current_peak_(0), current_sample(0), attack_samples_(max_attack_samples), release_samples_(max_release_samples) { generate_envelopes_reset(); } bool reconfigure(size_t attack_samples, size_t release_samples, sample_t threshold, sample_t smoothness) { if (attack_samples == 0 || attack_samples > attack_envelope_.capacity()) { return false; } if (release_samples == 0 || release_samples > release_envelope_.capacity()) { return false; } sample_t new_threshold = Value<sample_t>::force_between(threshold, 0.01, 1); sample_t new_smoothness = Value<sample_t>::force_between(smoothness, 1, 4); bool recalculate_attack_envelope = attack_samples != attack_samples_ || new_smoothness != smoothness_; bool recalculate_release_envelope = release_samples != release_samples_ || new_smoothness != smoothness_; attack_samples_ = attack_samples; release_samples_ = release_samples; threshold_ = threshold; smoothness_ = smoothness; generate_envelopes_reset(recalculate_attack_envelope, recalculate_release_envelope); return true; } bool set_smoothness(sample_t smoothness) { return reconfigure(attack_samples_, release_samples_, threshold_, smoothness); } bool set_attack_samples(size_t samples) { return reconfigure(samples, release_samples_, threshold_, smoothness_); } bool set_release_samples(size_t samples) { return reconfigure(attack_samples_, samples, threshold_, smoothness_); } bool set_threshold(double threshold) { return reconfigure(attack_samples_, release_samples_, threshold, smoothness_); } const sample_t limiter_submit_peak_return_amplification(sample_t samplePeakValue) { static int cnt = 0; const size_t prediction = attack_envelope_.size(); const sample_t relativeValue = samplePeakValue - threshold_; const int withinReleasePeriod = release_count_ < release_envelope_.size(); const sample_t releaseCurveValue = withinReleasePeriod ? current_peak_ * release_envelope_[release_count_] : 0.0; if (relativeValue < releaseCurveValue) { /* * The signal is below either the threshold_ or the projected release * curve of the last highest peak. We can just "follow" the release curve. */ if (withinReleasePeriod) { release_count_++; } cnt++; return getAmpAndMoveToNextSample(releaseCurveValue); } /** * Alas! We can forget about the last peak. * We will have alter the prediction values so that the current, * new peak, will be "predicted". */ release_count_ = 0; current_peak_ = relativeValue; /** * We will try to project the default attack-predicition curve, * (which is the relativeValue (peak) with the nicely smooth * attackEnvelope) into the "future". * As soon as this projection hits (is not greater than) a previously * predicted value, we proceed to the next step. */ const size_t max_t = attack_samples_ - 1; size_t tClash; // the hitting point size_t t; for (tClash = 0, t = current_sample; tClash < prediction; tClash++) { t = t < max_t ? t + 1 : 0; const sample_t existingValue = peaks_[t]; const sample_t projectedValue = attack_envelope_[tClash] * relativeValue; if (projectedValue <= existingValue) { break; } } /** * We have a clash. We will now blend the peak with the * previously predicted curve, using the attackEnvelope * as blend-factor. If tClash is smaller than the complete * prediction-length, the attackEnvelope will be compressed * to fit exactly up to that clash point. * Due to the properties of the attackEnvelope it can be * mathematically proven that the newly produced curve is * always larger than the previous one in the clash range and * will blend smoothly with the existing curve. */ size_t i; for (i = 0, t = current_sample; i < tClash; i++) { t = t < max_t ? t + 1 : 0; // get the compressed attack_envelope_ value const sample_t blendFactor = attack_envelope_[i * (prediction - 1) / tClash]; // blend the peak value with the previously calculated peak peaks_[t] = relativeValue * blendFactor + (1.0 - blendFactor) * peaks_[t]; } return getAmpAndMoveToNextSample(relativeValue); } }; } // namespace tdap #endif // TDAP_M_LIMITER_HPP
13,619
4,286
/* * DeletionFilter.cpp * * Created on: Mar 19, 2015 * Author: Martin Wermelinger, Peter Fankhauser * Institute: ETH Zurich, Autonomous Systems Lab */ #include "grid_map_filters/DeletionFilter.hpp" #include <grid_map_core/GridMap.hpp> #include <pluginlib/class_list_macros.h> using namespace filters; namespace grid_map { template<typename T> DeletionFilter<T>::DeletionFilter() { } template<typename T> DeletionFilter<T>::~DeletionFilter() { } template<typename T> bool DeletionFilter<T>::configure() { // Load Parameters if (!FilterBase<T>::getParam(std::string("layers"), layers_)) { ROS_ERROR("DeletionFilter did not find parameter 'layers'."); return false; } return true; } template<typename T> bool DeletionFilter<T>::update(const T& mapIn, T& mapOut) { mapOut = mapIn; for (const auto& layer : layers_) { // Check if layer exists. if (!mapOut.exists(layer)) { ROS_ERROR("Check your deletion layers! Type %s does not exist.", layer.c_str()); continue; } if (!mapOut.erase(layer)) { ROS_ERROR("Could not remove type %s.", layer.c_str()); } } return true; } } /* namespace */ PLUGINLIB_EXPORT_CLASS(grid_map::DeletionFilter<grid_map::GridMap>, filters::FilterBase<grid_map::GridMap>)
1,295
461
#include <bits/stdc++.h> using namespace std; int get_value_base(int num, int base) { int rv = 0; int p = 1; while (num > 0) { int dig = num % base; num = num / base; rv += dig * p; p = p * 10; } return rv; } int main() { int num = 634; int base = 8; int ans = 0; ans = get_value_base(num, base); cout << ans << endl; return 0; }
411
173
#include <cstdio> #include <cstring> #include <cstdlib> /**< 问题:最长递增子序列 */ // Ref: http://blog.csdn.net/joylnwang/article/details/6766317 // Ref: http://qiemengdao.iteye.com/blog/1660229 /* 给定一个长度为 N 的数组 a0, a1, a2, ..., an - 1,找出一个最长的单调递增子序列 * 递增的意思是对于任意的 i < j,都满足 ai < aj,此外子序列的意思是不要求连续,顺序不乱即可。 * 例如,长度为 6 的数组 A = {5, 6, 7, 1, 2, 8},则其最长的单调递增子序列为 {5, 6, 7, 8},长度为 4。 */ int LIncSeq1(int const* inArr, int const len) { if (len < 0) return len; int* const dp = new int[len]; int* const pre = new int[len]; // 储存开始位置 for (int k = 0; k < len; ++k) { dp[k] = 1; pre[k] = k; } // 寻找以 k 为末尾的最长递增子序列 for (int k = 1; k < len; ++k) for (int m = 0; m < k; ++m) { if (inArr[m] < inArr[k] && dp[k] < dp[m] + 1) { dp[k] = dp[m] + 1; pre[k] = m; } } int liss = 1; int iE = 0; // 末尾 for (int k = 1; k < len; ++k) if (liss < dp[k]) { liss = dp[k]; iE = k; } int* rst = new int[liss]; int pos = liss - 1; while (pre[iE] != iE) { rst[pos] = inArr[iE]; --pos; iE = pre[iE]; } rst[pos] = inArr[iE]; // 输出原始数组和结果 printf("\nArray (%d):\n", len); for (int k = 0; k < len; ++k) printf(" %+d", inArr[k]);; printf("\nLongest Increase Sub-Sequence (%d):\n", liss); for (int k = 0; k < liss; ++k) printf(" %+d", rst[k]); delete[] dp; delete[] pre; delete[] rst; return liss; } int main() { int const arr1[] = { 35, 36, 39, 3, 15, 27, 6, 42 }; int const n1 = sizeof(arr1) / sizeof(arr1[0]); LIncSeq1(arr1, n1); printf("\n"); return 0; }
1,493
945
#include <bits/stdc++.h> #define FOR(i, a, b) for (int i = a; i <= b; ++i) #define RFOR(i, b, a) for (int i = b; i >= a; --i) #define REP(i, N) for (int i = 0; i < N; ++i) #define MAXN 10000 #define INF 0x3F3F3F3F #define LINF 0x3F3F3F3FFFFFFFFFLL #define pb push_back #define mp make_pair using namespace std; struct tri { int atual, custo; tri(int atual = 0, int custo = 0) : atual(atual) , custo(custo) { } }; int n, m; typedef vector<int> vi; typedef vector<vi> vii; typedef vector<tri> vtri; typedef vector<vtri> vvtri; typedef long long int64; typedef unsigned long long uint64; typedef pair<int, int> ii; int visitado[100000], dist[1000000], res[1001][1001], p[10000], visited[10000], check = 1, s, t, f; vvtri grafo; void initialize() { REP(i, n) { FOR(j, i, n) res[i][j] = res[j][i] = 0; res[i][i] = 0; } } void augment(int v, int minEdge) { if (v == s) { f = minEdge; return; } else if (p[v] != -1) { augment(p[v], min(minEdge, res[p[v]][v])); res[p[v]][v] -= f; res[v][p[v]] += f; } } void dfs(int u) { if (u == t) return; REP(i, grafo[u].size()) { tri atual = grafo[u][i]; if (visited[atual.atual] != check && res[u][atual.atual] > 0) { visited[atual.atual] = check; p[atual.atual] = u; dfs(atual.atual); } } } int djsktra(int de, int para) { REP(i, n) { dist[i] = INF; visitado[i] = false; } tri atual; ii at; priority_queue<ii> pq; pq.push(mp(INF, de)); dist[de] = 0; int ans = 0; while (!pq.empty()) { at = pq.top(); pq.pop(); if (at.second == para) ans = max(ans, at.first); if (visitado[at.second]) continue; visitado[at.second] = true; int custo = at.first; int v = at.second; REP(i, grafo[v].size()) { atual = grafo[v][i]; pq.push(mp(min(custo, atual.custo), atual.atual)); } } return ans; } int main() { ios::sync_with_stdio(false); int tt, de, para, atoa, custo; cin >> tt; while (tt--) { cin >> atoa >> n >> m >> s >> t; grafo.resize(n + 10); initialize(); REP(i, m) { cin >> de >> para >> custo; grafo[de].pb(tri(para, custo)); grafo[para].pb(tri(de, custo)); res[de][para] = custo; } int ans, mf = 0; ans = djsktra(s, t); while (true) { f = 0; REP(i, t + 1) p[i] = -1; visited[s] = check; dfs(s); check++; augment(t, INF); if (!f) break; mf += f; } cout << atoa << " " << setprecision(3) << fixed << (double)mf / (double)ans << "\n"; grafo.clear(); check++; } return 0; }
3,001
1,249
#include <volt/pch.hpp> #include <volt/config.hpp> #include <volt/util/util.hpp> #include <volt/log.hpp> #include <volt/paths.hpp> namespace fs = std::filesystem; namespace nl = nlohmann; #ifdef VOLT_DEVELOPMENT static nl::json base_config; #endif static nl::json default_config, config; static nl::json cleave(nl::json from, const nl::json &what) { // Cleave from + what std::stack<std::pair<nl::json &, const nl::json &>> objects_to_cleave; objects_to_cleave.emplace(from, what); while (!objects_to_cleave.empty()) { nl::json &from = objects_to_cleave.top().first; const nl::json &what = objects_to_cleave.top().second; objects_to_cleave.pop(); for (auto it = from.begin(); it != from.end();) { auto prev = it++; if (what.contains(prev.key())) { nl::json &from_v = prev.value(); const nl::json &what_v = what[prev.key()]; if (from_v == what_v) from.erase(prev); else if (from_v.is_object() && what_v.is_object()) objects_to_cleave.emplace(from_v, what_v); } } } return from; } namespace volt::config { static void load_from_data() { try { ::config.update(nl::json::parse(util::read_text_file( paths::data() / "config.json"))); VOLT_LOG_INFO("User configuration has been loaded.") } catch (...) { VOLT_LOG_INFO("No user configuration available.") } } nl::json &json() { return ::config; } void save() { nl::json cleaved = cleave(::config, default_config); util::write_file(paths::data() / "config.json", cleaved.dump(1, '\t')); } void reset_to_default() { ::config = default_config; } #ifdef VOLT_DEVELOPMENT void save_default() { nl::json cleaved = cleave(default_config, base_config); util::write_file(fs::path(VOLT_DEVELOPMENT_PATH) / "config.json", cleaved.dump(1, '\t')); } void reset_to_base() { ::config = default_config = base_config; } void load() { load_from_data(); } #endif } namespace volt::config::_internal { void init() { #ifdef VOLT_DEVELOPMENT std::vector<std::string> paths = util::split(util::read_text_file( fs::path(VOLT_DEVELOPMENT_PATH) / "cache" / "packages.txt"), "\n"); base_config = nl::json::object(); for (auto &path_item : paths) { auto path = path_item.substr(path_item.find(' ') + 1) / fs::path("config.json"); if (fs::exists(path)) base_config.update(nl::json::parse(util::read_text_file(path))); } default_config = base_config; auto path = fs::path(VOLT_DEVELOPMENT_PATH) / "config.json"; if (fs::exists(path)) default_config.update(nl::json::parse(util::read_text_file(path))); #else default_config = nl::json::parse(util::read_text_file( fs::current_path() / ".." / "config.json")); #endif ::config = default_config; #ifndef VOLT_DEVELOPMENT load_from_data(); #endif } }
2,739
1,129
#ifndef SASS_MEMORY_POOL_H #define SASS_MEMORY_POOL_H #include <stdlib.h> #include <iostream> #include <algorithm> #include <climits> #include <vector> namespace Sass { // SIMPLE MEMORY-POOL ALLOCATOR WITH FREE-LIST ON TOP // This is a memory pool allocator with a free list on top. // We only allocate memory arenas from the system in specific // sizes (`SassAllocatorArenaSize`). Users claim memory slices // of certain sizes from the pool. If the allocation is too big // to fit into our buckets, we use regular malloc/free instead. // When the systems starts, we allocate the first arena and then // start to give out addresses to memory slices. During that // we steadily increase `offset` until the current arena is full. // Once that happens we allocate a new arena and continue. // https://en.wikipedia.org/wiki/Memory_pool // Fragments that get deallocated are not really freed, we put // them on our free-list. For every bucket we have a pointer to // the first item for reuse. That item itself holds a pointer to // the previously free item (regular free-list implementation). // https://en.wikipedia.org/wiki/Free_list // On allocation calls we first check if there is any suitable // item on the free-list. If there is we pop it from the stack // and return it to the caller. Otherwise we have to take out // a new slice from the current `arena` and increase `offset`. // Note that this is not thread safe. This is on purpose as we // want to use the memory pool in a thread local usage. In order // to get this thread safe you need to only allocate one pool // per thread. This can be achieved by using thread local PODs. // Simply create a pool on the first allocation and dispose // it once all allocations have been returned. E.g. by using: // static thread_local size_t allocations; // static thread_local MemoryPool* pool; class MemoryPool { // Current arena we fill up char* arena; // Position into the arena size_t offset = std::string::npos; // A list of full arenas std::vector<void*> arenas; // One pointer for every bucket (zero init) void* freeList[SassAllocatorBuckets] = {}; // Increase the address until it sits on a // memory aligned address (maybe use `aligned`). inline static size_t alignMemAddr(size_t addr) { return (addr + SASS_MEM_ALIGN - 1) & ~(SASS_MEM_ALIGN - 1); } public: // Default ctor MemoryPool() : // Wait for first allocation arena(nullptr), // Set to maximum value in order to // make an allocation on the first run offset(std::string::npos) { } // Destructor ~MemoryPool() { // Delete full arenas for (auto area : arenas) { free(area); } // Delete current arena free(arena); } // Allocate a slice of the memory pool void* allocate(size_t size) { // Increase size so its memory is aligned size = alignMemAddr( // Make sure we have enough space for us to // create the pointer to the free list later std::max(sizeof(void*), size) // and the size needed for our book-keeping + SassAllocatorBookSize); // Size must be multiple of alignment // So we can derive bucket index from it size_t bucket = size / SASS_MEM_ALIGN; // Everything bigger is allocated via malloc // Malloc is optimized for exactly this case if (bucket >= SassAllocatorBuckets) { char* buffer = (char*)malloc(size); if (buffer == nullptr) { throw std::bad_alloc(); } // Mark it for deallocation via free ((unsigned int*)buffer)[0] = UINT_MAX; // Return pointer after our book-keeping space return (void*)(buffer + SassAllocatorBookSize); } // Use custom allocator else { // Get item from free list void*& free = freeList[bucket]; // Do we have a free item? if (free != nullptr) { // Copy pointer to return void* ptr = free; // Update free list pointer free = ((void**)ptr)[0]; // Return popped item return ptr; } } // Make sure we have enough space in the arena if (!arena || offset > SassAllocatorArenaSize - size) { if (arena) arenas.emplace_back(arena); arena = (char*)malloc(SassAllocatorArenaSize); if (arena == nullptr) throw std::bad_alloc(); offset = SassAllocatorArenaHeadSize; } // Get pointer into the arena char* buffer = arena + offset; // Consume object size offset += size; // Set the bucket index for this slice ((unsigned int*)buffer)[0] = (unsigned int)bucket; // Return pointer after our book-keeping space return (void*)(buffer + SassAllocatorBookSize); } // EO allocate void deallocate(void* ptr) { // Rewind buffer from pointer char* buffer = (char*)ptr - SassAllocatorBookSize; // Get the bucket index stored in the header unsigned int bucket = ((unsigned int*)buffer)[0]; // Check allocation method if (bucket != UINT_MAX) { // Let memory point to previous item in free list ((void**)ptr)[0] = freeList[bucket]; // Free list now points to our memory freeList[bucket] = (void*)ptr; } else { // Release memory free(buffer); } } // EO deallocate }; } #endif
5,562
1,630
// Copyright (C) 2008-2018 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 (see accompanying // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt). // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html // Test invariant compilation on/off (using macro interface). #include "../detail/oteststream.hpp" #include "../detail/unprotected_commas.hpp" #include <boost/contract_macro.hpp> #include <boost/detail/lightweight_test.hpp> #include <sstream> boost::contract::test::detail::oteststream out; class a { public: BOOST_CONTRACT_STATIC_INVARIANT({ boost::contract::test::detail::unprotected_commas<void, void, void>:: call(); out << "a::static_inv" << std::endl; }) BOOST_CONTRACT_INVARIANT_VOLATILE({ boost::contract::test::detail::unprotected_commas<void, void, void>:: call(); out << "a::cv_inv" << std::endl; }) BOOST_CONTRACT_INVARIANT({ boost::contract::test::detail::unprotected_commas<void, void, void>:: call(); out << "a::const_inv" << std::endl; }) a() { // Test check both cv and const invariant (at exit if no throw). BOOST_CONTRACT_CONSTRUCTOR(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::ctor::body" << std::endl; } ~a() { // Test check both cv and const invariant (at entry). BOOST_CONTRACT_DESTRUCTOR(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::dtor::body" << std::endl; } void m() { // Test check const invariant (at entry and exit). BOOST_CONTRACT_PUBLIC_FUNCTION(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::m::body" << std::endl; } void c() const { // Test check const invariant (at entry and exit). BOOST_CONTRACT_PUBLIC_FUNCTION(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::c::body" << std::endl; } void v() volatile { // Test check cv invariant (at entry and exit). BOOST_CONTRACT_PUBLIC_FUNCTION(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::v::body" << std::endl; } void cv() const volatile { // Test check cv invariant (at entry and exit). BOOST_CONTRACT_PUBLIC_FUNCTION(boost::contract::test::detail:: unprotected_commas<void, void, void>::same(this)); out << "a::cv::body" << std::endl; } }; int main() { std::ostringstream ok; { out.str(""); a aa; ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl #endif << "a::ctor::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl << "a::const_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); out.str(""); aa.m(); ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl << "a::const_inv" << std::endl #endif << "a::m::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl << "a::const_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); out.str(""); aa.c(); ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl << "a::const_inv" << std::endl #endif << "a::c::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl << "a::const_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); out.str(""); aa.v(); ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl #endif << "a::v::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); out.str(""); aa.cv(); ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl #endif << "a::cv::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); out.str(""); } // Call dtor. ok.str(""); ok #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS << "a::static_inv" << std::endl << "a::cv_inv" << std::endl << "a::const_inv" << std::endl #endif << "a::dtor::body" << std::endl #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS << "a::static_inv" << std::endl #endif ; BOOST_TEST(out.eq(ok.str())); return boost::report_errors(); }
5,851
2,042
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <xalanc/Include/PlatformDefinitions.hpp> #include <cmath> #include <cstring> #include <ctime> #if defined(XALAN_CLASSIC_IOSTREAMS) #include <iostream.h> #else #include <iostream> #endif #include <xercesc/util/PlatformUtils.hpp> #include <xalanc/XalanTransformer/XalanTransformer.hpp> #include <xalanc/XPath/Function.hpp> #include <xalanc/XPath/XObjectFactory.hpp> XALAN_USING_XALAN(Function) XALAN_USING_XALAN(Locator) XALAN_USING_XALAN(XPathExecutionContext) XALAN_USING_XALAN(XalanDOMString) XALAN_USING_XALAN(XalanNode) XALAN_USING_XALAN(XObjectPtr) XALAN_USING_XALAN(MemoryManager) XALAN_USING_XALAN(XalanCopyConstruct) // This class defines a function that will return the square root // of its argument. class FunctionSquareRoot : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. Extension functions should override this version of execute(), * rather than one of the other calls designed for a specific number of * arguments. * * @param executionContext executing context * @param context current context node * @param args vector of pointers to XObject arguments * @param locator Locator for the XPath expression that contains the function call * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectArgVectorType& args, const Locator* locator) const { if (args.size() != 1) { XPathExecutionContext::GetAndReleaseCachedString theGuard(executionContext); generalError(executionContext, context, locator); } assert(args[0].null() == false); #if defined(XALAN_STRICT_ANSI_HEADERS) using std::sqrt; #endif return executionContext.getXObjectFactory().createNumber(sqrt(args[0]->num(executionContext))); } using Function::execute; /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionSquareRoot* #endif clone(MemoryManager& theManager) const { return XalanCopyConstruct(theManager, *this); } protected: /** * Get the error message to report when * the function is called with the wrong * number of arguments. * * @return function error message */ const XalanDOMString& getError(XalanDOMString& theResult) const { theResult.assign("The square-root() function accepts one argument!"); return theResult; } private: // Not implemented... FunctionSquareRoot& operator=(const FunctionSquareRoot&); bool operator==(const FunctionSquareRoot&) const; }; // This class defines a function that will return the cube // of its argument. class FunctionCube : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. Extension functions should override this version of execute(), * rather than one of the other calls designed for a specific number of * arguments. * * @param executionContext executing context * @param context current context node * @param args vector of pointers to XObject arguments * @param locator Locator for the XPath expression that contains the function call * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectArgVectorType& args, const Locator* locator) const { if (args.size() != 1) { XPathExecutionContext::GetAndReleaseCachedString theGuard(executionContext); generalError(executionContext, context, locator); } assert(args[0].null() == false); #if defined(XALAN_STRICT_ANSI_HEADERS) using std::pow; #endif return executionContext.getXObjectFactory().createNumber(pow(args[0]->num(executionContext), 3)); } using Function::execute; /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionCube* #endif clone(MemoryManager& theManager) const { return XalanCopyConstruct(theManager, *this); } protected: /** * Get the error message to report when * the function is called with the wrong * number of arguments. * * @return function error message */ const XalanDOMString& getError(XalanDOMString& theResult) const { theResult.assign("The cube() function accepts one argument!"); return theResult; } private: // Not implemented... FunctionCube& operator=(const FunctionCube&); bool operator==(const FunctionCube&) const; }; // This class defines a function that runs the C function // asctime() using the current system time. class FunctionAsctime : public Function { public: /** * Execute an XPath function object. The function must return a valid * object. Extension functions should override this version of execute(), * rather than one of the other calls designed for a specific number of * arguments. * * @param executionContext executing context * @param context current context node * @param args vector of pointers to XObject arguments * @param locator Locator for the XPath expression that contains the function call * @return pointer to the result XObject */ virtual XObjectPtr execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectArgVectorType& args, const Locator* locator) const { if (args.empty() == false) { generalError(executionContext, context, locator); } #if defined(XALAN_STRICT_ANSI_HEADERS) using std::time; using std::time_t; using std::localtime; using std::asctime; using std::strlen; #endif time_t theTime; time(&theTime); char* const theTimeString = asctime(localtime(&theTime)); assert(theTimeString != 0); // The resulting string has a newline character at the end, // so get rid of it. theTimeString[strlen(theTimeString) - 1] = '\0'; return executionContext.getXObjectFactory().createString(XalanDOMString(theTimeString)); } using Function::execute; /** * Create a copy of the function object. * * @return pointer to the new object */ #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionAsctime* #endif clone(MemoryManager& theManager) const { return XalanCopyConstruct(theManager, *this); } protected: /** * Get the error message to report when * the function is called with the wrong * number of arguments. * * @return function error message */ const XalanDOMString& getError(XalanDOMString& theResult) const { theResult.assign("The asctime() function accepts one argument!"); return theResult; } private: // Not implemented... FunctionAsctime& operator=(const FunctionAsctime&); bool operator==(const FunctionAsctime&) const; }; int main( int argc, char* /* argv */[]) { XALAN_USING_STD(cerr) XALAN_USING_STD(endl) int theResult = 0; if (argc != 1) { cerr << "Usage: ExternalFunction" << endl << endl; } else { XALAN_USING_XERCES(XMLPlatformUtils) XALAN_USING_XERCES(XMLException) XALAN_USING_XALAN(XalanTransformer) // Call the static initializer for Xerces. try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { cerr << "Error during Xerces initialization. Error code was " << toCatch.getCode() << "." << endl; theResult = -1; } if (theResult == 0) { // Initialize Xalan. XalanTransformer::initialize(); { // Create a XalanTransformer. XalanTransformer theXalanTransformer; // The namespace for our functions... const XalanDOMString theNamespace("http://ExternalFunction.xalan-c++.xml.apache.org"); // Install the functions in the local space. They will only // be installed in this instance, so no other instances // will know about them... theXalanTransformer.installExternalFunction( theNamespace, XalanDOMString("asctime"), FunctionAsctime()); theXalanTransformer.installExternalFunction( theNamespace, XalanDOMString("square-root"), FunctionSquareRoot()); theXalanTransformer.installExternalFunction( theNamespace, XalanDOMString("cube"), FunctionCube()); // Do the transform. theResult = theXalanTransformer.transform("foo.xml", "foo.xsl", "foo.out"); if(theResult != 0) { cerr << "ExternalFunction Error: \n" << theXalanTransformer.getLastError() << endl << endl; } } // Terminate Xalan... XalanTransformer::terminate(); } // Terminate Xerces... XMLPlatformUtils::Terminate(); // Clean up the ICU, if it's integrated... XalanTransformer::ICUCleanUp(); } return theResult; }
11,349
3,149
/* * (C) Copyright 1996- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ #include "eckit/linalg/sparse/LinearAlgebraEigen.h" #include <ostream> #include "eckit/exception/Exceptions.h" #include "eckit/linalg/Matrix.h" #include "eckit/linalg/SparseMatrix.h" #include "eckit/linalg/Vector.h" #include "eckit/linalg/sparse/LinearAlgebraGeneric.h" #include "eckit/maths/Eigen.h" namespace eckit { namespace linalg { namespace sparse { static const LinearAlgebraEigen __la("eigen"); using vec_t = Eigen::VectorXd::MapType; using mat_t = Eigen::MatrixXd::MapType; using spm_t = Eigen::MappedSparseMatrix<Scalar, Eigen::RowMajor, Index>; void LinearAlgebraEigen::print(std::ostream& out) const { out << "LinearAlgebraEigen[]"; } void LinearAlgebraEigen::spmv(const SparseMatrix& A, const Vector& x, Vector& y) const { ASSERT(x.size() == A.cols()); ASSERT(y.size() == A.rows()); // We expect indices to be 0-based ASSERT(A.outer()[0] == 0); // Eigen requires non-const pointers to the data spm_t Ai(A.rows(), A.cols(), A.nonZeros(), const_cast<Index*>(A.outer()), const_cast<Index*>(A.inner()), const_cast<Scalar*>(A.data())); vec_t xi(Eigen::VectorXd::Map(const_cast<Scalar*>(x.data()), x.size())); vec_t yi(Eigen::VectorXd::Map(y.data(), y.size())); yi = Ai * xi; } void LinearAlgebraEigen::spmm(const SparseMatrix& A, const Matrix& B, Matrix& C) const { ASSERT(A.cols() == B.rows()); ASSERT(A.rows() == C.rows()); ASSERT(B.cols() == C.cols()); // We expect indices to be 0-based ASSERT(A.outer()[0] == 0); // Eigen requires non-const pointers to the data spm_t Ai(A.rows(), A.cols(), A.nonZeros(), const_cast<Index*>(A.outer()), const_cast<Index*>(A.inner()), const_cast<Scalar*>(A.data())); mat_t Bi(Eigen::MatrixXd::Map(const_cast<Scalar*>(B.data()), B.rows(), B.cols())); mat_t Ci(Eigen::MatrixXd::Map(C.data(), C.rows(), C.cols())); Ci = Ai * Bi; } void LinearAlgebraEigen::dsptd(const Vector& x, const SparseMatrix& A, const Vector& y, SparseMatrix& B) const { static const sparse::LinearAlgebraGeneric generic; generic.dsptd(x, A, y, B); } } // namespace sparse } // namespace linalg } // namespace eckit
2,541
967
/* * Copyright 2019, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.hpp" #include "helper.hpp" #include <avm/machinestate/machinestate.hpp> #include <avm_values/vmValueParser.hpp> #include <data_storage/checkpoint/checkpointstorage.hpp> #include <data_storage/checkpoint/machinestatedeleter.hpp> #include <data_storage/checkpoint/machinestatefetcher.hpp> #include <data_storage/checkpoint/machinestatesaver.hpp> #include <catch2/catch.hpp> #include <boost/filesystem.hpp> void saveValue(MachineStateSaver& saver, const value& val, int expected_ref_count, bool expected_status) { auto results = saver.saveValue(val); saver.commitTransaction(); REQUIRE(results.status.ok() == expected_status); REQUIRE(results.reference_count == expected_ref_count); } void getValue(MachineStateFetcher& fetcher, std::vector<unsigned char>& hash_key, int expected_ref_count, uint256_t& expected_hash, ValueTypes expected_value_type, bool expected_status) { auto results = fetcher.getValue(hash_key); auto serialized_val = checkpoint::utils::serializeValue(results.data); auto type = (ValueTypes)serialized_val[0]; REQUIRE(results.status.ok() == expected_status); REQUIRE(results.reference_count == expected_ref_count); REQUIRE(type == expected_value_type); REQUIRE(hash(results.data) == expected_hash); } void saveTuple(MachineStateSaver& saver, const Tuple& tup, int expected_ref_count, bool expected_status) { auto results = saver.saveTuple(tup); saver.commitTransaction(); REQUIRE(results.status.ok() == expected_status); REQUIRE(results.reference_count == expected_ref_count); } void getTuple(MachineStateFetcher& fetcher, std::vector<unsigned char>& hash_key, int expected_ref_count, uint256_t& expected_hash, int expected_tuple_size, bool expected_status) { auto results = fetcher.getTuple(hash_key); REQUIRE(results.reference_count == expected_ref_count); REQUIRE(results.data.calculateHash() == expected_hash); REQUIRE(results.data.tuple_size() == expected_tuple_size); REQUIRE(results.status.ok() == expected_status); } void getTupleValues(MachineStateFetcher& fetcher, std::vector<unsigned char>& hash_key, std::vector<uint256_t> value_hashes) { auto results = fetcher.getTuple(hash_key); REQUIRE(results.data.tuple_size() == value_hashes.size()); for (size_t i = 0; i < value_hashes.size(); i++) { REQUIRE(hash(results.data.get_element(i)) == value_hashes[i]); } } TEST_CASE("Save value") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); SECTION("save 1 num tuple") { TuplePool pool; uint256_t num = 1; auto tuple = Tuple(num, &pool); saveValue(saver, tuple, 1, true); } SECTION("save num") { uint256_t num = 1; saveValue(saver, num, 1, true); } SECTION("save codepoint") { auto code_point = CodePoint(1, Operation(), 0); saveValue(saver, code_point, 1, true); } } TEST_CASE("Save tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); TuplePool pool; SECTION("save 1 num tuple") { uint256_t num = 1; auto tuple = Tuple(num, &pool); saveTuple(saver, tuple, 1, true); } SECTION("save 2, 1 num tuples") { uint256_t num = 1; auto tuple = Tuple(num, &pool); saveTuple(saver, tuple, 1, true); saveTuple(saver, tuple, 2, true); } SECTION("saved tuple in tuple") { uint256_t num = 1; auto inner_tuple = Tuple(num, &pool); auto tuple = Tuple(inner_tuple, &pool); saveTuple(saver, tuple, 1, true); saveTuple(saver, tuple, 2, true); } } TEST_CASE("Save and get value") { SECTION("save empty tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto tuple = Tuple(); auto hash_key = GetHashKey(tuple); auto tup_hash = tuple.calculateHash(); saveValue(saver, tuple, 1, true); getValue(fetcher, hash_key, 1, tup_hash, TUPLE, true); } SECTION("save tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; TuplePool pool; auto tuple = Tuple(num, &pool); auto hash_key = GetHashKey(tuple); auto tup_hash = tuple.calculateHash(); saveValue(saver, tuple, 1, true); getValue(fetcher, hash_key, 1, tup_hash, TUPLE, true); } SECTION("save num") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto hash_key = GetHashKey(num); auto num_hash = hash(num); saveValue(saver, num, 1, true); getValue(fetcher, hash_key, 1, num_hash, NUM, true); } SECTION("save codepoint") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto hash_key = GetHashKey(code_point); auto cp_hash = hash(code_point); saveValue(saver, code_point, 1, true); getValue(fetcher, hash_key, 1, cp_hash, CODEPT, true); } SECTION("save err codepoint") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto code_point = getErrCodePoint(); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto hash_key = GetHashKey(code_point); auto cp_hash = hash(code_point); saveValue(saver, code_point, 1, true); getValue(fetcher, hash_key, 1, cp_hash, CODEPT, true); } } TEST_CASE("Save and get tuple values") { SECTION("save num tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; TuplePool pool; auto tuple = Tuple(num, &pool); saveTuple(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(num)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } SECTION("save codepoint tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[1]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); TuplePool pool; auto tuple = Tuple(code_point, &pool); saveTuple(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(code_point)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } SECTION("save codepoint tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); TuplePool pool; auto tuple = Tuple(code_point, &pool); saveValue(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(code_point)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } SECTION("save nested tuple") { DBDeleter deleter; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto inner_tuple = Tuple(); TuplePool pool; auto tuple = Tuple(inner_tuple, &pool); saveTuple(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(inner_tuple)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } SECTION("save multiple valued tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto inner_tuple = Tuple(); uint256_t num = 1; auto tuple = Tuple(inner_tuple, num, code_point, &pool); saveTuple(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(inner_tuple), hash(num), hash(code_point)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } SECTION("save multiple valued tuple, saveValue()") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[2]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto inner_tuple = Tuple(); uint256_t num = 1; auto tuple = Tuple(inner_tuple, num, code_point, &pool); saveValue(saver, tuple, 1, true); std::vector<uint256_t> hashes{hash(inner_tuple), hash(num), hash(code_point)}; auto hash_key = GetHashKey(tuple); getTupleValues(fetcher, hash_key, hashes); } } TEST_CASE("Save And Get Tuple") { SECTION("save 1 num tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto tuple = Tuple(num, &pool); auto tup_hash = tuple.calculateHash(); auto hash_key = GetHashKey(tuple); saveTuple(saver, tuple, 1, true); getTuple(fetcher, hash_key, 1, tup_hash, 1, true); } SECTION("save codepoint in tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto tuple = Tuple(code_point, &pool); auto tup_hash = tuple.calculateHash(); auto hash_key = GetHashKey(tuple); saveTuple(saver, tuple, 1, true); getTuple(fetcher, hash_key, 1, tup_hash, 1, true); } SECTION("save 1 num tuple twice") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto saver2 = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto tuple = Tuple(num, &pool); auto tup_hash = tuple.calculateHash(); auto hash_key = GetHashKey(tuple); saveTuple(saver, tuple, 1, true); saveTuple(saver2, tuple, 2, true); getTuple(fetcher, hash_key, 2, tup_hash, 1, true); } SECTION("save 2 num tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); std::vector<CodePoint> code; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; uint256_t num2 = 2; auto tuple = Tuple(num, num2, &pool); auto tup_hash = tuple.calculateHash(); auto hash_key = GetHashKey(tuple); saveTuple(saver, tuple, 1, true); getTuple(fetcher, hash_key, 1, tup_hash, 2, true); } SECTION("save tuple in tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto inner_tuple = Tuple(num, &pool); auto tuple = Tuple(inner_tuple, &pool); saveTuple(saver, tuple, 1, true); auto inner_hash_key = GetHashKey(inner_tuple); auto inner_tup_hash = inner_tuple.calculateHash(); auto hash_key = GetHashKey(tuple); auto tup_hash = tuple.calculateHash(); getTuple(fetcher, hash_key, 1, tup_hash, 1, true); getTuple(fetcher, inner_hash_key, 1, inner_tup_hash, 1, true); } SECTION("save 2 tuples in tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto inner_tuple = Tuple(num, &pool); uint256_t num2 = 2; auto inner_tuple2 = Tuple(num2, &pool); auto tuple = Tuple(inner_tuple, inner_tuple2, &pool); saveTuple(saver, tuple, 1, true); auto inner_hash_key = GetHashKey(inner_tuple); auto inner_tup_hash = inner_tuple.calculateHash(); auto inner_hash_key2 = GetHashKey(inner_tuple2); auto inner_tup_hash2 = inner_tuple2.calculateHash(); auto hash_key = GetHashKey(tuple); auto tup_hash = tuple.calculateHash(); getTuple(fetcher, hash_key, 1, tup_hash, 2, true); getTuple(fetcher, inner_hash_key, 1, inner_tup_hash, 1, true); getTuple(fetcher, inner_hash_key2, 1, inner_tup_hash2, 1, true); } SECTION("save saved tuple in tuple") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); auto saver = MachineStateSaver(storage.makeTransaction()); auto saver2 = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); uint256_t num = 1; auto inner_tuple = Tuple(num, &pool); auto tuple = Tuple(inner_tuple, &pool); auto inner_hash_key = GetHashKey(inner_tuple); auto inner_tup_hash = inner_tuple.calculateHash(); auto hash_key = GetHashKey(tuple); auto tup_hash = tuple.calculateHash(); saveTuple(saver, inner_tuple, 1, true); getTuple(fetcher, inner_hash_key, 1, inner_tup_hash, 1, true); saveTuple(saver2, tuple, 1, true); getTuple(fetcher, hash_key, 1, tup_hash, 1, true); getTuple(fetcher, inner_hash_key, 2, inner_tup_hash, 1, true); } } void saveState(MachineStateSaver& saver, MachineStateKeys storage_data, std::vector<unsigned char> checkpoint_name) { auto results = saver.saveMachineState(storage_data, checkpoint_name); auto status = saver.commitTransaction(); REQUIRE(results.reference_count == 1); REQUIRE(results.status.ok()); } void getSavedState(MachineStateFetcher& fetcher, std::vector<unsigned char> checkpoint_name, MachineStateKeys expected_data, int expected_ref_count, std::vector<std::vector<unsigned char>> keys) { auto results = fetcher.getMachineState(checkpoint_name); REQUIRE(results.status.ok()); REQUIRE(results.reference_count == expected_ref_count); auto data = results.data; REQUIRE(data.status_char == expected_data.status_char); REQUIRE(data.pc_key == expected_data.pc_key); REQUIRE(data.datastack_key == expected_data.datastack_key); REQUIRE(data.auxstack_key == expected_data.auxstack_key); REQUIRE(data.register_val_key == expected_data.register_val_key); for (auto& key : keys) { auto res = fetcher.getValue(key); REQUIRE(res.status.ok()); } } void deleteCheckpoint(CheckpointStorage& storage, MachineStateFetcher& fetcher, std::vector<unsigned char> checkpoint_name, std::vector<std::vector<unsigned char>> deleted_values) { auto res = deleteCheckpoint(storage, checkpoint_name); auto results = fetcher.getMachineState(checkpoint_name); REQUIRE(results.status.ok() == false); for (auto& hash_key : deleted_values) { auto res = fetcher.getValue(hash_key); REQUIRE(res.status.ok() == false); } } void deleteCheckpointSavedTwice( CheckpointStorage& storage, MachineStateFetcher& fetcher, std::vector<unsigned char> checkpoint_name, std::vector<std::vector<unsigned char>> deleted_values) { auto res = deleteCheckpoint(storage, checkpoint_name); auto res2 = deleteCheckpoint(storage, checkpoint_name); auto results = fetcher.getMachineState(checkpoint_name); REQUIRE(results.status.ok() == false); for (auto& hash_key : deleted_values) { auto res = fetcher.getValue(hash_key); REQUIRE(res.status.ok() == false); } } void deleteCheckpointSavedTwiceReordered( CheckpointStorage& storage, MachineStateFetcher& fetcher, std::vector<unsigned char> checkpoint_name, std::vector<std::vector<unsigned char>> deleted_values) { auto resultsx = fetcher.getMachineState(checkpoint_name); for (auto& hash_key : deleted_values) { auto res = fetcher.getValue(hash_key); REQUIRE(res.status.ok()); } auto res = deleteCheckpoint(storage, checkpoint_name); auto results = fetcher.getMachineState(checkpoint_name); REQUIRE(results.status.ok() == true); for (auto& hash_key : deleted_values) { auto res = fetcher.getValue(hash_key); REQUIRE(res.status.ok()); } auto res2 = deleteCheckpoint(storage, checkpoint_name); auto results2 = fetcher.getMachineState(checkpoint_name); REQUIRE(results2.status.ok() == false); for (auto& hash_key : deleted_values) { auto res = fetcher.getValue(hash_key); REQUIRE(res.status.ok() == false); } } MachineStateKeys makeStorageData(MachineStateSaver& stateSaver, value registerVal, Datastack stack, Datastack auxstack, Status state, CodePoint pc, CodePoint err_pc, BlockReason blockReason) { TuplePool pool; auto datastack_results = stack.checkpointState(stateSaver, &pool); auto auxstack_results = auxstack.checkpointState(stateSaver, &pool); auto register_val_results = stateSaver.saveValue(registerVal); auto pc_results = stateSaver.saveValue(pc); auto err_pc_results = stateSaver.saveValue(err_pc); auto status_str = (unsigned char)state; return MachineStateKeys{ register_val_results.storage_key, datastack_results.storage_key, auxstack_results.storage_key, pc_results.storage_key, err_pc_results.storage_key, status_str}; } MachineStateKeys getStateValues(MachineStateSaver& saver) { TuplePool pool; uint256_t register_val = 100; auto static_val = Tuple(register_val, Tuple(), &pool); auto code_point = CodePoint(1, Operation(), 0); auto tup1 = Tuple(register_val, &pool); auto tup2 = Tuple(code_point, tup1, &pool); Datastack data_stack; data_stack.push(register_val); Datastack aux_stack; aux_stack.push(register_val); aux_stack.push(code_point); CodePoint pc_codepoint(0, Operation(), 0); CodePoint err_pc_codepoint(0, Operation(), 0); Status state = Status::Extensive; auto inbox_blocked = InboxBlocked(0); auto saved_data = makeStorageData(saver, register_val, data_stack, aux_stack, state, pc_codepoint, err_pc_codepoint, inbox_blocked); return saved_data; } MachineStateKeys getDefaultValues(MachineStateSaver& saver) { TuplePool pool; auto register_val = Tuple(); auto data_stack = Tuple(); auto aux_stack = Tuple(); Status state = Status::Extensive; CodePoint code_point(0, Operation(), 0); auto data = makeStorageData(saver, Tuple(), Datastack(), Datastack(), state, code_point, code_point, NotBlocked()); return data; } std::vector<std::vector<unsigned char>> getHashKeys(MachineStateKeys data) { std::vector<std::vector<unsigned char>> hash_keys; hash_keys.push_back(data.auxstack_key); hash_keys.push_back(data.datastack_key); hash_keys.push_back(data.pc_key); hash_keys.push_back(data.err_pc_key); hash_keys.push_back(data.register_val_key); return hash_keys; } TEST_CASE("Save Machinestatedata") { SECTION("default") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto data_values = getDefaultValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saveState(saver, data_values, checkpoint_key); } SECTION("with values") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; CodePoint code_point2 = storage.getInitialVmValues().code[1]; auto saver = MachineStateSaver(storage.makeTransaction()); auto state_data = getStateValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saveState(saver, state_data, checkpoint_key); } } TEST_CASE("Get Machinestate data") { SECTION("default") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto data_values = getDefaultValues(saver); auto keys = getHashKeys(data_values); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saver.saveMachineState(data_values, checkpoint_key); saver.commitTransaction(); getSavedState(fetcher, checkpoint_key, data_values, 1, keys); } SECTION("with values") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; CodePoint code_point2 = storage.getInitialVmValues().code[1]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto state_data = getStateValues(saver); auto keys = getHashKeys(state_data); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saveState(saver, state_data, checkpoint_key); getSavedState(fetcher, checkpoint_key, state_data, 1, keys); } } TEST_CASE("Delete checkpoint") { SECTION("default") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto data_values = getDefaultValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saver.saveMachineState(data_values, checkpoint_key); saver.commitTransaction(); auto hash_keys = getHashKeys(data_values); deleteCheckpoint(storage, fetcher, checkpoint_key, hash_keys); } SECTION("with actual state values") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; CodePoint code_point2 = storage.getInitialVmValues().code[2]; auto saver = MachineStateSaver(storage.makeTransaction()); auto fetcher = MachineStateFetcher(storage); auto data_values = getStateValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saver.saveMachineState(data_values, checkpoint_key); saver.commitTransaction(); auto hash_keys = getHashKeys(data_values); deleteCheckpoint(storage, fetcher, checkpoint_key, hash_keys); } SECTION("delete checkpoint saved twice") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; CodePoint code_point2 = storage.getInitialVmValues().code[1]; auto fetcher = MachineStateFetcher(storage); auto saver = MachineStateSaver(storage.makeTransaction()); auto data_values = getStateValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saver.saveMachineState(data_values, checkpoint_key); saver.saveMachineState(data_values, checkpoint_key); saver.commitTransaction(); auto hash_keys = getHashKeys(data_values); deleteCheckpointSavedTwice(storage, fetcher, checkpoint_key, hash_keys); } SECTION("delete checkpoint saved twice, reordered") { DBDeleter deleter; TuplePool pool; CheckpointStorage storage(dbpath, test_contract_path); CodePoint code_point = storage.getInitialVmValues().code[0]; CodePoint code_point2 = storage.getInitialVmValues().code[1]; auto fetcher = MachineStateFetcher(storage); auto saver = MachineStateSaver(storage.makeTransaction()); auto saver2 = MachineStateSaver(storage.makeTransaction()); auto data_values = getStateValues(saver); std::vector<unsigned char> checkpoint_key = {'k', 'e', 'y'}; saver.saveMachineState(data_values, checkpoint_key); saver.commitTransaction(); saver2.saveMachineState(data_values, checkpoint_key); saver2.commitTransaction(); auto hash_keys = getHashKeys(data_values); deleteCheckpointSavedTwiceReordered(storage, fetcher, checkpoint_key, hash_keys); } }
28,059
8,838
// Copyright (c) 2008-2022 the Urho3D project // License: MIT #include "../IK/IKSolver.h" #include "../IK/IKConstraint.h" #include "../IK/IKEvents.h" #include "../IK/IKEffector.h" #include "../IK/IKConverters.h" #include "../Core/Context.h" #include "../Core/Profiler.h" #include "../Graphics/Animation.h" #include "../Graphics/AnimationState.h" #include "../Graphics/DebugRenderer.h" #include "../IO/Log.h" #include "../Scene/SceneEvents.h" #include <ik/effector.h> #include <ik/node.h> #include <ik/solver.h> #include <ik/util.h> namespace Urho3D { extern const char* IK_CATEGORY; // ---------------------------------------------------------------------------- IKSolver::IKSolver(Context* context) : Component(context), solver_(nullptr), algorithm_(FABRIK), features_(AUTO_SOLVE | JOINT_ROTATIONS | UPDATE_ACTIVE_POSE), chainTreesNeedUpdating_(false), treeNeedsRebuild(true), solverTreeValid_(false) { context_->RequireIK(); SetAlgorithm(FABRIK); SubscribeToEvent(E_COMPONENTADDED, URHO3D_HANDLER(IKSolver, HandleComponentAdded)); SubscribeToEvent(E_COMPONENTREMOVED, URHO3D_HANDLER(IKSolver, HandleComponentRemoved)); SubscribeToEvent(E_NODEADDED, URHO3D_HANDLER(IKSolver, HandleNodeAdded)); SubscribeToEvent(E_NODEREMOVED, URHO3D_HANDLER(IKSolver, HandleNodeRemoved)); } // ---------------------------------------------------------------------------- IKSolver::~IKSolver() { // Destroying the solver tree will destroy the effector objects, so remove // any references any of the IKEffector objects could be holding for (Vector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it) (*it)->SetIKEffectorNode(nullptr); ik_solver_destroy(solver_); context_->ReleaseIK(); } // ---------------------------------------------------------------------------- void IKSolver::RegisterObject(Context* context) { context->RegisterFactory<IKSolver>(IK_CATEGORY); static const char* algorithmNames[] = { "1 Bone", "2 Bone", "FABRIK", /* not implemented, "MSD (Mass/Spring/Damper)", "Jacobian Inverse", "Jacobian Transpose",*/ nullptr }; URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Algorithm", GetAlgorithm, SetAlgorithm, Algorithm, algorithmNames, FABRIK, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Max Iterations", GetMaximumIterations, SetMaximumIterations, unsigned, 20, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Convergence Tolerance", GetTolerance, SetTolerance, float, 0.001, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Joint Rotations", GetJOINT_ROTATIONS, SetJOINT_ROTATIONS, bool, true, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Target Rotations", GetTARGET_ROTATIONS, SetTARGET_ROTATIONS, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Update Original Pose", GetUPDATE_ORIGINAL_POSE, SetUPDATE_ORIGINAL_POSE, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Update Active Pose", GetUPDATE_ACTIVE_POSE, SetUPDATE_ACTIVE_POSE, bool, true, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Use Original Pose", GetUSE_ORIGINAL_POSE, SetUSE_ORIGINAL_POSE, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Enable Constraints", GetCONSTRAINTS, SetCONSTRAINTS, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Auto Solve", GetAUTO_SOLVE, SetAUTO_SOLVE, bool, true, AM_DEFAULT); } // ---------------------------------------------------------------------------- IKSolver::Algorithm IKSolver::GetAlgorithm() const { return algorithm_; } // ---------------------------------------------------------------------------- void IKSolver::SetAlgorithm(IKSolver::Algorithm algorithm) { algorithm_ = algorithm; /* We need to rebuild the tree so make sure that the scene is in the * initial pose when this occurs.*/ if (node_ != nullptr) ApplyOriginalPoseToScene(); // Initial flags for when there is no solver to destroy uint8_t initialFlags = 0; // Destroys the tree and the solver if (solver_ != nullptr) { initialFlags = solver_->flags; DestroyTree(); ik_solver_destroy(solver_); } switch (algorithm_) { case ONE_BONE : solver_ = ik_solver_create(SOLVER_ONE_BONE); break; case TWO_BONE : solver_ = ik_solver_create(SOLVER_TWO_BONE); break; case FABRIK : solver_ = ik_solver_create(SOLVER_FABRIK); break; /*case MSD : solver_ = ik_solver_create(SOLVER_MSD); break;*/ } solver_->flags = initialFlags; if (node_ != nullptr) RebuildTree(); } // ---------------------------------------------------------------------------- bool IKSolver::GetFeature(Feature feature) const { return (features_ & feature) != 0; } // ---------------------------------------------------------------------------- void IKSolver::SetFeature(Feature feature, bool enable) { switch (feature) { case CONSTRAINTS: { solver_->flags &= ~SOLVER_ENABLE_CONSTRAINTS; if (enable) solver_->flags |= SOLVER_ENABLE_CONSTRAINTS; } break; case TARGET_ROTATIONS: { solver_->flags &= ~SOLVER_CALCULATE_TARGET_ROTATIONS; if (enable) solver_->flags |= SOLVER_CALCULATE_TARGET_ROTATIONS; } break; case AUTO_SOLVE: { if (((features_ & AUTO_SOLVE) != 0) == enable) break; if (enable) SubscribeToEvent(GetScene(), E_SCENEDRAWABLEUPDATEFINISHED, URHO3D_HANDLER(IKSolver, HandleSceneDrawableUpdateFinished)); else UnsubscribeFromEvent(GetScene(), E_SCENEDRAWABLEUPDATEFINISHED); } break; default: break; } features_ &= ~feature; if (enable) features_ |= feature; } // ---------------------------------------------------------------------------- unsigned IKSolver::GetMaximumIterations() const { return solver_->max_iterations; } // ---------------------------------------------------------------------------- void IKSolver::SetMaximumIterations(unsigned iterations) { solver_->max_iterations = iterations; } // ---------------------------------------------------------------------------- float IKSolver::GetTolerance() const { return solver_->tolerance; } // ---------------------------------------------------------------------------- void IKSolver::SetTolerance(float tolerance) { if (tolerance < M_EPSILON) tolerance = M_EPSILON; solver_->tolerance = tolerance; } // ---------------------------------------------------------------------------- ik_node_t* IKSolver::CreateIKNodeFromUrhoNode(const Node* node) { ik_node_t* ikNode = ik_node_create(node->GetID()); // Set initial position/rotation and pass in Node* as user data for later ikNode->original_position = Vec3Urho2IK(node->GetWorldPosition()); ikNode->original_rotation = QuatUrho2IK(node->GetWorldRotation()); ikNode->user_data = (void*)node; /* * If Urho's node has an effector, also create and attach one to the * library's node. At this point, the IKEffector component shouldn't be * holding a reference to any internal effector. Check this for debugging * purposes and log if it does. */ auto* effector = node->GetComponent<IKEffector>(); if (effector != nullptr) { #ifdef DEBUG if (effector->ikEffectorNode_ != nullptr) URHO3D_LOGWARNINGF("[ik] IKEffector (attached to node \"%s\") has a reference to a possibly invalid internal effector. Should be NULL.", effector->GetNode()->GetName().CString()); #endif ik_effector_t* ikEffector = ik_effector_create(); ik_node_attach_effector(ikNode, ikEffector); // ownership of effector effector->SetIKSolver(this); effector->SetIKEffectorNode(ikNode); } // Exact same deal with the constraint auto* constraint = node->GetComponent<IKConstraint>(); if (constraint != nullptr) { #ifdef DEBUG if (constraint->ikConstraintNode_ != nullptr) URHO3D_LOGWARNINGF("[ik] IKConstraint (attached to node \"%s\") has a reference to a possibly invalid internal constraint. Should be NULL.", constraint->GetNode()->GetName().CString()); #endif constraint->SetIKConstraintNode(ikNode); } return ikNode; } // ---------------------------------------------------------------------------- void IKSolver::DestroyTree() { ik_solver_destroy_tree(solver_); effectorList_.Clear(); constraintList_.Clear(); } // ---------------------------------------------------------------------------- void IKSolver::RebuildTree() { assert (node_ != nullptr); // Destroy current tree and set a new root node DestroyTree(); ik_node_t* ikRoot = CreateIKNodeFromUrhoNode(node_); ik_solver_set_tree(solver_, ikRoot); /* * Collect all effectors and constraints from children, and filter them to * make sure they are in our subtree. */ node_->GetComponents<IKEffector>(effectorList_, true); node_->GetComponents<IKConstraint>(constraintList_, true); for (Vector<IKEffector*>::Iterator it = effectorList_.Begin(); it != effectorList_.End();) { if (ComponentIsInOurSubtree(*it)) { BuildTreeToEffector((*it)); ++it; } else { it = effectorList_.Erase(it); } } for (Vector<IKConstraint*>::Iterator it = constraintList_.Begin(); it != constraintList_.End();) { if (ComponentIsInOurSubtree(*it)) ++it; else it = constraintList_.Erase(it); } treeNeedsRebuild = false; MarkChainsNeedUpdating(); } // ---------------------------------------------------------------------------- bool IKSolver::BuildTreeToEffector(IKEffector* effector) { /* * NOTE: This function makes the assumption that the node the effector is * attached to is -- without a doubt -- in our subtree (by using * ComponentIsInOurSubtree() first). If this is not the case, the program * will abort. */ /* * we need to build tree up to the node where this effector was added. Do * this by following the chain of parent nodes until we hit a node that * exists in the solver's subtree. Then iterate backwards again and add each * missing node to the solver's tree. */ const Node* iterNode = effector->GetNode(); ik_node_t* ikNode; Vector<const Node*> missingNodes; while ((ikNode = ik_node_find_child(solver_->tree, iterNode->GetID())) == nullptr) { missingNodes.Push(iterNode); iterNode = iterNode->GetParent(); // Assert the assumptions made (described in the beginning of this function) assert(iterNode != nullptr); assert (iterNode->HasComponent<IKSolver>() == false || iterNode == node_); } while (missingNodes.Size() > 0) { iterNode = missingNodes.Back(); missingNodes.Pop(); ik_node_t* ikChildNode = CreateIKNodeFromUrhoNode(iterNode); ik_node_add_child(ikNode, ikChildNode); ikNode = ikChildNode; } return true; } // ---------------------------------------------------------------------------- bool IKSolver::ComponentIsInOurSubtree(Component* component) const { const Node* iterNode = component->GetNode(); while (true) { // Note part of our subtree if (iterNode == nullptr) return false; // Reached the root node, it's part of our subtree! if (iterNode == node_) return true; // Path to us is being blocked by another solver Component* otherSolver = iterNode->GetComponent<IKSolver>(); if (otherSolver != nullptr && otherSolver != component) return false; iterNode = iterNode->GetParent(); } return true; } // ---------------------------------------------------------------------------- void IKSolver::RebuildChainTrees() { solverTreeValid_ = (ik_solver_rebuild_chain_trees(solver_) == 0); ik_calculate_rotation_weight_decays(&solver_->chain_tree); chainTreesNeedUpdating_ = false; } // ---------------------------------------------------------------------------- void IKSolver::RecalculateSegmentLengths() { ik_solver_recalculate_segment_lengths(solver_); } // ---------------------------------------------------------------------------- void IKSolver::CalculateJointRotations() { ik_solver_calculate_joint_rotations(solver_); } // ---------------------------------------------------------------------------- void IKSolver::Solve() { URHO3D_PROFILE(IKSolve); if (treeNeedsRebuild) RebuildTree(); if (chainTreesNeedUpdating_) RebuildChainTrees(); if (IsSolverTreeValid() == false) return; if (features_ & UPDATE_ORIGINAL_POSE) ApplySceneToOriginalPose(); if (features_ & UPDATE_ACTIVE_POSE) ApplySceneToActivePose(); if (features_ & USE_ORIGINAL_POSE) ApplyOriginalPoseToActivePose(); for (Vector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it) { (*it)->UpdateTargetNodePosition(); } ik_solver_solve(solver_); if (features_ & JOINT_ROTATIONS) ik_solver_calculate_joint_rotations(solver_); ApplyActivePoseToScene(); } // ---------------------------------------------------------------------------- static void ApplyInitialPoseToSceneCallback(ik_node_t* ikNode) { auto* node = (Node*)ikNode->user_data; node->SetWorldRotation(QuatIK2Urho(&ikNode->original_rotation)); node->SetWorldPosition(Vec3IK2Urho(&ikNode->original_position)); } void IKSolver::ApplyOriginalPoseToScene() { ik_solver_iterate_tree(solver_, ApplyInitialPoseToSceneCallback); } // ---------------------------------------------------------------------------- static void ApplySceneToInitialPoseCallback(ik_node_t* ikNode) { auto* node = (Node*)ikNode->user_data; ikNode->original_rotation = QuatUrho2IK(node->GetWorldRotation()); ikNode->original_position = Vec3Urho2IK(node->GetWorldPosition()); } void IKSolver::ApplySceneToOriginalPose() { ik_solver_iterate_tree(solver_, ApplySceneToInitialPoseCallback); } // ---------------------------------------------------------------------------- static void ApplyActivePoseToSceneCallback(ik_node_t* ikNode) { auto* node = (Node*)ikNode->user_data; node->SetWorldRotation(QuatIK2Urho(&ikNode->rotation)); node->SetWorldPosition(Vec3IK2Urho(&ikNode->position)); } void IKSolver::ApplyActivePoseToScene() { ik_solver_iterate_tree(solver_, ApplyActivePoseToSceneCallback); } // ---------------------------------------------------------------------------- static void ApplySceneToActivePoseCallback(ik_node_t* ikNode) { auto* node = (Node*)ikNode->user_data; ikNode->rotation = QuatUrho2IK(node->GetWorldRotation()); ikNode->position = Vec3Urho2IK(node->GetWorldPosition()); } void IKSolver::ApplySceneToActivePose() { ik_solver_iterate_tree(solver_, ApplySceneToActivePoseCallback); } // ---------------------------------------------------------------------------- void IKSolver::ApplyOriginalPoseToActivePose() { ik_solver_reset_to_original_pose(solver_); } // ---------------------------------------------------------------------------- void IKSolver::MarkChainsNeedUpdating() { chainTreesNeedUpdating_ = true; } // ---------------------------------------------------------------------------- void IKSolver::MarkTreeNeedsRebuild() { treeNeedsRebuild = true; } // ---------------------------------------------------------------------------- bool IKSolver::IsSolverTreeValid() const { return solverTreeValid_; } // ---------------------------------------------------------------------------- /* * This next section maintains the internal list of effector nodes. Whenever * nodes are deleted or added to the scene, or whenever components are added * or removed from nodes, we must check to see which of those nodes are/were * IK effector nodes and update our internal list accordingly. * * Unfortunately, E_COMPONENTREMOVED and E_COMPONENTADDED do not fire when a * parent node is removed/added containing child effector nodes, so we must * also monitor E_NODEREMOVED AND E_NODEADDED. */ // ---------------------------------------------------------------------------- void IKSolver::OnSceneSet(Scene* scene) { if (features_ & AUTO_SOLVE) SubscribeToEvent(scene, E_SCENEDRAWABLEUPDATEFINISHED, URHO3D_HANDLER(IKSolver, HandleSceneDrawableUpdateFinished)); } // ---------------------------------------------------------------------------- void IKSolver::OnNodeSet(Node* node) { ApplyOriginalPoseToScene(); DestroyTree(); if (node != nullptr) RebuildTree(); } // ---------------------------------------------------------------------------- void IKSolver::HandleComponentAdded(StringHash eventType, VariantMap& eventData) { using namespace ComponentAdded; (void)eventType; auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr()); auto* component = static_cast<Component*>(eventData[P_COMPONENT].GetPtr()); /* * When a solver gets added into the scene, any parent solver's tree will * be invalidated. We need to find all parent solvers (by iterating up the * tree) and mark them as such. */ if (component->GetType() == IKSolver::GetTypeStatic()) { for (Node* iterNode = node; iterNode != nullptr; iterNode = iterNode->GetParent()) { auto* parentSolver = iterNode->GetComponent<IKSolver>(); if (parentSolver != nullptr) parentSolver->MarkTreeNeedsRebuild(); } return; // No need to continue processing effectors or constraints } if (solver_->tree == nullptr) return; /* * Update tree if component is an effector and is part of our subtree. */ if (component->GetType() == IKEffector::GetTypeStatic()) { // Not interested in components that won't be part of our if (ComponentIsInOurSubtree(component) == false) return; BuildTreeToEffector(static_cast<IKEffector*>(component)); effectorList_.Push(static_cast<IKEffector*>(component)); return; } if (component->GetType() == IKConstraint::GetTypeStatic()) { if (ComponentIsInOurSubtree(component) == false) return; constraintList_.Push(static_cast<IKConstraint*>(component)); } } // ---------------------------------------------------------------------------- void IKSolver::HandleComponentRemoved(StringHash eventType, VariantMap& eventData) { using namespace ComponentRemoved; if (solver_->tree == nullptr) return; auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr()); auto* component = static_cast<Component*>(eventData[P_COMPONENT].GetPtr()); /* * When a solver gets added into the scene, any parent solver's tree will * be invalidated. We need to find all parent solvers (by iterating up the * tree) and mark them as such. */ if (component->GetType() == IKSolver::GetTypeStatic()) { for (Node* iterNode = node; iterNode != nullptr; iterNode = iterNode->GetParent()) { auto* parentSolver = iterNode->GetComponent<IKSolver>(); if (parentSolver != nullptr) parentSolver->MarkTreeNeedsRebuild(); } return; // No need to continue processing effectors or constraints } // If an effector was removed, the tree will have to be rebuilt. if (component->GetType() == IKEffector::GetTypeStatic()) { if (ComponentIsInOurSubtree(component) == false) return; ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID()); assert(ikNode != nullptr); ik_node_destroy_effector(ikNode); static_cast<IKEffector*>(component)->SetIKEffectorNode(nullptr); effectorList_.RemoveSwap(static_cast<IKEffector*>(component)); ApplyOriginalPoseToScene(); MarkTreeNeedsRebuild(); return; } // Remove the ikNode* reference the IKConstraint was holding if (component->GetType() == IKConstraint::GetTypeStatic()) { if (ComponentIsInOurSubtree(component) == false) return; ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID()); assert(ikNode != nullptr); static_cast<IKConstraint*>(component)->SetIKConstraintNode(nullptr); constraintList_.RemoveSwap(static_cast<IKConstraint*>(component)); } } // ---------------------------------------------------------------------------- void IKSolver::HandleNodeAdded(StringHash eventType, VariantMap& eventData) { using namespace NodeAdded; if (solver_->tree == nullptr) return; auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr()); Vector<IKEffector*> effectors; node->GetComponents<IKEffector>(effectors, true); for (Vector<IKEffector*>::ConstIterator it = effectors.Begin(); it != effectors.End(); ++it) { if (ComponentIsInOurSubtree(*it) == false) continue; BuildTreeToEffector(*it); effectorList_.Push(*it); } Vector<IKConstraint*> constraints; node->GetComponents<IKConstraint>(constraints, true); for (Vector<IKConstraint*>::ConstIterator it = constraints.Begin(); it != constraints.End(); ++it) { if (ComponentIsInOurSubtree(*it) == false) continue; constraintList_.Push(*it); } } // ---------------------------------------------------------------------------- void IKSolver::HandleNodeRemoved(StringHash eventType, VariantMap& eventData) { using namespace NodeRemoved; if (solver_->tree == nullptr) return; auto* node = static_cast<Node*>(eventData[P_NODE].GetPtr()); // Remove cached IKEffectors from our list Vector<IKEffector*> effectors; node->GetComponents<IKEffector>(effectors, true); for (Vector<IKEffector*>::ConstIterator it = effectors.Begin(); it != effectors.End(); ++it) { (*it)->SetIKEffectorNode(nullptr); effectorList_.RemoveSwap(*it); } Vector<IKConstraint*> constraints; node->GetComponents<IKConstraint>(constraints, true); for (Vector<IKConstraint*>::ConstIterator it = constraints.Begin(); it != constraints.End(); ++it) { constraintList_.RemoveSwap(*it); } // Special case, if the node being destroyed is the root node, destroy the // solver's tree instead of destroying the single node. Calling // ik_node_destroy() on the solver's root node will cause segfaults. ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID()); if (ikNode != nullptr) { if (ikNode == solver_->tree) ik_solver_destroy_tree(solver_); else ik_node_destroy(ikNode); MarkChainsNeedUpdating(); } } // ---------------------------------------------------------------------------- void IKSolver::HandleSceneDrawableUpdateFinished(StringHash eventType, VariantMap& eventData) { Solve(); } // ---------------------------------------------------------------------------- void IKSolver::DrawDebugGeometry(bool depthTest) { auto* debug = GetScene()->GetComponent<DebugRenderer>(); if (debug) DrawDebugGeometry(debug, depthTest); } // ---------------------------------------------------------------------------- void IKSolver::DrawDebugGeometry(DebugRenderer* debug, bool depthTest) { // Draws all scene segments for (Vector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it) (*it)->DrawDebugGeometry(debug, depthTest); ORDERED_VECTOR_FOR_EACH(&solver_->effector_nodes_list, ik_node_t*, pnode) ik_effector_t* effector = (*pnode)->effector; // Calculate average length of all segments so we can determine the radius // of the debug spheres to draw int chainLength = effector->chain_length == 0 ? -1 : effector->chain_length; ik_node_t* a = *pnode; ik_node_t* b = a->parent; float averageLength = 0.0f; unsigned numberOfSegments = 0; while (b && chainLength-- != 0) { vec3_t v = a->original_position; vec3_sub_vec3(v.f, b->original_position.f); averageLength += vec3_length(v.f); ++numberOfSegments; a = b; b = b->parent; } averageLength /= numberOfSegments; // connect all chained nodes together with lines chainLength = effector->chain_length == 0 ? -1 : effector->chain_length; a = *pnode; b = a->parent; debug->AddSphere( Sphere(Vec3IK2Urho(&a->original_position), averageLength * 0.1f), Color(0, 0, 255), depthTest ); debug->AddSphere( Sphere(Vec3IK2Urho(&a->position), averageLength * 0.1f), Color(255, 128, 0), depthTest ); while (b && chainLength-- != 0) { debug->AddLine( Vec3IK2Urho(&a->original_position), Vec3IK2Urho(&b->original_position), Color(0, 255, 255), depthTest ); debug->AddSphere( Sphere(Vec3IK2Urho(&b->original_position), averageLength * 0.1f), Color(0, 0, 255), depthTest ); debug->AddLine( Vec3IK2Urho(&a->position), Vec3IK2Urho(&b->position), Color(255, 0, 0), depthTest ); debug->AddSphere( Sphere(Vec3IK2Urho(&b->position), averageLength * 0.1f), Color(255, 128, 0), depthTest ); a = b; b = b->parent; } ORDERED_VECTOR_END_EACH } // ---------------------------------------------------------------------------- // Need these wrapper functions flags of GetFeature/SetFeature can be correctly // exposed to the editor // ---------------------------------------------------------------------------- #define DEF_FEATURE_GETTER(feature_name) \ bool IKSolver::Get##feature_name() const \ { \ return GetFeature(feature_name); \ } #define DEF_FEATURE_SETTER(feature_name) \ void IKSolver::Set##feature_name(bool enable) \ { \ SetFeature(feature_name, enable); \ } DEF_FEATURE_GETTER(JOINT_ROTATIONS) DEF_FEATURE_GETTER(TARGET_ROTATIONS) DEF_FEATURE_GETTER(UPDATE_ORIGINAL_POSE) DEF_FEATURE_GETTER(UPDATE_ACTIVE_POSE) DEF_FEATURE_GETTER(USE_ORIGINAL_POSE) DEF_FEATURE_GETTER(CONSTRAINTS) DEF_FEATURE_GETTER(AUTO_SOLVE) DEF_FEATURE_SETTER(JOINT_ROTATIONS) DEF_FEATURE_SETTER(TARGET_ROTATIONS) DEF_FEATURE_SETTER(UPDATE_ORIGINAL_POSE) DEF_FEATURE_SETTER(UPDATE_ACTIVE_POSE) DEF_FEATURE_SETTER(USE_ORIGINAL_POSE) DEF_FEATURE_SETTER(CONSTRAINTS) DEF_FEATURE_SETTER(AUTO_SOLVE) } // namespace Urho3D
27,365
8,454
/* ---------------------------------------------------------------------------- * GTSAM Copyright 2010, Georgia Tech Research Corporation, * Atlanta, Georgia 30332-0415 * All Rights Reserved * Authors: Frank Dellaert, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file Pose2SLAMwSPCG.cpp * @brief A 2D Pose SLAM example using the SimpleSPCGSolver. * @author Yong-Dian Jian * @date June 2, 2012 */ // For an explanation of headers below, please see Pose2SLAMExample.cpp #include <gtsam/slam/BetweenFactor.h> #include <gtsam/geometry/Pose2.h> #include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h> // In contrast to that example, however, we will use a PCG solver here #include <gtsam/linear/SubgraphSolver.h> using namespace std; using namespace gtsam; int main(int argc, char** argv) { // 1. Create a factor graph container and add factors to it NonlinearFactorGraph graph; // 2a. Add a prior on the first pose, setting it to the origin Pose2 prior(0.0, 0.0, 0.0); // prior at origin auto priorNoise = noiseModel::Diagonal::Sigmas(Vector3(0.3, 0.3, 0.1)); graph.addPrior(1, prior, priorNoise); // 2b. Add odometry factors auto odometryNoise = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.1)); graph.emplace_shared<BetweenFactor<Pose2> >(1, 2, Pose2(2.0, 0.0, M_PI_2), odometryNoise); graph.emplace_shared<BetweenFactor<Pose2> >(2, 3, Pose2(2.0, 0.0, M_PI_2), odometryNoise); graph.emplace_shared<BetweenFactor<Pose2> >(3, 4, Pose2(2.0, 0.0, M_PI_2), odometryNoise); graph.emplace_shared<BetweenFactor<Pose2> >(4, 5, Pose2(2.0, 0.0, M_PI_2), odometryNoise); // 2c. Add the loop closure constraint auto model = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.1)); graph.emplace_shared<BetweenFactor<Pose2> >(5, 1, Pose2(0.0, 0.0, 0.0), model); graph.print("\nFactor Graph:\n"); // print // 3. Create the data structure to hold the initialEstimate estimate to the // solution Values initialEstimate; initialEstimate.insert(1, Pose2(0.5, 0.0, 0.2)); initialEstimate.insert(2, Pose2(2.3, 0.1, 1.1)); initialEstimate.insert(3, Pose2(2.1, 1.9, 2.8)); initialEstimate.insert(4, Pose2(-.3, 2.5, 4.2)); initialEstimate.insert(5, Pose2(0.1, -0.7, 5.8)); initialEstimate.print("\nInitial Estimate:\n"); // print // 4. Single Step Optimization using Levenberg-Marquardt LevenbergMarquardtParams parameters; parameters.verbosity = NonlinearOptimizerParams::ERROR; parameters.verbosityLM = LevenbergMarquardtParams::LAMBDA; // LM is still the outer optimization loop, but by specifying "Iterative" // below We indicate that an iterative linear solver should be used. In // addition, the *type* of the iterativeParams decides on the type of // iterative solver, in this case the SPCG (subgraph PCG) parameters.linearSolverType = NonlinearOptimizerParams::Iterative; parameters.iterativeParams = boost::make_shared<SubgraphSolverParameters>(); LevenbergMarquardtOptimizer optimizer(graph, initialEstimate, parameters); Values result = optimizer.optimize(); result.print("Final Result:\n"); cout << "subgraph solver final error = " << graph.error(result) << endl; return 0; }
3,349
1,253
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <sstream> #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/range/range.h" #include "ui/gfx/range/range_f.h" namespace { template <typename T> class RangeTest : public testing::Test {}; typedef testing::Types<gfx::Range, gfx::RangeF> RangeTypes; TYPED_TEST_SUITE(RangeTest, RangeTypes); template <typename T> void TestContainsAndIntersects(const T& r1, const T& r2, const T& r3) { EXPECT_TRUE(r1.Intersects(r1)); EXPECT_TRUE(r1.Contains(r1)); EXPECT_EQ(T(10, 12), r1.Intersect(r1)); EXPECT_FALSE(r1.Intersects(r2)); EXPECT_FALSE(r1.Contains(r2)); EXPECT_TRUE(r1.Intersect(r2).is_empty()); EXPECT_FALSE(r2.Intersects(r1)); EXPECT_FALSE(r2.Contains(r1)); EXPECT_TRUE(r2.Intersect(r1).is_empty()); EXPECT_TRUE(r1.Intersects(r3)); EXPECT_TRUE(r3.Intersects(r1)); EXPECT_TRUE(r3.Contains(r1)); EXPECT_FALSE(r1.Contains(r3)); EXPECT_EQ(T(10, 12), r1.Intersect(r3)); EXPECT_EQ(T(10, 12), r3.Intersect(r1)); EXPECT_TRUE(r2.Intersects(r3)); EXPECT_TRUE(r3.Intersects(r2)); EXPECT_FALSE(r3.Contains(r2)); EXPECT_FALSE(r2.Contains(r3)); EXPECT_EQ(T(5, 8), r2.Intersect(r3)); EXPECT_EQ(T(5, 8), r3.Intersect(r2)); } } // namespace TYPED_TEST(RangeTest, EmptyInit) { TypeParam r; EXPECT_EQ(0U, r.start()); EXPECT_EQ(0U, r.end()); EXPECT_EQ(0U, r.length()); EXPECT_FALSE(r.is_reversed()); EXPECT_TRUE(r.is_empty()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(0U, r.GetMin()); EXPECT_EQ(0U, r.GetMax()); } TYPED_TEST(RangeTest, StartEndInit) { TypeParam r(10, 15); EXPECT_EQ(10U, r.start()); EXPECT_EQ(15U, r.end()); EXPECT_EQ(5U, r.length()); EXPECT_FALSE(r.is_reversed()); EXPECT_FALSE(r.is_empty()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(10U, r.GetMin()); EXPECT_EQ(15U, r.GetMax()); } TYPED_TEST(RangeTest, StartEndReversedInit) { TypeParam r(10, 5); EXPECT_EQ(10U, r.start()); EXPECT_EQ(5U, r.end()); EXPECT_EQ(5U, r.length()); EXPECT_TRUE(r.is_reversed()); EXPECT_FALSE(r.is_empty()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(5U, r.GetMin()); EXPECT_EQ(10U, r.GetMax()); } TYPED_TEST(RangeTest, PositionInit) { TypeParam r(12); EXPECT_EQ(12U, r.start()); EXPECT_EQ(12U, r.end()); EXPECT_EQ(0U, r.length()); EXPECT_FALSE(r.is_reversed()); EXPECT_TRUE(r.is_empty()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(12U, r.GetMin()); EXPECT_EQ(12U, r.GetMax()); } TYPED_TEST(RangeTest, InvalidRange) { TypeParam r(TypeParam::InvalidRange()); EXPECT_EQ(0U, r.length()); EXPECT_EQ(r.start(), r.end()); EXPECT_EQ(r.GetMax(), r.GetMin()); EXPECT_FALSE(r.is_reversed()); EXPECT_TRUE(r.is_empty()); EXPECT_FALSE(r.IsValid()); EXPECT_EQ(r, TypeParam::InvalidRange()); EXPECT_TRUE(r.EqualsIgnoringDirection(TypeParam::InvalidRange())); } TYPED_TEST(RangeTest, Equality) { TypeParam r1(10, 4); TypeParam r2(10, 4); TypeParam r3(10, 2); EXPECT_EQ(r1, r2); EXPECT_NE(r1, r3); EXPECT_NE(r2, r3); TypeParam r4(11, 4); EXPECT_NE(r1, r4); EXPECT_NE(r2, r4); EXPECT_NE(r3, r4); TypeParam r5(12, 5); EXPECT_NE(r1, r5); EXPECT_NE(r2, r5); EXPECT_NE(r3, r5); } TYPED_TEST(RangeTest, EqualsIgnoringDirection) { TypeParam r1(10, 5); TypeParam r2(5, 10); EXPECT_TRUE(r1.EqualsIgnoringDirection(r2)); } TYPED_TEST(RangeTest, SetStart) { TypeParam r(10, 20); EXPECT_EQ(10U, r.start()); EXPECT_EQ(10U, r.length()); r.set_start(42); EXPECT_EQ(42U, r.start()); EXPECT_EQ(20U, r.end()); EXPECT_EQ(22U, r.length()); EXPECT_TRUE(r.is_reversed()); } TYPED_TEST(RangeTest, SetEnd) { TypeParam r(10, 13); EXPECT_EQ(10U, r.start()); EXPECT_EQ(3U, r.length()); r.set_end(20); EXPECT_EQ(10U, r.start()); EXPECT_EQ(20U, r.end()); EXPECT_EQ(10U, r.length()); } TYPED_TEST(RangeTest, SetStartAndEnd) { TypeParam r; r.set_end(5); r.set_start(1); EXPECT_EQ(1U, r.start()); EXPECT_EQ(5U, r.end()); EXPECT_EQ(4U, r.length()); EXPECT_EQ(1U, r.GetMin()); EXPECT_EQ(5U, r.GetMax()); } TYPED_TEST(RangeTest, ReversedRange) { TypeParam r(10, 5); EXPECT_EQ(10U, r.start()); EXPECT_EQ(5U, r.end()); EXPECT_EQ(5U, r.length()); EXPECT_TRUE(r.is_reversed()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(5U, r.GetMin()); EXPECT_EQ(10U, r.GetMax()); } TYPED_TEST(RangeTest, SetReversedRange) { TypeParam r(10, 20); r.set_start(25); EXPECT_EQ(25U, r.start()); EXPECT_EQ(20U, r.end()); EXPECT_EQ(5U, r.length()); EXPECT_TRUE(r.is_reversed()); EXPECT_TRUE(r.IsValid()); r.set_end(21); EXPECT_EQ(25U, r.start()); EXPECT_EQ(21U, r.end()); EXPECT_EQ(4U, r.length()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(21U, r.GetMin()); EXPECT_EQ(25U, r.GetMax()); } TYPED_TEST(RangeTest, ContainAndIntersect) { { SCOPED_TRACE("contain and intersect"); TypeParam r1(10, 12); TypeParam r2(1, 8); TypeParam r3(5, 12); TestContainsAndIntersects(r1, r2, r3); } { SCOPED_TRACE("contain and intersect: reversed"); TypeParam r1(12, 10); TypeParam r2(8, 1); TypeParam r3(12, 5); TestContainsAndIntersects(r1, r2, r3); } // Invalid rect tests TypeParam r1(10, 12); TypeParam r2(8, 1); TypeParam invalid = r1.Intersect(r2); EXPECT_FALSE(invalid.IsValid()); EXPECT_FALSE(invalid.Contains(invalid)); EXPECT_FALSE(invalid.Contains(r1)); EXPECT_FALSE(invalid.Intersects(invalid)); EXPECT_FALSE(invalid.Intersects(r1)); EXPECT_FALSE(r1.Contains(invalid)); EXPECT_FALSE(r1.Intersects(invalid)); } TEST(RangeTest, RangeOperations) { constexpr gfx::Range invalid_range = gfx::Range::InvalidRange(); constexpr gfx::Range ranges[] = {{0, 0}, {0, 1}, {0, 2}, {1, 0}, {1, 1}, {1, 2}, {2, 0}, {2, 1}, {2, 2}}; // Ensures valid behavior over same range. for (const auto& range : ranges) { SCOPED_TRACE(range.ToString()); // A range should contain itself. EXPECT_TRUE(range.Contains(range)); // A ranges should intersect with itself. EXPECT_TRUE(range.Intersects(range)); } // Ensures valid behavior with an invalid range. for (const auto& range : ranges) { SCOPED_TRACE(range.ToString()); EXPECT_FALSE(invalid_range.Contains(range)); EXPECT_FALSE(invalid_range.Intersects(range)); EXPECT_FALSE(range.Contains(invalid_range)); EXPECT_FALSE(range.Intersects(invalid_range)); } EXPECT_FALSE(invalid_range.Contains(invalid_range)); EXPECT_FALSE(invalid_range.Intersects(invalid_range)); // Ensures consistent operations between Contains(...) and Intersects(...). for (const auto& range1 : ranges) { for (const auto& range2 : ranges) { SCOPED_TRACE(testing::Message() << "range1=" << range1 << " range2=" << range2); if (range1.Contains(range2)) { EXPECT_TRUE(range1.Intersects(range2)); EXPECT_EQ(range2.Contains(range1), range1.EqualsIgnoringDirection(range2)); } EXPECT_EQ(range2.Intersects(range1), range1.Intersects(range2)); EXPECT_EQ(range1.Intersect(range2) != invalid_range, range1.Intersects(range2)); } } // Ranges should behave the same way no matter the direction. for (const auto& range1 : ranges) { for (const auto& range2 : ranges) { SCOPED_TRACE(testing::Message() << "range1=" << range1 << " range2=" << range2); EXPECT_EQ(range1.Contains(range2), range1.Contains(gfx::Range(range2.GetMax(), range2.GetMin()))); EXPECT_EQ( range1.Intersects(range2), range1.Intersects(gfx::Range(range2.GetMax(), range2.GetMin()))); } } } TEST(RangeTest, RangeFOperations) { constexpr gfx::RangeF invalid_range = gfx::RangeF::InvalidRange(); constexpr gfx::RangeF ranges[] = {{0.f, 0.f}, {0.f, 1.f}, {0.f, 2.f}, {1.f, 0.f}, {1.f, 1.f}, {1.f, 2.f}, {2.f, 0.f}, {2.f, 1.f}, {2.f, 2.f}}; // Ensures valid behavior over same range. for (const auto& range : ranges) { SCOPED_TRACE(range.ToString()); // A range should contain itself. EXPECT_TRUE(range.Contains(range)); // A ranges should intersect with itself. EXPECT_TRUE(range.Intersects(range)); } // Ensures valid behavior with an invalid range. for (const auto& range : ranges) { SCOPED_TRACE(range.ToString()); EXPECT_FALSE(invalid_range.Contains(range)); EXPECT_FALSE(invalid_range.Intersects(range)); EXPECT_FALSE(range.Contains(invalid_range)); EXPECT_FALSE(range.Intersects(invalid_range)); } EXPECT_FALSE(invalid_range.Contains(invalid_range)); EXPECT_FALSE(invalid_range.Intersects(invalid_range)); // Ensures consistent operations between Contains(...) and Intersects(...). for (const auto& range1 : ranges) { for (const auto& range2 : ranges) { SCOPED_TRACE(testing::Message() << "range1=" << range1 << " range2=" << range2); if (range1.Contains(range2)) { EXPECT_TRUE(range1.Intersects(range2)); EXPECT_EQ(range2.Contains(range1), range1.EqualsIgnoringDirection(range2)); } EXPECT_EQ(range2.Intersects(range1), range1.Intersects(range2)); EXPECT_EQ(range1.Intersect(range2) != invalid_range, range1.Intersects(range2)); } } // Ranges should behave the same way no matter the direction. for (const auto& range1 : ranges) { for (const auto& range2 : ranges) { SCOPED_TRACE(testing::Message() << "range1=" << range1 << " range2=" << range2); EXPECT_EQ(range1.Contains(range2), range1.Contains(gfx::RangeF(range2.GetMax(), range2.GetMin()))); EXPECT_EQ( range1.Intersects(range2), range1.Intersects(gfx::RangeF(range2.GetMax(), range2.GetMin()))); } } } TEST(RangeTest, ContainsAndIntersects) { constexpr gfx::Range r1(0, 0); constexpr gfx::Range r2(0, 1); constexpr gfx::Range r3(1, 2); constexpr gfx::Range r4(1, 0); constexpr gfx::Range r5(2, 1); constexpr gfx::Range r6(0, 2); constexpr gfx::Range r7(2, 0); constexpr gfx::Range r8(1, 1); // Ensures Contains(...) handle the open range. EXPECT_TRUE(r2.Contains(r1)); EXPECT_TRUE(r4.Contains(r1)); EXPECT_TRUE(r3.Contains(r5)); EXPECT_TRUE(r5.Contains(r3)); // Ensures larger ranges contains smaller ranges. EXPECT_TRUE(r6.Contains(r1)); EXPECT_TRUE(r6.Contains(r2)); EXPECT_TRUE(r6.Contains(r3)); EXPECT_TRUE(r6.Contains(r4)); EXPECT_TRUE(r6.Contains(r5)); EXPECT_TRUE(r7.Contains(r1)); EXPECT_TRUE(r7.Contains(r2)); EXPECT_TRUE(r7.Contains(r3)); EXPECT_TRUE(r7.Contains(r4)); EXPECT_TRUE(r7.Contains(r5)); // Ensures Intersects(...) handle the open range. EXPECT_TRUE(r2.Intersects(r1)); EXPECT_TRUE(r4.Intersects(r1)); // Ensures larger ranges intersects smaller ranges. EXPECT_TRUE(r6.Intersects(r1)); EXPECT_TRUE(r6.Intersects(r2)); EXPECT_TRUE(r6.Intersects(r3)); EXPECT_TRUE(r6.Intersects(r4)); EXPECT_TRUE(r6.Intersects(r5)); EXPECT_TRUE(r7.Intersects(r1)); EXPECT_TRUE(r7.Intersects(r2)); EXPECT_TRUE(r7.Intersects(r3)); EXPECT_TRUE(r7.Intersects(r4)); EXPECT_TRUE(r7.Intersects(r5)); // Ensures adjacent ranges don't overlap. EXPECT_FALSE(r2.Intersects(r3)); EXPECT_FALSE(r5.Intersects(r4)); // Ensures empty ranges are handled correctly. EXPECT_FALSE(r1.Contains(r8)); EXPECT_FALSE(r2.Contains(r8)); EXPECT_TRUE(r3.Contains(r8)); EXPECT_TRUE(r8.Contains(r8)); EXPECT_FALSE(r1.Intersects(r8)); EXPECT_FALSE(r2.Intersects(r8)); EXPECT_TRUE(r3.Intersects(r8)); EXPECT_TRUE(r8.Intersects(r8)); } TEST(RangeTest, ContainsAndIntersectsRangeF) { constexpr gfx::RangeF r1(0.f, 0.f); constexpr gfx::RangeF r2(0.f, 1.f); constexpr gfx::RangeF r3(1.f, 2.f); constexpr gfx::RangeF r4(1.f, 0.f); constexpr gfx::RangeF r5(2.f, 1.f); constexpr gfx::RangeF r6(0.f, 2.f); constexpr gfx::RangeF r7(2.f, 0.f); constexpr gfx::RangeF r8(1.f, 1.f); // Ensures Contains(...) handle the open range. EXPECT_TRUE(r2.Contains(r1)); EXPECT_TRUE(r4.Contains(r1)); EXPECT_TRUE(r3.Contains(r5)); EXPECT_TRUE(r5.Contains(r3)); // Ensures larger ranges contains smaller ranges. EXPECT_TRUE(r6.Contains(r1)); EXPECT_TRUE(r6.Contains(r2)); EXPECT_TRUE(r6.Contains(r3)); EXPECT_TRUE(r6.Contains(r4)); EXPECT_TRUE(r6.Contains(r5)); EXPECT_TRUE(r7.Contains(r1)); EXPECT_TRUE(r7.Contains(r2)); EXPECT_TRUE(r7.Contains(r3)); EXPECT_TRUE(r7.Contains(r4)); EXPECT_TRUE(r7.Contains(r5)); // Ensures Intersects(...) handle the open range. EXPECT_TRUE(r2.Intersects(r1)); EXPECT_TRUE(r4.Intersects(r1)); // Ensures larger ranges intersects smaller ranges. EXPECT_TRUE(r6.Intersects(r1)); EXPECT_TRUE(r6.Intersects(r2)); EXPECT_TRUE(r6.Intersects(r3)); EXPECT_TRUE(r6.Intersects(r4)); EXPECT_TRUE(r6.Intersects(r5)); EXPECT_TRUE(r7.Intersects(r1)); EXPECT_TRUE(r7.Intersects(r2)); EXPECT_TRUE(r7.Intersects(r3)); EXPECT_TRUE(r7.Intersects(r4)); EXPECT_TRUE(r7.Intersects(r5)); // Ensures adjacent ranges don't overlap. EXPECT_FALSE(r2.Intersects(r3)); EXPECT_FALSE(r5.Intersects(r4)); // Ensures empty ranges are handled correctly. EXPECT_FALSE(r1.Contains(r8)); EXPECT_FALSE(r2.Contains(r8)); EXPECT_TRUE(r3.Contains(r8)); EXPECT_TRUE(r8.Contains(r8)); EXPECT_FALSE(r1.Intersects(r8)); EXPECT_FALSE(r2.Intersects(r8)); EXPECT_TRUE(r3.Intersects(r8)); EXPECT_TRUE(r8.Intersects(r8)); } TEST(RangeTest, Intersect) { EXPECT_EQ(gfx::Range(0, 1).Intersect({0, 1}), gfx::Range(0, 1)); EXPECT_EQ(gfx::Range(0, 1).Intersect({0, 0}), gfx::Range(0, 0)); EXPECT_EQ(gfx::Range(0, 0).Intersect({1, 0}), gfx::Range(0, 0)); EXPECT_EQ(gfx::Range(0, 4).Intersect({2, 3}), gfx::Range(2, 3)); EXPECT_EQ(gfx::Range(0, 4).Intersect({2, 7}), gfx::Range(2, 4)); EXPECT_EQ(gfx::Range(0, 4).Intersect({3, 4}), gfx::Range(3, 4)); EXPECT_EQ(gfx::Range(0, 1).Intersect({1, 1}), gfx::Range::InvalidRange()); EXPECT_EQ(gfx::Range(1, 1).Intersect({1, 0}), gfx::Range::InvalidRange()); EXPECT_EQ(gfx::Range(0, 1).Intersect({1, 2}), gfx::Range::InvalidRange()); EXPECT_EQ(gfx::Range(0, 1).Intersect({2, 1}), gfx::Range::InvalidRange()); EXPECT_EQ(gfx::Range(2, 1).Intersect({1, 0}), gfx::Range::InvalidRange()); } TEST(RangeTest, IntersectRangeF) { EXPECT_EQ(gfx::RangeF(0.f, 1.f).Intersect(gfx::RangeF(0.f, 1.f)), gfx::RangeF(0.f, 1.f)); EXPECT_EQ(gfx::RangeF(0.f, 1.f).Intersect(gfx::RangeF(0.f, 0.f)), gfx::RangeF(0.f, 0.f)); EXPECT_EQ(gfx::RangeF(0.f, 0.f).Intersect(gfx::RangeF(1.f, 0.f)), gfx::RangeF(0.f, 0.f)); EXPECT_EQ(gfx::RangeF(0.f, 4.f).Intersect(gfx::RangeF(2.f, 3.f)), gfx::RangeF(2.f, 3.f)); EXPECT_EQ(gfx::RangeF(0.f, 4.f).Intersect(gfx::RangeF(2.f, 7.f)), gfx::RangeF(2.f, 4.f)); EXPECT_EQ(gfx::RangeF(0.f, 4.f).Intersect(gfx::RangeF(3.f, 4.f)), gfx::RangeF(3.f, 4.f)); EXPECT_EQ(gfx::RangeF(0.f, 1.f).Intersect(gfx::RangeF(1.f, 1.f)), gfx::RangeF::InvalidRange()); EXPECT_EQ(gfx::RangeF(1.f, 1.f).Intersect(gfx::RangeF(1.f, 0.f)), gfx::RangeF::InvalidRange()); EXPECT_EQ(gfx::RangeF(0.f, 1.f).Intersect(gfx::RangeF(1.f, 2.f)), gfx::RangeF::InvalidRange()); EXPECT_EQ(gfx::RangeF(0.f, 1.f).Intersect(gfx::RangeF(2.f, 1.f)), gfx::RangeF::InvalidRange()); EXPECT_EQ(gfx::RangeF(2.f, 1.f).Intersect(gfx::RangeF(1.f, 0.f)), gfx::RangeF::InvalidRange()); } TEST(RangeTest, IsBoundedBy) { constexpr gfx::Range r1(0, 0); constexpr gfx::Range r2(0, 1); EXPECT_TRUE(r1.IsBoundedBy(r1)); EXPECT_FALSE(r2.IsBoundedBy(r1)); constexpr gfx::Range r3(0, 2); constexpr gfx::Range r4(2, 2); EXPECT_TRUE(r4.IsBoundedBy(r3)); EXPECT_FALSE(r3.IsBoundedBy(r4)); } TEST(RangeTest, ToString) { gfx::Range range(4, 7); EXPECT_EQ("{4,7}", range.ToString()); range = gfx::Range::InvalidRange(); std::ostringstream expected; expected << "{" << range.start() << "," << range.end() << "}"; EXPECT_EQ(expected.str(), range.ToString()); }
16,237
7,238
// Copyright (c) 2012 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/instant/instant_controller.h" #include "base/command_line.h" #include "base/i18n/case_conversion.h" #include "base/metrics/histogram.h" #include "base/string_util.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autocomplete/autocomplete_provider.h" #include "chrome/browser/google/google_util.h" #include "chrome/browser/history/history.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/history/history_tab_helper.h" #include "chrome/browser/instant/instant_loader.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/search_engines/template_url_service.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/ui/browser_instant_controller.h" #include "chrome/browser/ui/search/search.h" #include "chrome/browser/ui/search/search_tab_helper.h" #include "chrome/browser/ui/tab_contents/tab_contents.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "net/base/escape.h" #include "unicode/normalizer2.h" #include "unicode/unistr.h" #if defined(TOOLKIT_VIEWS) #include "ui/views/widget/widget.h" #endif namespace { enum PreviewUsageType { PREVIEW_CREATED = 0, PREVIEW_DELETED, PREVIEW_LOADED, PREVIEW_SHOWED, PREVIEW_COMMITTED, PREVIEW_NUM_TYPES, }; // An artificial delay (in milliseconds) we introduce before telling the Instant // page about the new omnibox bounds, in cases where the bounds shrink. This is // to avoid the page jumping up/down very fast in response to bounds changes. const int kUpdateBoundsDelayMS = 1000; // The maximum number of times we'll load a non-Instant-supporting search engine // before we give up and blacklist it for the rest of the browsing session. const int kMaxInstantSupportFailures = 10; // If an Instant page has not been used in these many milliseconds, it is // reloaded so that the page does not become stale. const int kStaleLoaderTimeoutMS = 3 * 3600 * 1000; std::string ModeToString(InstantController::Mode mode) { switch (mode) { case InstantController::EXTENDED: return "_Extended"; case InstantController::INSTANT: return "_Instant"; case InstantController::DISABLED: return "_Disabled"; } NOTREACHED(); return std::string(); } void AddPreviewUsageForHistogram(InstantController::Mode mode, PreviewUsageType usage) { DCHECK(0 <= usage && usage < PREVIEW_NUM_TYPES) << usage; base::Histogram* histogram = base::LinearHistogram::FactoryGet( "Instant.Previews" + ModeToString(mode), 1, PREVIEW_NUM_TYPES, PREVIEW_NUM_TYPES + 1, base::Histogram::kUmaTargetedHistogramFlag); histogram->Add(usage); } void AddSessionStorageHistogram(InstantController::Mode mode, const TabContents* tab1, const TabContents* tab2) { base::Histogram* histogram = base::BooleanHistogram::FactoryGet( "Instant.SessionStorageNamespace" + ModeToString(mode), base::Histogram::kUmaTargetedHistogramFlag); const content::SessionStorageNamespaceMap& session_storage_map1 = tab1->web_contents()->GetController().GetSessionStorageNamespaceMap(); const content::SessionStorageNamespaceMap& session_storage_map2 = tab2->web_contents()->GetController().GetSessionStorageNamespaceMap(); bool is_session_storage_the_same = session_storage_map1.size() == session_storage_map2.size(); if (is_session_storage_the_same) { // The size is the same, so let's check that all entries match. for (content::SessionStorageNamespaceMap::const_iterator it1 = session_storage_map1.begin(), it2 = session_storage_map2.begin(); it1 != session_storage_map1.end() && it2 != session_storage_map2.end(); ++it1, ++it2) { if (it1->first != it2->first || it1->second != it2->second) { is_session_storage_the_same = false; break; } } } histogram->AddBoolean(is_session_storage_the_same); } InstantController::Mode GetModeForProfile(Profile* profile) { if (chrome::search::IsInstantExtendedAPIEnabled(profile)) return InstantController::EXTENDED; if (!profile || profile->IsOffTheRecord() || !profile->GetPrefs() || !profile->GetPrefs()->GetBoolean(prefs::kInstantEnabled)) return InstantController::DISABLED; return InstantController::INSTANT; } string16 Normalize(const string16& str) { UErrorCode status = U_ZERO_ERROR; const icu::Normalizer2* normalizer = icu::Normalizer2::getInstance(NULL, "nfkc_cf", UNORM2_COMPOSE, status); if (normalizer == NULL || U_FAILURE(status)) return str; icu::UnicodeString norm_str(normalizer->normalize( icu::UnicodeString(FALSE, str.c_str(), str.size()), status)); if (U_FAILURE(status)) return str; return string16(norm_str.getBuffer(), norm_str.length()); } bool NormalizeAndStripPrefix(string16* text, const string16& prefix) { const string16 norm_prefix = Normalize(prefix); string16 norm_text = Normalize(*text); if (norm_prefix.size() <= norm_text.size() && norm_text.compare(0, norm_prefix.size(), norm_prefix) == 0) { *text = norm_text.erase(0, norm_prefix.size()); return true; } return false; } } // namespace InstantController::~InstantController() { if (GetPreviewContents()) AddPreviewUsageForHistogram(mode_, PREVIEW_DELETED); } // static InstantController* InstantController::CreateInstant( Profile* profile, chrome::BrowserInstantController* browser) { const Mode mode = GetModeForProfile(profile); return mode == DISABLED ? NULL : new InstantController(browser, mode); } // static bool InstantController::IsExtendedAPIEnabled(Profile* profile) { return GetModeForProfile(profile) == EXTENDED; } // static bool InstantController::IsInstantEnabled(Profile* profile) { const Mode mode = GetModeForProfile(profile); return mode == EXTENDED || mode == INSTANT; } // static void InstantController::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kInstantConfirmDialogShown, false, PrefService::SYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kInstantEnabled, false, PrefService::SYNCABLE_PREF); } bool InstantController::Update(const AutocompleteMatch& match, const string16& user_text, const string16& full_text, bool verbatim) { const TabContents* active_tab = browser_->GetActiveTabContents(); // We could get here with no active tab if the Browser is closing. if (!active_tab) { Hide(); return false; } std::string instant_url; Profile* profile = active_tab->profile(); // If the match's TemplateURL is valid, it's a search query; use it. If it's // not valid, it's likely a URL; in EXTENDED mode, try using the default // search engine's TemplateURL instead. const GURL& tab_url = active_tab->web_contents()->GetURL(); if (GetInstantURL(match.GetTemplateURL(profile, false), tab_url, &instant_url)) { ResetLoader(instant_url, active_tab); } else if (mode_ != EXTENDED || !CreateDefaultLoader()) { Hide(); return false; } if (full_text.empty()) { Hide(); return false; } // Track the non-Instant search URL for this query. url_for_history_ = match.destination_url; last_transition_type_ = match.transition; last_active_tab_ = active_tab; last_match_was_search_ = AutocompleteMatch::IsSearchType(match.type); // In EXTENDED mode, we send only |user_text| as the query text. In all other // modes, we use the entire |full_text|. const string16& query_text = mode_ == EXTENDED ? user_text : full_text; string16 last_query_text = mode_ == EXTENDED ? last_user_text_ : last_full_text_; last_user_text_ = user_text; last_full_text_ = full_text; // Don't send an update to the loader if the query text hasn't changed. if (query_text == last_query_text && verbatim == last_verbatim_) { // Reuse the last suggestion, as it's still valid. browser_->SetInstantSuggestion(last_suggestion_); // We need to call Show() here because of this: // 1. User has typed a query (say Q). Instant overlay is showing results. // 2. User arrows-down to a URL entry or erases all omnibox text. Both of // these cause the overlay to Hide(). // 3. User arrows-up to Q or types Q again. The last text we processed is // still Q, so we don't Update() the loader, but we do need to Show(). if (loader_processed_last_update_) Show(100, INSTANT_SIZE_PERCENT); return true; } last_verbatim_ = verbatim; loader_processed_last_update_ = false; last_suggestion_ = InstantSuggestion(); loader_->Update(query_text, verbatim); content::NotificationService::current()->Notify( chrome::NOTIFICATION_INSTANT_CONTROLLER_UPDATED, content::Source<InstantController>(this), content::NotificationService::NoDetails()); // We don't have suggestions yet, but need to reset any existing "gray text". browser_->SetInstantSuggestion(InstantSuggestion()); // Though we may have handled a URL match above, we return false here, so that // omnibox prerendering can kick in. TODO(sreeram): Remove this (and always // return true) once we are able to commit URLs as well. return last_match_was_search_; } // TODO(tonyg): This method only fires when the omnibox bounds change. It also // needs to fire when the preview bounds change (e.g.: open/close info bar). void InstantController::SetOmniboxBounds(const gfx::Rect& bounds) { if (omnibox_bounds_ == bounds) return; omnibox_bounds_ = bounds; if (omnibox_bounds_.height() > last_omnibox_bounds_.height()) { update_bounds_timer_.Stop(); SendBoundsToPage(); } else if (!update_bounds_timer_.IsRunning()) { update_bounds_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(kUpdateBoundsDelayMS), this, &InstantController::SendBoundsToPage); } } void InstantController::HandleAutocompleteResults( const std::vector<AutocompleteProvider*>& providers) { if (mode_ != EXTENDED || !GetPreviewContents()) return; std::vector<InstantAutocompleteResult> results; for (ACProviders::const_iterator provider = providers.begin(); provider != providers.end(); ++provider) { for (ACMatches::const_iterator match = (*provider)->matches().begin(); match != (*provider)->matches().end(); ++match) { InstantAutocompleteResult result; result.provider = UTF8ToUTF16((*provider)->GetName()); result.is_search = AutocompleteMatch::IsSearchType(match->type); result.contents = match->description; result.destination_url = match->destination_url; result.relevance = match->relevance; results.push_back(result); } } loader_->SendAutocompleteResults(results); } bool InstantController::OnUpOrDownKeyPressed(int count) { if (mode_ != EXTENDED || !GetPreviewContents()) return false; loader_->OnUpOrDownKeyPressed(count); return true; } TabContents* InstantController::GetPreviewContents() const { return loader_.get() ? loader_->preview_contents() : NULL; } void InstantController::Hide() { last_active_tab_ = NULL; // The only time when the model is not already in the desired NOT_READY state // and GetPreviewContents() returns NULL is when we are in the commit path. // In that case, don't change the state just yet; otherwise we may cause the // preview to hide unnecessarily. Instead, the state will be set correctly // after the commit is done. if (GetPreviewContents()) model_.SetDisplayState(InstantModel::NOT_READY, 0, INSTANT_SIZE_PERCENT); if (GetPreviewContents() && !last_full_text_.empty()) { // Send a blank query to ask the preview to clear out old results. last_full_text_.clear(); last_user_text_.clear(); loader_->Update(last_full_text_, true); } } bool InstantController::IsCurrent() const { return !IsOutOfDate() && GetPreviewContents() && loader_->supports_instant() && last_match_was_search_; } void InstantController::CommitCurrentPreview(InstantCommitType type) { TabContents* preview = loader_->ReleasePreviewContents(type, last_full_text_); if (mode_ == EXTENDED) { // Consider what's happening: // 1. The user has typed a query in the omnibox and committed it (either // by pressing Enter or clicking on the preview). // 2. We commit the preview to the tab strip, and tell the page. // 3. The page will update the URL hash fragment with the query terms. // After steps 1 and 3, the omnibox will show the query terms. However, if // the URL we are committing at step 2 doesn't already have query terms, it // will flash for a brief moment as a plain URL. So, avoid that flicker by // pretending that the plain URL is actually the typed query terms. // TODO(samarth,beaudoin): Instead of this hack, we should add a new field // to NavigationEntry to keep track of what the correct query, if any, is. content::NavigationEntry* entry = preview->web_contents()->GetController().GetVisibleEntry(); std::string url = entry->GetVirtualURL().spec(); if (!google_util::IsInstantExtendedAPIGoogleSearchUrl(url) && google_util::IsGoogleDomainUrl(url, google_util::ALLOW_SUBDOMAIN, google_util::ALLOW_NON_STANDARD_PORTS)) { entry->SetVirtualURL(GURL( url + "#q=" + net::EscapeQueryParamValue(UTF16ToUTF8(last_full_text_), true))); chrome::search::SearchTabHelper::FromWebContents( preview->web_contents())->NavigationEntryUpdated(); } } // If the preview page has navigated since the last Update(), we need to add // the navigation to history ourselves. Else, the page will navigate after // commit, and it will be added to history in the usual manner. const history::HistoryAddPageArgs& last_navigation = loader_->last_navigation(); if (!last_navigation.url.is_empty()) { content::NavigationEntry* entry = preview->web_contents()->GetController().GetActiveEntry(); DCHECK_EQ(last_navigation.url, entry->GetURL()); // Add the page to history. HistoryTabHelper* history_tab_helper = HistoryTabHelper::FromWebContents(preview->web_contents()); history_tab_helper->UpdateHistoryForNavigation(last_navigation); // Update the page title. history_tab_helper->UpdateHistoryPageTitle(*entry); } // Add a fake history entry with a non-Instant search URL, so that search // terms extraction (for autocomplete history matches) works. if (HistoryService* history = HistoryServiceFactory::GetForProfile( preview->profile(), Profile::EXPLICIT_ACCESS)) { history->AddPage(url_for_history_, base::Time::Now(), NULL, 0, GURL(), history::RedirectList(), last_transition_type_, history::SOURCE_BROWSED, false); } AddPreviewUsageForHistogram(mode_, PREVIEW_COMMITTED); DeleteLoader(); preview->web_contents()->GetController().PruneAllButActive(); if (type != INSTANT_COMMIT_PRESSED_ALT_ENTER) { const TabContents* active_tab = browser_->GetActiveTabContents(); AddSessionStorageHistogram(mode_, active_tab, preview); preview->web_contents()->GetController().CopyStateFromAndPrune( &active_tab->web_contents()->GetController()); } // Browser takes ownership of the preview. browser_->CommitInstant(preview, type == INSTANT_COMMIT_PRESSED_ALT_ENTER); content::NotificationService::current()->Notify( chrome::NOTIFICATION_INSTANT_COMMITTED, content::Source<content::WebContents>(preview->web_contents()), content::NotificationService::NoDetails()); model_.SetDisplayState(InstantModel::NOT_READY, 0, INSTANT_SIZE_PERCENT); // Try to create another loader immediately so that it is ready for the next // user interaction. CreateDefaultLoader(); } void InstantController::OnAutocompleteLostFocus( gfx::NativeView view_gaining_focus) { is_omnibox_focused_ = false; // If there is no preview, nothing to do. if (!GetPreviewContents()) return; loader_->OnAutocompleteLostFocus(); // If the preview is not showing, only need to check for loader staleness. if (!model_.is_ready()) { MaybeOnStaleLoader(); return; } #if defined(OS_MACOSX) if (!loader_->IsPointerDownFromActivate()) { Hide(); MaybeOnStaleLoader(); } #else content::RenderWidgetHostView* rwhv = GetPreviewContents()->web_contents()->GetRenderWidgetHostView(); if (!view_gaining_focus || !rwhv) { Hide(); MaybeOnStaleLoader(); return; } #if defined(TOOLKIT_VIEWS) // For views the top level widget is always focused. If the focus change // originated in views determine the child Widget from the view that is being // focused. views::Widget* widget = views::Widget::GetWidgetForNativeView(view_gaining_focus); if (widget) { views::FocusManager* focus_manager = widget->GetFocusManager(); if (focus_manager && focus_manager->is_changing_focus() && focus_manager->GetFocusedView() && focus_manager->GetFocusedView()->GetWidget()) { view_gaining_focus = focus_manager->GetFocusedView()->GetWidget()->GetNativeView(); } } #endif gfx::NativeView tab_view = GetPreviewContents()->web_contents()->GetNativeView(); // Focus is going to the renderer. if (rwhv->GetNativeView() == view_gaining_focus || tab_view == view_gaining_focus) { // If the mouse is not down, focus is not going to the renderer. Someone // else moved focus and we shouldn't commit. if (!loader_->IsPointerDownFromActivate()) { Hide(); MaybeOnStaleLoader(); } return; } // Walk up the view hierarchy. If the view gaining focus is a subview of the // WebContents view (such as a windowed plugin or http auth dialog), we want // to keep the preview contents. Otherwise, focus has gone somewhere else, // such as the JS inspector, and we want to cancel the preview. gfx::NativeView view_gaining_focus_ancestor = view_gaining_focus; while (view_gaining_focus_ancestor && view_gaining_focus_ancestor != tab_view) { view_gaining_focus_ancestor = platform_util::GetParent(view_gaining_focus_ancestor); } if (view_gaining_focus_ancestor) { CommitCurrentPreview(INSTANT_COMMIT_FOCUS_LOST); return; } Hide(); MaybeOnStaleLoader(); #endif } void InstantController::OnAutocompleteGotFocus() { is_omnibox_focused_ = true; if (GetPreviewContents()) loader_->OnAutocompleteGotFocus(); CreateDefaultLoader(); } void InstantController::OnActiveTabModeChanged(bool active_tab_is_ntp) { active_tab_is_ntp_ = active_tab_is_ntp; if (GetPreviewContents()) loader_->OnActiveTabModeChanged(active_tab_is_ntp_); } bool InstantController::commit_on_pointer_release() const { return GetPreviewContents() && loader_->IsPointerDownFromActivate(); } void InstantController::SetSuggestions( InstantLoader* loader, const std::vector<InstantSuggestion>& suggestions) { if (loader_ != loader || IsOutOfDate()) return; loader_processed_last_update_ = true; InstantSuggestion suggestion; if (!suggestions.empty()) suggestion = suggestions[0]; if (suggestion.behavior == INSTANT_COMPLETE_REPLACE) { // We don't get an Update() when changing the omnibox due to a REPLACE // suggestion (so that we don't inadvertently cause the preview to change // what it's showing, as the user arrows up/down through the page-provided // suggestions). So, update these state variables here. last_full_text_ = suggestion.text; last_user_text_.clear(); last_verbatim_ = true; last_suggestion_ = InstantSuggestion(); last_match_was_search_ = suggestion.type == INSTANT_SUGGESTION_SEARCH; browser_->SetInstantSuggestion(suggestion); } else { // Suggestion text should be a full URL for URL suggestions, or the // completion of a query for query suggestions. if (suggestion.type == INSTANT_SUGGESTION_URL) { if (!StartsWith(suggestion.text, ASCIIToUTF16("http://"), false) && !StartsWith(suggestion.text, ASCIIToUTF16("https://"), false)) suggestion.text = ASCIIToUTF16("http://") + suggestion.text; } else if (StartsWith(suggestion.text, last_user_text_, true)) { // The user typed an exact prefix of the suggestion. suggestion.text.erase(0, last_user_text_.size()); } else if (!NormalizeAndStripPrefix(&suggestion.text, last_user_text_)) { // Unicode normalize and case-fold the user text and suggestion. If the // user text is a prefix, suggest the normalized, case-folded completion; // for instance, if the user types 'i' and the suggestion is 'INSTANT', // suggestion 'nstant'. Otherwise, the user text really isn't a prefix, // so suggest nothing. suggestion.text.clear(); } last_suggestion_ = suggestion; // Set the suggested text if the suggestion behavior is // INSTANT_COMPLETE_NEVER irrespective of verbatim because in this case // the suggested text does not get committed if the user presses enter. if (suggestion.behavior == INSTANT_COMPLETE_NEVER || !last_verbatim_) browser_->SetInstantSuggestion(suggestion); } Show(100, INSTANT_SIZE_PERCENT); } void InstantController::CommitInstantLoader(InstantLoader* loader) { if (loader_ != loader || !model_.is_ready() || IsOutOfDate()) return; CommitCurrentPreview(INSTANT_COMMIT_FOCUS_LOST); } void InstantController::ShowInstantPreview(InstantLoader* loader, InstantShownReason reason, int height, InstantSizeUnits units) { // Show even if IsOutOfDate() on the extended mode NTP to enable a search // provider call SetInstantPreviewHeight() to show a custom logo, e.g. a // Google doodle, before the user interacts with the page. if (loader_ != loader || mode_ != EXTENDED || (IsOutOfDate() && !active_tab_is_ntp_)) return; Show(height, units); } void InstantController::InstantLoaderPreviewLoaded(InstantLoader* loader) { AddPreviewUsageForHistogram(mode_, PREVIEW_LOADED); } void InstantController::InstantSupportDetermined(InstantLoader* loader, bool supports_instant) { if (supports_instant) { blacklisted_urls_.erase(loader->instant_url()); } else { ++blacklisted_urls_[loader->instant_url()]; if (loader_ == loader) DeleteLoader(); } content::NotificationService::current()->Notify( chrome::NOTIFICATION_INSTANT_SUPPORT_DETERMINED, content::Source<InstantController>(this), content::NotificationService::NoDetails()); } void InstantController::SwappedTabContents(InstantLoader* loader) { if (loader_ == loader) model_.SetPreviewContents(GetPreviewContents()); } void InstantController::InstantLoaderContentsFocused(InstantLoader* loader) { #if defined(USE_AURA) // On aura the omnibox only receives a focus lost if we initiate the focus // change. This does that. if (model_.is_ready() && !IsOutOfDate()) browser_->InstantPreviewFocused(); #endif } InstantController::InstantController(chrome::BrowserInstantController* browser, Mode mode) : browser_(browser), model_(ALLOW_THIS_IN_INITIALIZER_LIST(this)), mode_(mode), last_active_tab_(NULL), last_verbatim_(false), last_transition_type_(content::PAGE_TRANSITION_LINK), last_match_was_search_(false), loader_processed_last_update_(false), is_omnibox_focused_(false), active_tab_is_ntp_(false) { } void InstantController::ResetLoader(const std::string& instant_url, const TabContents* active_tab) { if (GetPreviewContents() && loader_->instant_url() != instant_url) DeleteLoader(); if (!GetPreviewContents()) { loader_.reset(new InstantLoader(this, instant_url, active_tab)); loader_->Init(); // Ensure the searchbox API has the correct focus state and context. if (is_omnibox_focused_) loader_->OnAutocompleteGotFocus(); else loader_->OnAutocompleteLostFocus(); loader_->OnActiveTabModeChanged(active_tab_is_ntp_); AddPreviewUsageForHistogram(mode_, PREVIEW_CREATED); // Reset the loader timer. stale_loader_timer_.Stop(); stale_loader_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kStaleLoaderTimeoutMS), this, &InstantController::OnStaleLoader); } } bool InstantController::CreateDefaultLoader() { const TabContents* active_tab = browser_->GetActiveTabContents(); // We could get here with no active tab if the Browser is closing. if (!active_tab) return false; const TemplateURL* template_url = TemplateURLServiceFactory::GetForProfile(active_tab->profile())-> GetDefaultSearchProvider(); const GURL& tab_url = active_tab->web_contents()->GetURL(); std::string instant_url; if (!GetInstantURL(template_url, tab_url, &instant_url)) return false; ResetLoader(instant_url, active_tab); return true; } void InstantController::OnStaleLoader() { // If the loader is showing, do not delete it. It will get deleted the next // time the autocomplete loses focus. if (model_.is_ready()) return; DeleteLoader(); CreateDefaultLoader(); } void InstantController::MaybeOnStaleLoader() { if (!stale_loader_timer_.IsRunning()) OnStaleLoader(); } void InstantController::DeleteLoader() { last_active_tab_ = NULL; last_full_text_.clear(); last_user_text_.clear(); last_verbatim_ = false; last_suggestion_ = InstantSuggestion(); last_match_was_search_ = false; loader_processed_last_update_ = false; last_omnibox_bounds_ = gfx::Rect(); url_for_history_ = GURL(); if (GetPreviewContents()) { AddPreviewUsageForHistogram(mode_, PREVIEW_DELETED); model_.SetDisplayState(InstantModel::NOT_READY, 0, INSTANT_SIZE_PERCENT); } // Schedule the deletion for later, since we may have gotten here from a call // within a |loader_| method (i.e., it's still on the stack). If we deleted // the loader immediately, things would still be fine so long as the caller // doesn't access any instance members after we return, but why rely on that? MessageLoop::current()->DeleteSoon(FROM_HERE, loader_.release()); } void InstantController::Show(int height, InstantSizeUnits units) { // Call even if showing in case height changed. if (!model_.is_ready()) AddPreviewUsageForHistogram(mode_, PREVIEW_SHOWED); model_.SetDisplayState(InstantModel::QUERY_RESULTS, height, units); } void InstantController::SendBoundsToPage() { if (last_omnibox_bounds_ == omnibox_bounds_ || IsOutOfDate() || !GetPreviewContents() || loader_->IsPointerDownFromActivate()) return; last_omnibox_bounds_ = omnibox_bounds_; gfx::Rect preview_bounds = browser_->GetInstantBounds(); gfx::Rect intersection = gfx::IntersectRects(omnibox_bounds_, preview_bounds); // Translate into window coordinates. if (!intersection.IsEmpty()) { intersection.Offset(-preview_bounds.origin().x(), -preview_bounds.origin().y()); } // In the current Chrome UI, these must always be true so they sanity check // the above operations. In a future UI, these may be removed or adjusted. // There is no point in sanity-checking |intersection.y()| because the omnibox // can be placed anywhere vertically relative to the preview (for example, in // Mac fullscreen mode, the omnibox is fully enclosed by the preview bounds). DCHECK_LE(0, intersection.x()); DCHECK_LE(0, intersection.width()); DCHECK_LE(0, intersection.height()); loader_->SetOmniboxBounds(intersection); } bool InstantController::GetInstantURL(const TemplateURL* template_url, const GURL& tab_url, std::string* instant_url) const { CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kInstantURL)) { *instant_url = command_line->GetSwitchValueASCII(switches::kInstantURL); return template_url != NULL; } if (!template_url) return false; const TemplateURLRef& instant_url_ref = template_url->instant_url_ref(); if (!instant_url_ref.IsValid()) return false; // Even if the URL template doesn't have search terms, it may have other // components (such as {google:baseURL}) that need to be replaced. *instant_url = instant_url_ref.ReplaceSearchTerms( TemplateURLRef::SearchTermsArgs(string16())); // Extended mode should always use HTTPS. TODO(sreeram): This section can be // removed if TemplateURLs supported "https://{google:host}/..." instead of // only supporting "{google:baseURL}...". if (mode_ == EXTENDED) { GURL url_obj(*instant_url); if (!url_obj.is_valid()) return false; if (!url_obj.SchemeIsSecure()) { const std::string new_scheme = "https"; const std::string new_port = "443"; GURL::Replacements secure; secure.SetSchemeStr(new_scheme); secure.SetPortStr(new_port); url_obj = url_obj.ReplaceComponents(secure); if (!url_obj.is_valid()) return false; *instant_url = url_obj.spec(); } } std::map<std::string, int>::const_iterator iter = blacklisted_urls_.find(*instant_url); if (iter != blacklisted_urls_.end() && iter->second > kMaxInstantSupportFailures) return false; return true; } bool InstantController::IsOutOfDate() const { return !last_active_tab_ || last_active_tab_ != browser_->GetActiveTabContents(); }
30,608
9,582
/* * Copyright (C) 2015, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "aidl.h" #include <fcntl.h> #include <iostream> #include <map> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/param.h> #include <sys/stat.h> #include <unistd.h> #ifdef _WIN32 #include <io.h> #include <direct.h> #include <sys/stat.h> #endif #include <android-base/strings.h> #include "aidl_language.h" #include "generate_cpp.h" #include "generate_java.h" #include "import_resolver.h" #include "logging.h" #include "options.h" #include "os.h" #include "type_cpp.h" #include "type_java.h" #include "type_namespace.h" #ifndef O_BINARY # define O_BINARY 0 #endif using android::base::Join; using android::base::Split; using std::cerr; using std::endl; using std::map; using std::set; using std::string; using std::unique_ptr; using std::vector; namespace android { namespace aidl { namespace { // The following are gotten as the offset from the allowable id's between // android.os.IBinder.FIRST_CALL_TRANSACTION=1 and // android.os.IBinder.LAST_CALL_TRANSACTION=16777215 const int kMinUserSetMethodId = 0; const int kMaxUserSetMethodId = 16777214; bool check_filename(const std::string& filename, const std::string& package, const std::string& name, unsigned line) { const char* p; string expected; string fn; size_t len; bool valid = false; if (!IoDelegate::GetAbsolutePath(filename, &fn)) { return false; } if (!package.empty()) { expected = package; expected += '.'; } len = expected.length(); for (size_t i=0; i<len; i++) { if (expected[i] == '.') { expected[i] = OS_PATH_SEPARATOR; } } expected.append(name, 0, name.find('.')); expected += ".aidl"; len = fn.length(); valid = (len >= expected.length()); if (valid) { p = fn.c_str() + (len - expected.length()); #ifdef _WIN32 if (OS_PATH_SEPARATOR != '/') { // Input filename under cygwin most likely has / separators // whereas the expected string uses \\ separators. Adjust // them accordingly. for (char *c = const_cast<char *>(p); *c; ++c) { if (*c == '/') *c = OS_PATH_SEPARATOR; } } #endif // aidl assumes case-insensitivity on Mac Os and Windows. #if defined(__linux__) valid = (expected == p); #else valid = !strcasecmp(expected.c_str(), p); #endif } if (!valid) { fprintf(stderr, "%s:%d interface %s should be declared in a file" " called %s.\n", filename.c_str(), line, name.c_str(), expected.c_str()); } return valid; } bool check_filenames(const std::string& filename, const AidlDocument* doc) { if (!doc) return true; const AidlInterface* interface = doc->GetInterface(); if (interface) { return check_filename(filename, interface->GetPackage(), interface->GetName(), interface->GetLine()); } bool success = true; for (const auto& item : doc->GetParcelables()) { success &= check_filename(filename, item->GetPackage(), item->GetName(), item->GetLine()); } return success; } bool gather_types(const std::string& filename, const AidlDocument* doc, TypeNamespace* types) { bool success = true; const AidlInterface* interface = doc->GetInterface(); if (interface) return types->AddBinderType(*interface, filename); for (const auto& item : doc->GetParcelables()) { success &= types->AddParcelableType(*item, filename); } return success; } int check_types(const string& filename, const AidlInterface* c, TypeNamespace* types) { int err = 0; if (c->IsUtf8() && c->IsUtf8InCpp()) { cerr << filename << ":" << c->GetLine() << "Interface cannot be marked as both @utf8 and @utf8InCpp"; err = 1; } // Has to be a pointer due to deleting copy constructor. No idea why. map<string, const AidlMethod*> method_names; for (const auto& m : c->GetMethods()) { bool oneway = m->IsOneway() || c->IsOneway(); if (!types->MaybeAddContainerType(m->GetType())) { err = 1; // return type is invalid } const ValidatableType* return_type = types->GetReturnType(m->GetType(), filename, *c); if (!return_type) { err = 1; } m->GetMutableType()->SetLanguageType(return_type); if (oneway && m->GetType().GetName() != "void") { cerr << filename << ":" << m->GetLine() << " oneway method '" << m->GetName() << "' cannot return a value" << endl; err = 1; } int index = 1; for (const auto& arg : m->GetArguments()) { if (!types->MaybeAddContainerType(arg->GetType())) { err = 1; } const ValidatableType* arg_type = types->GetArgType(*arg, index, filename, *c); if (!arg_type) { err = 1; } arg->GetMutableType()->SetLanguageType(arg_type); if (oneway && arg->IsOut()) { cerr << filename << ":" << m->GetLine() << " oneway method '" << m->GetName() << "' cannot have out parameters" << endl; err = 1; } } auto it = method_names.find(m->GetName()); // prevent duplicate methods if (it == method_names.end()) { method_names[m->GetName()] = m.get(); } else { cerr << filename << ":" << m->GetLine() << " attempt to redefine method " << m->GetName() << "," << endl << filename << ":" << it->second->GetLine() << " previously defined here." << endl; err = 1; } } return err; } void write_common_dep_file(const string& output_file, const vector<string>& aidl_sources, CodeWriter* writer) { // Encode that the output file depends on aidl input files. writer->Write("%s : \\\n", output_file.c_str()); writer->Write(" %s", Join(aidl_sources, " \\\n ").c_str()); writer->Write("\n\n"); // Output "<input_aidl_file>: " so make won't fail if the input .aidl file // has been deleted, moved or renamed in incremental build. for (const auto& src : aidl_sources) { writer->Write("%s :\n", src.c_str()); } } bool write_java_dep_file(const JavaOptions& options, const vector<unique_ptr<AidlImport>>& imports, const IoDelegate& io_delegate, const string& output_file_name) { string dep_file_name = options.DependencyFilePath(); if (dep_file_name.empty()) { return true; // nothing to do } CodeWriterPtr writer = io_delegate.GetCodeWriter(dep_file_name); if (!writer) { LOG(ERROR) << "Could not open dependency file: " << dep_file_name; return false; } vector<string> source_aidl = {options.input_file_name_}; for (const auto& import : imports) { if (!import->GetFilename().empty()) { source_aidl.push_back(import->GetFilename()); } } write_common_dep_file(output_file_name, source_aidl, writer.get()); return true; } bool write_cpp_dep_file(const CppOptions& options, const AidlInterface& interface, const vector<unique_ptr<AidlImport>>& imports, const IoDelegate& io_delegate) { using ::android::aidl::cpp::HeaderFile; using ::android::aidl::cpp::ClassNames; string dep_file_name = options.DependencyFilePath(); if (dep_file_name.empty()) { return true; // nothing to do } CodeWriterPtr writer = io_delegate.GetCodeWriter(dep_file_name); if (!writer) { LOG(ERROR) << "Could not open dependency file: " << dep_file_name; return false; } vector<string> source_aidl = {options.InputFileName()}; for (const auto& import : imports) { if (!import->GetFilename().empty()) { source_aidl.push_back(import->GetFilename()); } } vector<string> headers; for (ClassNames c : {ClassNames::CLIENT, ClassNames::SERVER, ClassNames::INTERFACE}) { headers.push_back(options.OutputHeaderDir() + '/' + HeaderFile(interface, c, false /* use_os_sep */)); } write_common_dep_file(options.OutputCppFilePath(), source_aidl, writer.get()); writer->Write("\n"); // Generated headers also depend on the source aidl files. writer->Write("%s : \\\n %s\n", Join(headers, " \\\n ").c_str(), Join(source_aidl, " \\\n ").c_str()); return true; } string generate_outputFileName(const JavaOptions& options, const AidlInterface& interface) { const string& name = interface.GetName(); string package = interface.GetPackage(); string result; // create the path to the destination folder based on the // interface package name result = options.output_base_folder_; result += OS_PATH_SEPARATOR; string packageStr = package; size_t len = packageStr.length(); for (size_t i=0; i<len; i++) { if (packageStr[i] == '.') { packageStr[i] = OS_PATH_SEPARATOR; } } result += packageStr; // add the filename by replacing the .aidl extension to .java result += OS_PATH_SEPARATOR; result.append(name, 0, name.find('.')); result += ".java"; return result; } int check_and_assign_method_ids(const char * filename, const std::vector<std::unique_ptr<AidlMethod>>& items) { // Check whether there are any methods with manually assigned id's and any that are not. // Either all method id's must be manually assigned or all of them must not. // Also, check for duplicates of user set id's and that the id's are within the proper bounds. set<int> usedIds; bool hasUnassignedIds = false; bool hasAssignedIds = false; for (const auto& item : items) { if (item->HasId()) { hasAssignedIds = true; // Ensure that the user set id is not duplicated. if (usedIds.find(item->GetId()) != usedIds.end()) { // We found a duplicate id, so throw an error. fprintf(stderr, "%s:%d Found duplicate method id (%d) for method: %s\n", filename, item->GetLine(), item->GetId(), item->GetName().c_str()); return 1; } // Ensure that the user set id is within the appropriate limits if (item->GetId() < kMinUserSetMethodId || item->GetId() > kMaxUserSetMethodId) { fprintf(stderr, "%s:%d Found out of bounds id (%d) for method: %s\n", filename, item->GetLine(), item->GetId(), item->GetName().c_str()); fprintf(stderr, " Value for id must be between %d and %d inclusive.\n", kMinUserSetMethodId, kMaxUserSetMethodId); return 1; } usedIds.insert(item->GetId()); } else { hasUnassignedIds = true; } if (hasAssignedIds && hasUnassignedIds) { fprintf(stderr, "%s: You must either assign id's to all methods or to none of them.\n", filename); return 1; } } // In the case that all methods have unassigned id's, set a unique id for them. if (hasUnassignedIds) { int newId = 0; for (const auto& item : items) { item->SetId(newId++); } } // success return 0; } bool validate_constants(const AidlInterface& interface) { bool success = true; set<string> names; for (const std::unique_ptr<AidlIntConstant>& int_constant : interface.GetIntConstants()) { if (names.count(int_constant->GetName()) > 0) { LOG(ERROR) << "Found duplicate constant name '" << int_constant->GetName() << "'"; success = false; } names.insert(int_constant->GetName()); // We've logged an error message for this on object construction. success = success && int_constant->IsValid(); } for (const std::unique_ptr<AidlStringConstant>& string_constant : interface.GetStringConstants()) { if (names.count(string_constant->GetName()) > 0) { LOG(ERROR) << "Found duplicate constant name '" << string_constant->GetName() << "'"; success = false; } names.insert(string_constant->GetName()); // We've logged an error message for this on object construction. success = success && string_constant->IsValid(); } return success; } // TODO: Remove this in favor of using the YACC parser b/25479378 bool ParsePreprocessedLine(const string& line, string* decl, vector<string>* package, string* class_name) { // erase all trailing whitespace and semicolons const size_t end = line.find_last_not_of(" ;\t"); if (end == string::npos) { return false; } if (line.rfind(';', end) != string::npos) { return false; } decl->clear(); string type; vector<string> pieces = Split(line.substr(0, end + 1), " \t"); for (const string& piece : pieces) { if (piece.empty()) { continue; } if (decl->empty()) { *decl = std::move(piece); } else if (type.empty()) { type = std::move(piece); } else { return false; } } // Note that this logic is absolutely wrong. Given a parcelable // org.some.Foo.Bar, the class name is Foo.Bar, but this code will claim that // the class is just Bar. However, this was the way it was done in the past. // // See b/17415692 size_t dot_pos = type.rfind('.'); if (dot_pos != string::npos) { *class_name = type.substr(dot_pos + 1); *package = Split(type.substr(0, dot_pos), "."); } else { *class_name = type; package->clear(); } return true; } } // namespace namespace internals { bool parse_preprocessed_file(const IoDelegate& io_delegate, const string& filename, TypeNamespace* types) { bool success = true; unique_ptr<LineReader> line_reader = io_delegate.GetLineReader(filename); if (!line_reader) { LOG(ERROR) << "cannot open preprocessed file: " << filename; success = false; return success; } string line; unsigned lineno = 1; for ( ; line_reader->ReadLine(&line); ++lineno) { if (line.empty() || line.compare(0, 2, "//") == 0) { // skip comments and empty lines continue; } string decl; vector<string> package; string class_name; if (!ParsePreprocessedLine(line, &decl, &package, &class_name)) { success = false; break; } if (decl == "parcelable") { AidlParcelable doc(new AidlQualifiedName(class_name, ""), lineno, package); types->AddParcelableType(doc, filename); } else if (decl == "interface") { auto temp = new std::vector<std::unique_ptr<AidlMember>>(); AidlInterface doc(class_name, lineno, "", false, temp, package); types->AddBinderType(doc, filename); } else { success = false; break; } } if (!success) { LOG(ERROR) << filename << ':' << lineno << " malformed preprocessed file line: '" << line << "'"; } return success; } AidlError load_and_validate_aidl( const std::vector<std::string>& preprocessed_files, const std::vector<std::string>& import_paths, const std::string& input_file_name, const IoDelegate& io_delegate, TypeNamespace* types, std::unique_ptr<AidlInterface>* returned_interface, std::vector<std::unique_ptr<AidlImport>>* returned_imports) { AidlError err = AidlError::OK; std::map<AidlImport*,std::unique_ptr<AidlDocument>> docs; // import the preprocessed file for (const string& s : preprocessed_files) { if (!parse_preprocessed_file(io_delegate, s, types)) { err = AidlError::BAD_PRE_PROCESSED_FILE; } } if (err != AidlError::OK) { return err; } // parse the input file Parser p{io_delegate}; if (!p.ParseFile(input_file_name)) { return AidlError::PARSE_ERROR; } AidlDocument* parsed_doc = p.GetDocument(); unique_ptr<AidlInterface> interface(parsed_doc->ReleaseInterface()); if (!interface) { LOG(ERROR) << "refusing to generate code from aidl file defining " "parcelable"; return AidlError::FOUND_PARCELABLE; } if (!check_filename(input_file_name.c_str(), interface->GetPackage(), interface->GetName(), interface->GetLine()) || !types->IsValidPackage(interface->GetPackage())) { LOG(ERROR) << "Invalid package declaration '" << interface->GetPackage() << "'"; return AidlError::BAD_PACKAGE; } // parse the imports of the input file ImportResolver import_resolver{io_delegate, import_paths}; for (auto& import : p.GetImports()) { if (types->HasImportType(*import)) { // There are places in the Android tree where an import doesn't resolve, // but we'll pick the type up through the preprocessed types. // This seems like an error, but legacy support demands we support it... continue; } string import_path = import_resolver.FindImportFile(import->GetNeededClass()); if (import_path.empty()) { cerr << import->GetFileFrom() << ":" << import->GetLine() << ": couldn't find import for class " << import->GetNeededClass() << endl; err = AidlError::BAD_IMPORT; continue; } import->SetFilename(import_path); Parser p{io_delegate}; if (!p.ParseFile(import->GetFilename())) { cerr << "error while parsing import for class " << import->GetNeededClass() << endl; err = AidlError::BAD_IMPORT; continue; } std::unique_ptr<AidlDocument> document(p.ReleaseDocument()); if (!check_filenames(import->GetFilename(), document.get())) err = AidlError::BAD_IMPORT; docs[import.get()] = std::move(document); } if (err != AidlError::OK) { return err; } // gather the types that have been declared if (!types->AddBinderType(*interface.get(), input_file_name)) { err = AidlError::BAD_TYPE; } interface->SetLanguageType(types->GetInterfaceType(*interface)); for (const auto& import : p.GetImports()) { // If we skipped an unresolved import above (see comment there) we'll have // an empty bucket here. const auto import_itr = docs.find(import.get()); if (import_itr == docs.cend()) { continue; } if (!gather_types(import->GetFilename(), import_itr->second.get(), types)) { err = AidlError::BAD_TYPE; } } // check the referenced types in parsed_doc to make sure we've imported them if (check_types(input_file_name, interface.get(), types) != 0) { err = AidlError::BAD_TYPE; } if (err != AidlError::OK) { return err; } // assign method ids and validate. if (check_and_assign_method_ids(input_file_name.c_str(), interface->GetMethods()) != 0) { return AidlError::BAD_METHOD_ID; } if (!validate_constants(*interface)) { return AidlError::BAD_CONSTANTS; } if (returned_interface) *returned_interface = std::move(interface); if (returned_imports) p.ReleaseImports(returned_imports); return AidlError::OK; } } // namespace internals int compile_aidl_to_cpp(const CppOptions& options, const IoDelegate& io_delegate) { unique_ptr<AidlInterface> interface; std::vector<std::unique_ptr<AidlImport>> imports; unique_ptr<cpp::TypeNamespace> types(new cpp::TypeNamespace()); types->Init(); AidlError err = internals::load_and_validate_aidl( std::vector<std::string>{}, // no preprocessed files options.ImportPaths(), options.InputFileName(), io_delegate, types.get(), &interface, &imports); if (err != AidlError::OK) { return 1; } if (!write_cpp_dep_file(options, *interface, imports, io_delegate)) { return 1; } return (cpp::GenerateCpp(options, *types, *interface, io_delegate)) ? 0 : 1; } int compile_aidl_to_java(const JavaOptions& options, const IoDelegate& io_delegate) { unique_ptr<AidlInterface> interface; std::vector<std::unique_ptr<AidlImport>> imports; unique_ptr<java::JavaTypeNamespace> types(new java::JavaTypeNamespace()); types->Init(); AidlError aidl_err = internals::load_and_validate_aidl( options.preprocessed_files_, options.import_paths_, options.input_file_name_, io_delegate, types.get(), &interface, &imports); if (aidl_err == AidlError::FOUND_PARCELABLE && !options.fail_on_parcelable_) { // We aborted code generation because this file contains parcelables. // However, we were not told to complain if we find parcelables. // Just generate a dep file and exit quietly. The dep file is for a legacy // use case by the SDK. write_java_dep_file(options, imports, io_delegate, ""); return 0; } if (aidl_err != AidlError::OK) { return 1; } string output_file_name = options.output_file_name_; // if needed, generate the output file name from the base folder if (output_file_name.empty() && !options.output_base_folder_.empty()) { output_file_name = generate_outputFileName(options, *interface); } // make sure the folders of the output file all exists if (!io_delegate.CreatePathForFile(output_file_name)) { return 1; } if (!write_java_dep_file(options, imports, io_delegate, output_file_name)) { return 1; } return generate_java(output_file_name, options.input_file_name_.c_str(), interface.get(), types.get(), io_delegate); } bool preprocess_aidl(const JavaOptions& options, const IoDelegate& io_delegate) { unique_ptr<CodeWriter> writer = io_delegate.GetCodeWriter(options.output_file_name_); for (const auto& file : options.files_to_preprocess_) { Parser p{io_delegate}; if (!p.ParseFile(file)) return false; AidlDocument* doc = p.GetDocument(); string line; const AidlInterface* interface = doc->GetInterface(); if (interface != nullptr && !writer->Write("interface %s;\n", interface->GetCanonicalName().c_str())) { return false; } for (const auto& parcelable : doc->GetParcelables()) { if (!writer->Write("parcelable %s;\n", parcelable->GetCanonicalName().c_str())) { return false; } } } return writer->Close(); } } // namespace android } // namespace aidl
23,425
7,477
#ifndef BOOST_MP11_SET_HPP_INCLUDED #define BOOST_MP11_SET_HPP_INCLUDED // Copyright 2015 Peter Dimov. // // Distributed under the Boost Software License, Version 1.0. // // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt #include <boost/mp11/utility.hpp> #include <boost/mp11/detail/mp_list.hpp> #include <type_traits> namespace boost { namespace mp11 { // mp_set_contains<S, V> namespace detail { template<class S, class V> struct mp_set_contains_impl; template<template<class...> class L, class... T, class V> struct mp_set_contains_impl<L<T...>, V> { using type = mp_to_bool<std::is_base_of<mp_identity<V>, mp_inherit<mp_identity<T>...>>>; }; } // namespace detail template<class S, class V> using mp_set_contains = typename detail::mp_set_contains_impl<S, V>::type; // mp_set_push_back<S, T...> namespace detail { template<class S, class... T> struct mp_set_push_back_impl; template<template<class...> class L, class... U> struct mp_set_push_back_impl<L<U...>> { using type = L<U...>; }; template<template<class...> class L, class... U, class T1, class... T> struct mp_set_push_back_impl<L<U...>, T1, T...> { using S = mp_if<mp_set_contains<L<U...>, T1>, L<U...>, L<U..., T1>>; using type = typename mp_set_push_back_impl<S, T...>::type; }; } // namespace detail template<class S, class... T> using mp_set_push_back = typename detail::mp_set_push_back_impl<S, T...>::type; // mp_set_push_front<S, T...> namespace detail { template<class S, class... T> struct mp_set_push_front_impl; template<template<class...> class L, class... U> struct mp_set_push_front_impl<L<U...>> { using type = L<U...>; }; template<template<class...> class L, class... U, class T1> struct mp_set_push_front_impl<L<U...>, T1> { using type = mp_if<mp_set_contains<L<U...>, T1>, L<U...>, L<T1, U...>>; }; template<template<class...> class L, class... U, class T1, class... T> struct mp_set_push_front_impl<L<U...>, T1, T...> { using S = typename mp_set_push_front_impl<L<U...>, T...>::type; using type = typename mp_set_push_front_impl<S, T1>::type; }; } // namespace detail template<class S, class... T> using mp_set_push_front = typename detail::mp_set_push_front_impl<S, T...>::type; // mp_is_set<S> namespace detail { template<class S> struct mp_is_set_impl { using type = mp_false; }; template<template<class...> class L, class... T> struct mp_is_set_impl<L<T...>> { using type = mp_to_bool<std::is_same<mp_list<T...>, mp_set_push_back<mp_list<>, T...>>>; }; } // namespace detail template<class S> using mp_is_set = typename detail::mp_is_set_impl<S>::type; } // namespace mp11 } // namespace boost #endif // #ifndef BOOST_MP11_SET_HPP_INCLUDED
2,741
1,090
/* ============================================================================== KratosStructuralApplication A library based on: Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi, Janosch Stascheit, Felix Nagel pooyan@cimne.upc.edu rrossi@cimne.upc.edu janosch.stascheit@rub.de nagel@sd.rub.de - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain - Ruhr-University Bochum, Institute for Structural Mechanics, Germany 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 condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS. 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 variablesIS", 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. ============================================================================== */ /* ********************************************************* * * Last Modified by: $Author: nelson $ * Date: $Date: 2008-09-03 \* Revision: $Revision: 1.1 $ * * ***********************************************************/ // System includes #include <iostream> // External includes #include<cmath> // Project includes #include "includes/define.h" #include "constitutive_laws/Isotropic_Damage_3D.h" #include "includes/constitutive_law.h" #include "utilities/math_utils.h" #include "custom_utilities/sd_math_utils.h" #include "custom_utilities/Tensor_utils.h" #include "includes/variables.h" #include "includes/process_info.h" #include "structural_application.h" #include "includes/properties.h" namespace Kratos { namespace Isotropic_Damage_3D_Auxiliaries { boost::numeric::ublas::bounded_matrix<double,3,3> mstemp; #pragma omp threadprivate(mstemp) boost::numeric::ublas::bounded_matrix<double,3,3> msaux; #pragma omp threadprivate(msaux) Matrix StressTensor(0,0); #pragma omp threadprivate(StressTensor) Matrix InvertedMatrix(0,0); #pragma omp threadprivate(InvertedMatrix) Vector PrincipalStress(0); #pragma omp threadprivate(PrincipalStress) Vector Aux_Vector(0); #pragma omp threadprivate(Aux_Vector) // Ver pagina 57 " Metodologia de Evaluacion de Estructuras de Hormigon Armado" Matrix C(0,0); #pragma omp threadprivate(C) Matrix D(0,0); #pragma omp threadprivate(D) Matrix V(0,0); #pragma omp threadprivate(V) Vector d_Sigma(0); #pragma omp threadprivate(d_Sigma) } using namespace Isotropic_Damage_3D_Auxiliaries; /** * TO BE TESTED!!! */ Isotropic_Damage_3D::Isotropic_Damage_3D() : ConstitutiveLaw< Node<3> >() { } /** * TO BE TESTED!!! */ Isotropic_Damage_3D::~Isotropic_Damage_3D() { } bool Isotropic_Damage_3D::Has( const Variable<double>& rThisVariable ) { return false; } bool Isotropic_Damage_3D::Has( const Variable<Vector>& rThisVariable ) { return false; } bool Isotropic_Damage_3D::Has( const Variable<Matrix>& rThisVariable ) { return false; } double Isotropic_Damage_3D::GetValue( const Variable<double>& rThisVariable ) { if( rThisVariable == DAMAGE) { return md; } else { return 0.00; //KRATOS_ERROR(std::logic_error, "double Variable case not considered", ""); } } Vector Isotropic_Damage_3D::GetValue( const Variable<Vector>& rThisVariable ) { KRATOS_ERROR(std::logic_error, "Vector Variable case not considered", ""); } Matrix Isotropic_Damage_3D::GetValue( const Variable<Matrix>& rThisVariable ) { KRATOS_ERROR(std::logic_error, "Matrix Variable case not considered", ""); } void Isotropic_Damage_3D::SetValue( const Variable<double>& rThisVariable, const double& rValue, const ProcessInfo& rCurrentProcessInfo ) { } void Isotropic_Damage_3D::SetValue( const Variable<Vector>& rThisVariable, const Vector& rValue, const ProcessInfo& rCurrentProcessInfo ) { } void Isotropic_Damage_3D::SetValue( const Variable<Matrix>& rThisVariable, const Matrix& rValue, const ProcessInfo& rCurrentProcessInfo ) { } void Isotropic_Damage_3D::Calculate(const Variable<Matrix >& rVariable, Matrix& rResult, const ProcessInfo& rCurrentProcessInfo) { } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::InitializeMaterial( const Properties& props, const GeometryType& geom, const Vector& ShapeFunctionsValues ) { // Nota: Estas Variables no seran necesarias almacenarlas por cada elemento. // Basta con llamarlas con sus propiedades. mFc = props[FC]; mFt = props[FT]; mEc = props[CONCRETE_YOUNG_MODULUS_C]; mEt = props[CONCRETE_YOUNG_MODULUS_T]; mNU = props[POISSON_RATIO]; mGE = props[FRACTURE_ENERGY]; ml = pow(fabs(geom.Volume()),0.333333333333333333); // longitud del elemento mr_old = mFt/sqrt(mEc); // KRATOS_WATCH(geom.Volume()); // KRATOS_WATCH(ml); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::InitializeSolutionStep( const Properties& props, const GeometryType& geom, const Vector& ShapeFunctionsValues , const ProcessInfo& CurrentProcessInfo) { //KRATOS_WATCH(ml); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateNoDamageElasticMatrix(Matrix& C, const double E, const double NU) { C.resize(6,6, false); //setting up material matrix double c1 = E / ((1.00+NU)*(1-2*NU)); double c2 = c1 * (1-NU); double c3 = c1 * NU; double c4 = c1 * 0.5 * (1 - 2*NU); //filling material matrix C(0,0) = c2; C(0,1) = c3; C(0,2) = c3; C(0,3) = 0.0; C(0,4) = 0.0; C(0,5) = 0.0; C(1,0) = c3; C(1,1) = c2; C(1,2) = c3; C(1,3) = 0.0; C(1,4) = 0.0; C(1,5) = 0.0; C(2,0) = c3; C(2,1) = c3; C(2,2) = c2; C(2,3) = 0.0; C(2,4) = 0.0; C(2,5) = 0.0; C(3,0) = 0.0; C(3,1) = 0.0; C(3,2) = 0.0; C(3,3) = c4; C(3,4) = 0.0; C(3,5) = 0.0; C(4,0) = 0.0; C(4,1) = 0.0; C(4,2) = 0.0; C(4,3) = 0.0; C(4,4) = c4; C(4,5) = 0.0; C(5,0) = 0.0; C(5,1) = 0.0; C(5,2) = 0.0; C(5,3) = 0.0; C(5,4) = 0.0; C(5,5) = c4; //KRATOS_WATCH(C); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateConstitutiveMatrix(const Vector& StrainVector, Matrix& ConstitutiveMatrix) { //Vector StressVector; ConstitutiveMatrix.resize(6,6,false); //StressVector.resize(3, false); Isotropic_Damage_3D::CalculateNoDamageElasticMatrix(ConstitutiveMatrix,mEc,mNU); ConstitutiveMatrix = (1.00-md)*ConstitutiveMatrix; //Isotropic_Damage_3D::CalculateStressAndTangentMatrix(StressVector,StrainVector,ConstitutiveMatrix); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateDamage(const Matrix& ConstitutiveMatrix, const Vector& StressVector, double& d) { double Tau = 0.00; double A = 0.00; double crit = 1.0e-9; double zero = 1.0e-9; double teta_a = 0.00; double teta_b = 0.00; double teta = 0.00; double r = 0.00; double elev = 0.00; double norma = 0.00; if (Aux_Vector.size() != 6) { StressTensor.resize(3,3,false); InvertedMatrix.resize(6,6, false); PrincipalStress.resize(3, false); Aux_Vector.resize(6, false); } double ro = mFt/sqrt(mEc); //Suponiendo el Ec=Ect double n = mFc/mFt; A = 1.00/((mGE*mEc)/(ml*mFt*mFt)-0.5); //KRATOS_WATCH(A); if (A < 0.00) { A = 0.00; std::cout<< "Warning: A is less than zero"<<std::endl; } StressTensor = MathUtils<double>::StressVectorToTensor(StressVector); SD_MathUtils<double>::InvertMatrix(ConstitutiveMatrix, InvertedMatrix); // Calculando norma de una matriz norma = SD_MathUtils<double>::normTensor(StressTensor); if(norma<1e-9) { PrincipalStress(0) = 0.00; PrincipalStress(1) = 0.00; PrincipalStress(2) = 0.00; } else { PrincipalStress = SD_MathUtils<double>::EigneValues(StressTensor,crit, zero); } // KRATOS_WATCH(PrincipalStress); teta_a = Tensor_Utils<double>::Mc_aully(PrincipalStress); teta_b = norm_1(PrincipalStress); // Condicion para no tener divison de 0/0 if (teta_a==0.00 && teta_b==0.00) teta = 1.00; else teta = teta_a/teta_b; noalias(Aux_Vector) = prod(trans(StressVector),InvertedMatrix); Tau = inner_prod(StressVector,Aux_Vector); Tau = sqrt(Tau); Tau = (teta + (1.00-teta)/n)*Tau; r = std::max(mr_old,Tau); // rold por ro elev = A*(1.00-r/ro); d = 1.00 - (ro/r)*exp(elev); if (d < 0.00) { d = fabs(d); //std::cout<<"Warning: Damage is less than zero"<<std::endl; } this-> md = d; this-> mr_new = r; } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::FinalizeSolutionStep( const Properties& props, const GeometryType& geom, const Vector& ShapeFunctionsValues , const ProcessInfo& CurrentProcessInfo) { mr_old = mr_new; //KRATOS_WATCH(mr_old); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateNoDamageStress(const Vector& StrainVector, Vector& StressVector) { double c1 = mEc / ((1.00+mNU)*(1-2*mNU)); double c2 = c1 * (1-mNU); double c3 = c1 * mNU; double c4 = c1 * 0.5 * (1 - 2*mNU); StressVector[0] = c2*StrainVector[0] + c3 * (StrainVector[1] + StrainVector[2]) ; StressVector[1] = c2*StrainVector[1] + c3 * (StrainVector[0] + StrainVector[2]) ; StressVector[2] = c2*StrainVector[2] + c3 * (StrainVector[0] + StrainVector[1]) ; StressVector[3] = c4*StrainVector[3]; StressVector[4] = c4*StrainVector[4]; StressVector[5] = c4*StrainVector[5]; } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateStress( const Vector& StrainVector, Vector& StressVector) { Matrix ConstitutiveMatrix; ConstitutiveMatrix.resize(6,6, false); double d=0.00; Isotropic_Damage_3D::CalculateNoDamageStress(StrainVector, StressVector); Isotropic_Damage_3D::CalculateNoDamageElasticMatrix(ConstitutiveMatrix,mEc,mNU); Isotropic_Damage_3D::CalculateDamage(ConstitutiveMatrix, StressVector, d); StressVector = (1.00-d)*StressVector; } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateCauchyStresses( Vector& rCauchy_StressVector, const Matrix& rF, const Vector& rPK2_StressVector, const Vector& rGreenLagrangeStrainVector) { Matrix S = MathUtils<double>::StressVectorToTensor( rPK2_StressVector ); double J = MathUtils<double>::Det2( rF ); noalias(mstemp) = prod(rF,S); noalias(msaux) = prod(mstemp,trans(rF)); msaux *= J; if(rCauchy_StressVector.size() != 6) rCauchy_StressVector.resize(6); rCauchy_StressVector[0] = msaux(0,0); rCauchy_StressVector[1] = msaux(1,1); rCauchy_StressVector[2] = msaux(2,2); rCauchy_StressVector[3] = msaux(1,2); rCauchy_StressVector[4] = msaux(1,3); rCauchy_StressVector[5] = msaux(2,3); } //*********************************************************************************************** //*********************************************************************************************** void Isotropic_Damage_3D::CalculateStressAndTangentMatrix(Vector& StressVector, const Vector& StrainVector, Matrix& algorithmicTangent) { } }
14,287
5,309
/* * @Author: xiaominfc * @Date: 2020-09-02 17:10:06 * @Description: main run for routeserver */ #include "RouteConn.h" #include "netlib.h" #include "ConfigFileReader.h" #include "version.h" #include "EventSocket.h" int main(int argc, char* argv[]) { PRINTSERVERVERSION() signal(SIGPIPE, SIG_IGN); srand(time(NULL)); CConfigFileReader config_file("routeserver.conf"); char* listen_ip = config_file.GetConfigName("ListenIP"); char* str_listen_msg_port = config_file.GetConfigName("ListenMsgPort"); if (!listen_ip || !str_listen_msg_port) { log("config item missing, exit... "); return -1; } uint16_t listen_msg_port = atoi(str_listen_msg_port); int ret = netlib_init(); if (ret == NETLIB_ERROR) return ret; CStrExplode listen_ip_list(listen_ip, ';'); for (uint32_t i = 0; i < listen_ip_list.GetItemCnt(); i++) { //ret = netlib_listen(listen_ip_list.GetItem(i), listen_msg_port, route_serv_callback, NULL); ret = tcp_server_listen(listen_ip_list.GetItem(i), listen_msg_port,new IMConnEventDefaultFactory<CRouteConn>()); if (ret == NETLIB_ERROR) return ret; } printf("server start listen on: %s:%d\n", listen_ip, listen_msg_port); init_routeconn_timer_callback(); printf("now enter the event loop...\n"); writePid(); netlib_eventloop(); return 0; }
1,306
536
#include <iostream> #include <map> #include <string> #include <vector> #include <math.h> #include<bits/stdc++.h> using namespace std; char Mapa[4] = {'a','b','c','d'}; vector<int> returnQuaternary(long int value, long int n_pos) { vector<int> retVect; int target = value; int module_r = 0; int counter = 0; int ii = 0; while(ii<n_pos) { while(target!=0) { module_r = target % 4; target = target / 4; retVect.push_back(module_r); ii++; } if(retVect.size()<n_pos)retVect.push_back(0); ii++; } /* cout<<"n = "<<value<<", quad = "; while(counter < retVect.size() ) { cout<<retVect[counter]; counter++; } cout<<endl; */ return retVect; } void returnManyPos(long int value,long int *offset,long int *n_pos) { long int counter = 1; long int target = value; long int adv = pow(4,counter); long int prev_adv = 0; while(adv<target) { counter++; prev_adv = adv; adv += pow(4,counter); } *offset = prev_adv; *n_pos = counter++; } string Solve (long int k, long int np) { // Write your code here string s; int counter = 0; string Letter; vector<int> vect; vect = returnQuaternary(k, np); counter = vect.size()-1; while(counter >= 0) { Letter = Mapa[vect[counter]]; s.append(Letter); counter--; } counter = 0; while(counter < vect.size()) { Letter = Mapa[vect[counter]]; s.append(Letter); counter++; } return s; } int main() { ios::sync_with_stdio(0); cin.tie(0); int T; long int n_offset = 0; long int n_position = 0; cin >> T; for(int t_i=0; t_i<T; t_i++) { int k; cin >> k; returnManyPos(k, &n_offset,&n_position); //cout<<"n_offset "<<n_offset<<", n_pos "<<n_position <<endl; string out_; out_ = Solve(k-n_offset-1,n_position); cout << out_; cout << "\n"; } }
2,107
799
// Copyright (C) 2015-2021 Virgil Security, Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> #include "CloudFile.h" #include <QDir> #include "Utils.h" using namespace vm; CloudFileId CloudFile::id() const noexcept { return m_id; } void CloudFile::setId(const CloudFileId &id) { m_id = id; } CloudFileId CloudFile::parentId() const noexcept { return m_parentId; } void CloudFile::setParentId(const CloudFileId &id) { m_parentId = id; } QString CloudFile::name() const noexcept { return m_name; } void CloudFile::setName(const QString &name) { m_name = name; } bool CloudFile::isFolder() const noexcept { return m_isFolder; } void CloudFile::setIsFolder(const bool isFolder) { m_isFolder = isFolder; } QString CloudFile::type() const { return m_type; } void CloudFile::setType(const QString &type) { m_type = type; } quint64 CloudFile::size() const noexcept { return m_size; } void CloudFile::setSize(const quint64 size) { m_size = size; } QDateTime CloudFile::createdAt() const noexcept { return m_createdAt; } void CloudFile::setCreatedAt(const QDateTime &dateTime) { m_createdAt = dateTime; } QDateTime CloudFile::updatedAt() const noexcept { return m_updatedAt; } void CloudFile::setUpdatedAt(const QDateTime &dateTime) { m_updatedAt = dateTime; } UserId CloudFile::updatedBy() const noexcept { return m_updatedBy; } void CloudFile::setUpdatedBy(const UserId &userId) { m_updatedBy = userId; } QByteArray CloudFile::encryptedKey() const noexcept { return m_encryptedKey; } void CloudFile::setEncryptedKey(const QByteArray &key) { m_encryptedKey = key; } QByteArray CloudFile::publicKey() const noexcept { return m_publicKey; } void CloudFile::setPublicKey(const QByteArray &key) { m_publicKey = key; } QString CloudFile::localPath() const noexcept { return m_localPath; } void CloudFile::setLocalPath(const QString &path) { m_localPath = path; } QString CloudFile::fingerprint() const noexcept { return m_fingerprint; } void CloudFile::setFingerprint(const QString &fingerprint) { m_fingerprint = fingerprint; } CloudFsSharedGroupId CloudFile::sharedGroupId() const { return m_sharedGroupId; } void CloudFile::setSharedGroupId(const CloudFsSharedGroupId &sharedGroupId) { m_sharedGroupId = sharedGroupId; } bool CloudFile::isRoot() const { return m_isFolder && m_id == CloudFileId::root(); } bool CloudFile::isShared() const { return m_sharedGroupId.isValid(); } void CloudFile::update(const CloudFile &file, const CloudFileUpdateSource source) { if (file.id() != id()) { throw std::logic_error("Failed to update cloud file: source id is different"); } if (isFolder() != file.isFolder()) { throw std::logic_error("Failed to update cloud file: used file and folder"); } setParentId(file.parentId()); // update always if (source == CloudFileUpdateSource::ListedParent) { setName(file.name()); setCreatedAt(file.createdAt()); setUpdatedAt(file.updatedAt()); setUpdatedBy(file.updatedBy()); setLocalPath(file.localPath()); if (isFolder()) { setEncryptedKey(file.encryptedKey()); setPublicKey(file.publicKey()); setSharedGroupId(file.sharedGroupId()); } } else if (source == CloudFileUpdateSource::ListedChild) { setName(file.name()); setCreatedAt(file.createdAt()); setUpdatedAt(file.updatedAt()); setUpdatedBy(file.updatedBy()); setLocalPath(file.localPath()); if (isFolder()) { if (file.updatedAt() > updatedAt()) { setEncryptedKey(QByteArray()); setPublicKey(QByteArray()); setSharedGroupId(CloudFsSharedGroupId()); } } else { setType(file.type()); setSize(file.size()); if (file.updatedAt() > updatedAt()) { setFingerprint(QString()); } } } else if (source == CloudFileUpdateSource::Download) { if (!isFolder()) { setFingerprint(file.fingerprint()); } } }
5,763
1,898
// https://leetcode.com/problems/kth-smallest-element-in-a-bst/ // Honestly, this problem should be classified as easy. class Solution { public: int kthSmallest(TreeNode* root, int k) { stack<TreeNode*> s; TreeNode* cur = root; while(cur != NULL){ s.push(cur); cur = cur->left; } while(k--){ cur = s.top(); s.pop(); if(k > 0 && cur->right != NULL){ s.push(cur->right); cur = cur->right; while(cur->left != NULL){ s.push(cur->left); cur = cur->left; } } } return cur->val; } };
721
222
#include <unistd.h> #include <cctype> #include <sstream> #include <string> #include <vector> #include <linux_parser.h> #include "process.h" using std::string; using std::to_string; using std::vector; Process::Process(int pid) :pid_(pid), user_(LinuxParser::User(pid_)), commandUsed_(LinuxParser::Command(pid_)) {}; int Process::Pid() { return pid_; } float Process::CpuUtilization() { // per https://stackoverflow.com/a/16736599 float total_time = LinuxParser::ActiveJiffies(Pid()); float uptime = LinuxParser::UpTime(); float seconds_active = uptime - (Process::UpTime() / sysconf(_SC_CLK_TCK)); return (total_time / sysconf(_SC_CLK_TCK)) / seconds_active; } string Process::Command() { return commandUsed_; } string Process::Ram() { return LinuxParser::Ram(pid_); } string Process::User() { return LinuxParser::User(pid_); } long int Process::UpTime() { return LinuxParser::UpTime(pid_); } bool Process::operator<(Process& a) { return CpuUtilization() > a.CpuUtilization(); }
1,029
356
/* * Copyright (c) 2018 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-03-24 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #pragma once #include <maxbase/ccdefs.hh> #include <atomic> #include <maxbase/worker.hh> #include <maxbase/watchdognotifier.hh> namespace maxbase { /** * @class WatchedWorker * * Base-class for workers that should be watched, that is, monitored * to ensure that they are processing epoll events. * * If a watched worker stops processing events it will cause the systemd * watchdog notification *not* to be generated, with the effect that the * process is killed and restarted. */ class WatchedWorker : public Worker, public WatchdogNotifier::Dependent { public: ~WatchedWorker(); protected: WatchedWorker(mxb::WatchdogNotifier* pNotifier); private: void call_epoll_tick() override final; }; }
1,130
345
#include <stdinc.h> #include "compiler.hpp" #include "symtable.hpp" #include "commands.hpp" #include "program.hpp" template<typename T, typename = std::enable_if_t<std::is_integral<T>::value>> static ArgVariant conv_int(T integral) { int32_t i = static_cast<int32_t>(integral); if(i >= std::numeric_limits<int8_t>::min() && i <= std::numeric_limits<int8_t>::max()) return int8_t(i); else if(i >= std::numeric_limits<int16_t>::min() && i <= std::numeric_limits<int16_t>::max()) return int16_t(i); else return int32_t(i); } void CompilerContext::compile() { Expects(compiled.empty()); Expects(script->top_label->code_position == nullopt); Expects(script->start_label->code_position == nullopt); program.supported_or_fatal(nocontext, commands.andor, "ANDOR"); program.supported_or_fatal(nocontext, commands.goto_, "GOTO"); program.supported_or_fatal(nocontext, commands.goto_if_false, "GOTO_IF_FALSE"); compile_label(script->top_label); compile_label(script->start_label); return compile_statements(*script->tree); } shared_ptr<Label> CompilerContext::make_internal_label() { this->internal_labels.emplace_back(std::make_shared<Label>(this->current_scope, this->script)); return this->internal_labels.back(); } void CompilerContext::compile_label(const SyntaxTree& label_node) { return compile_label(label_node.annotation<shared_ptr<Label>>()); } void CompilerContext::compile_label(shared_ptr<Label> label_ptr) { this->compiled.emplace_back(std::move(label_ptr)); } void CompilerContext::compile_command(const Command& command, ArgList args, bool not_flag) { if(command.extension && program.opt.pedantic) program.pedantic(this->script, "use of command {} which is a language extension [-pedantic]", command.name); if(command.has_optional()) { assert(args.size() == 0 || !is<EOAL>(args.back())); args.emplace_back(EOAL{}); } this->compiled.emplace_back(CompiledCommand{ not_flag, command, std::move(args) }); } void CompilerContext::compile_command(const SyntaxTree& command_node, bool not_flag) { if(command_node.maybe_annotation<DummyCommandAnnotation>()) { // compile nothing } else if(auto opt_annot = command_node.maybe_annotation<const ReplacedCommandAnnotation&>()) { const Command& command = opt_annot->command; if(commands.equal(command, commands.skip_cutscene_start_internal)) { this->label_skip_cutscene_end = any_cast<shared_ptr<Label>>(opt_annot->params[0]); } compile_command(command, get_args(opt_annot->command, opt_annot->params)); } else { const Command& command = command_node.annotation<std::reference_wrapper<const Command>>(); if(commands.equal(command, commands.skip_cutscene_end) && this->label_skip_cutscene_end) { compile_label(this->label_skip_cutscene_end); this->label_skip_cutscene_end = nullptr; } compile_command(command, get_args(command, command_node), not_flag); } } void CompilerContext::compile_statements(const SyntaxTree& base) { for(auto it = base.begin(); it != base.end(); ++it) compile_statement(*it->get()); } void CompilerContext::compile_statements(const SyntaxTree& parent, size_t from_id, size_t to_id_including) { for(size_t i = from_id; i <= to_id_including; ++i) compile_statement(parent.child(i)); } void CompilerContext::compile_statement(const SyntaxTree& node, bool not_flag) { switch(node.type()) { case NodeType::Block: // group of anything, usually group of statements compile_statements(node); break; case NodeType::NOT: compile_statement(node.child(0), !not_flag); break; case NodeType::Command: compile_command(node, not_flag); break; case NodeType::MISSION_START: case NodeType::SCRIPT_START: break; case NodeType::MISSION_END: case NodeType::SCRIPT_END: compile_mission_end(node, not_flag); break; case NodeType::Greater: case NodeType::GreaterEqual: case NodeType::Lesser: case NodeType::LesserEqual: compile_condition(node, not_flag); break; case NodeType::Equal: case NodeType::Cast: compile_expr(node, not_flag); break; case NodeType::Increment: case NodeType::Decrement: compile_incdec(node, not_flag); break; case NodeType::Label: compile_label(node); break; case NodeType::Scope: compile_scope(node); break; case NodeType::IF: compile_if(node); break; case NodeType::WHILE: compile_while(node); break; case NodeType::REPEAT: compile_repeat(node); break; case NodeType::SWITCH: compile_switch(node); break; case NodeType::BREAK: compile_break(node); break; case NodeType::CONTINUE: compile_continue(node); break; case NodeType::VAR_INT: case NodeType::LVAR_INT: case NodeType::VAR_FLOAT: case NodeType::LVAR_FLOAT: case NodeType::VAR_TEXT_LABEL: case NodeType::LVAR_TEXT_LABEL: case NodeType::VAR_TEXT_LABEL16: case NodeType::LVAR_TEXT_LABEL16: break; case NodeType::CONST_INT: case NodeType::CONST_FLOAT: break; case NodeType::DUMP: compile_dump(node); break; default: Unreachable(); } } void CompilerContext::compile_dump(const SyntaxTree& node) { this->compiled.emplace_back(node.annotation<DumpAnnotation>().bytes); } void CompilerContext::compile_scope(const SyntaxTree& scope_node) { auto guard = make_scope_guard([this] { this->current_scope = nullptr; }); Expects(this->current_scope == nullptr); this->current_scope = scope_node.annotation<shared_ptr<Scope>>(); compile_statements(scope_node.child(0)); } void CompilerContext::compile_if(const SyntaxTree& if_node) { if(if_node.child_count() == 3) // [conds, case_true, else] { auto else_ptr = make_internal_label(); auto end_ptr = make_internal_label(); compile_conditions(if_node.child(0), else_ptr); compile_statements(if_node.child(1)); compile_command(*this->commands.goto_, { end_ptr }); compile_label(else_ptr); compile_statements(if_node.child(2)); compile_label(end_ptr); } else // [conds, case_true] { auto end_ptr = make_internal_label(); compile_conditions(if_node.child(0), end_ptr); compile_statements(if_node.child(1)); compile_label(end_ptr); } } void CompilerContext::compile_while(const SyntaxTree& while_node) { auto beg_ptr = make_internal_label(); auto end_ptr = make_internal_label(); loop_stack.emplace_back(LoopInfo { beg_ptr, end_ptr }); compile_label(beg_ptr); compile_conditions(while_node.child(0), end_ptr); compile_statements(while_node.child(1)); compile_command(*this->commands.goto_, { beg_ptr }); compile_label(end_ptr); loop_stack.pop_back(); } void CompilerContext::compile_repeat(const SyntaxTree& repeat_node) { auto& annotation = repeat_node.annotation<const RepeatAnnotation&>(); auto& times = repeat_node.child(0); auto& var = repeat_node.child(1); auto continue_ptr = make_internal_label(); auto break_ptr = make_internal_label(); auto loop_ptr = make_internal_label(); loop_stack.emplace_back(LoopInfo { continue_ptr, break_ptr }); compile_command(annotation.set_var_to_zero, { get_arg(var), get_arg(annotation.number_zero) }); compile_label(loop_ptr); compile_statements(repeat_node.child(2)); compile_label(continue_ptr); compile_command(annotation.add_var_with_one, { get_arg(var), get_arg(annotation.number_one) }); compile_command(annotation.is_var_geq_times, { get_arg(var), get_arg(times) }); compile_command(*this->commands.goto_if_false, { loop_ptr }); compile_label(break_ptr); loop_stack.pop_back(); } void CompilerContext::compile_switch(const SyntaxTree& switch_node) { auto continue_ptr = nullptr; auto break_ptr = make_internal_label(); loop_stack.emplace_back(LoopInfo{ continue_ptr, break_ptr }); std::vector<Case> cases; cases.reserve(1 + switch_node.annotation<const SwitchAnnotation&>().num_cases); auto& switch_body = switch_node.child(1); for(size_t i = 0; i < switch_body.child_count(); ++i) { auto& node = switch_body.child(i); switch(node.type()) { case NodeType::CASE: { auto value = node.child(0).annotation<int32_t>(); auto& isveq = node.annotation<const SwitchCaseAnnotation&>().is_var_eq_int; cases.emplace_back(value, isveq); break; } case NodeType::DEFAULT: { cases.emplace_back(nullopt, nullopt); break; } default: // statement { if(!cases.empty()) { auto& prev_case = cases.back(); if(prev_case.first_statement_id == SIZE_MAX) prev_case.first_statement_id = i; prev_case.last_statement_id = i; } break; } } } auto blank_cases_begin = cases.end(); auto blank_cases_end = cases.end(); for(auto it = cases.begin(); it != cases.end(); ++it) { if(it->is_empty()) { if(blank_cases_begin == cases.end()) { blank_cases_begin = it; blank_cases_end = std::next(it); } else { blank_cases_end = std::next(it); } } else { if(blank_cases_begin != cases.end()) { for(auto e = blank_cases_begin; e != blank_cases_end; ++e) { e->first_statement_id = it->first_statement_id; e->last_statement_id = it->last_statement_id; } blank_cases_begin = cases.end(); blank_cases_end = cases.end(); } } } auto opt_switch_start = commands.switch_start; auto opt_switch_continued = commands.switch_continued; if(opt_switch_start && opt_switch_start->supported && opt_switch_continued && opt_switch_continued->supported) { compile_switch_withop(switch_node, cases, break_ptr); } else { compile_switch_ifchain(switch_node, cases, break_ptr); } loop_stack.pop_back(); } void CompilerContext::compile_switch_withop(const SyntaxTree& swnode, std::vector<Case>& cases, shared_ptr<Label> break_ptr) { std::vector<Case*> sorted_cases; // does not contain default, unlike `cases` sorted_cases.resize(cases.size()); bool has_default = swnode.annotation<const SwitchAnnotation&>().has_default; const Case* case_default = nullptr; const Command& switch_start = this->commands.switch_start.value(); const Command& switch_continued = this->commands.switch_continued.value(); std::transform(cases.begin(), cases.end(), sorted_cases.begin(), [] (auto& c) { return std::addressof<Case>(c); }); std::sort(sorted_cases.begin(), sorted_cases.end(), [](const Case* a, const Case* b) { if(a->is_default()) return false; // default should be the last if(b->is_default()) return true; // !a->is_default() == true return *a->value < *b->value; }); if(has_default) { case_default = sorted_cases.back(); sorted_cases.pop_back(); assert(case_default->is_default()); } for(auto& c : cases) c.target = make_internal_label(); for(size_t i = 0; i < sorted_cases.size(); ) { std::vector<ArgVariant> args; args.reserve(18); const Command& switch_op = (i == 0? switch_start : switch_continued); size_t max_cases_here = (i == 0? 7 : 9); if(i == 0) { args.emplace_back(get_arg(swnode.child(0))); args.emplace_back(conv_int(sorted_cases.size())); args.emplace_back(conv_int(has_default)); args.emplace_back(has_default? case_default->target : break_ptr); } for(size_t k = 0; k < max_cases_here; ++k, ++i) { if(i < sorted_cases.size()) { args.emplace_back(conv_int(*sorted_cases[i]->value)); args.emplace_back(sorted_cases[i]->target); } else { args.emplace_back(conv_int(-1)); args.emplace_back(break_ptr); } } compile_command(switch_op, std::move(args)); } for(auto it = cases.begin(); it != cases.end(); ++it) { compile_label(it->target); if(std::next(it) == cases.end() || !std::next(it)->same_body_as(*it)) { compile_statements(swnode.child(1), it->first_statement_id, it->last_statement_id); } } compile_label(break_ptr); } void CompilerContext::compile_switch_ifchain(const SyntaxTree& swnode, std::vector<Case>& cases, shared_ptr<Label> break_ptr) { Case* default_case = nullptr; for(auto it = cases.begin(), next_it = cases.end(); it != cases.end(); it = next_it) { auto next_ptr = make_internal_label(); auto body_ptr = make_internal_label(); next_it = std::find_if(std::next(it), cases.end(), [&](const Case& c){ return !c.same_body_as(*it); }); auto num_ifs = std::accumulate(it, next_it, size_t(0), [](size_t accum, const Case& c) { return accum + (c.is_default()? 0 : 1); }); if(num_ifs > 8) program.error(swnode, "more than 8 cases with the same body not supported using if-chain"); else if(num_ifs > 1) compile_command(*commands.andor, { conv_int(21 + num_ifs - 2) }); else if(num_ifs == 0 && it->is_default()) { default_case = std::addressof(*it); continue; } for(auto k = it; k != next_it; ++k) { if(!k->is_default()) { if(k->is_var_eq_int == nullopt) program.fatal_error(nocontext, "unexpected failure at {}", __func__); compile_command(**k->is_var_eq_int, { get_arg(swnode.child(0)), conv_int(*k->value) }); } else default_case = std::addressof(*k); } if(num_ifs) compile_command(*commands.goto_if_false, { next_ptr }); compile_label(body_ptr); std::for_each(it, next_it, [&](Case& c) { c.target = body_ptr; }); compile_statements(swnode.child(1), it->first_statement_id, it->last_statement_id); compile_label(next_ptr); } if(default_case) { if(default_case->target) { compile_command(*commands.goto_, { default_case->target }); } else { default_case->target = make_internal_label(); compile_label(default_case->target); compile_statements(swnode.child(1), default_case->first_statement_id, default_case->last_statement_id); } } compile_label(break_ptr); } void CompilerContext::compile_break(const SyntaxTree& break_node) { for(auto it = loop_stack.rbegin(); it != loop_stack.rend(); ++it) { if(it->break_label) { compile_command(*commands.goto_, { it->break_label }); return; } } Unreachable(); } void CompilerContext::compile_continue(const SyntaxTree& continue_node) { for(auto it = loop_stack.rbegin(); it != loop_stack.rend(); ++it) { if(it->continue_label) { compile_command(*commands.goto_, { it->continue_label }); return; } } Unreachable(); } void CompilerContext::compile_expr(const SyntaxTree& eq_node, bool not_flag) { if(eq_node.child(1).maybe_annotation<std::reference_wrapper<const Command>>()) { // 'a = b OP c' or 'a OP= b' const SyntaxTree& op_node = eq_node.child(1); const Command& cmd_set = eq_node.annotation<std::reference_wrapper<const Command>>(); const Command& cmd_op = op_node.annotation<std::reference_wrapper<const Command>>(); auto a = get_arg(eq_node.child(0)); auto b = get_arg(op_node.child(0)); auto c = get_arg(op_node.child(1)); if(!is_same_var(a, b)) { if(!is_same_var(a, c)) { compile_command(cmd_set, { a, b }, not_flag); compile_command(cmd_op, { a, c }, not_flag); } else { // Safe. The annotate_tree step won't allow non-commutative // operations (substraction or division) to be compiled. compile_command(cmd_op, { a, b }, not_flag); } } else { compile_command(cmd_op, { a, c }, not_flag); } } else { // 'a = b' or 'a =# b' or 'a > b' (and such) bool invert = (eq_node.type() == NodeType::Lesser || eq_node.type() == NodeType::LesserEqual); auto& a_node = eq_node.child(!invert? 0 : 1); auto& b_node = eq_node.child(!invert? 1 : 0); const Command& cmd_set = eq_node.annotation<std::reference_wrapper<const Command>>(); compile_command(cmd_set, { get_arg(a_node), get_arg(b_node) }, not_flag); } } void CompilerContext::compile_incdec(const SyntaxTree& op_node, bool not_flag) { auto& annotation = op_node.annotation<const IncDecAnnotation&>(); auto& var = op_node.child(0); compile_command(annotation.op_var_with_one, { get_arg(var), get_arg(annotation.number_one) }); } void CompilerContext::compile_mission_end(const SyntaxTree& me_node, bool not_flag) { const Command& command = me_node.annotation<std::reference_wrapper<const Command>>(); return compile_command(command, {}, not_flag); } void CompilerContext::compile_condition(const SyntaxTree& node, bool not_flag) { // also see compile_conditions switch(node.type()) { case NodeType::NOT: return compile_condition(node.child(0), !not_flag); case NodeType::Command: return compile_command(node, not_flag); case NodeType::Equal: case NodeType::Greater: case NodeType::GreaterEqual: case NodeType::Lesser: case NodeType::LesserEqual: return compile_expr(node, not_flag); default: Unreachable(); } } void CompilerContext::compile_conditions(const SyntaxTree& conds_node, const shared_ptr<Label>& else_ptr) { auto compile_multi_andor = [this](const auto& conds_node, size_t op) { assert(conds_node.child_count() <= 8); compile_command(*this->commands.andor, { conv_int(op + conds_node.child_count() - 2) }); for(auto& cond : conds_node) compile_condition(*cond); }; switch(conds_node.type()) { // single condition (also see compile_condition) case NodeType::NOT: case NodeType::Command: case NodeType::Equal: case NodeType::Greater: case NodeType::GreaterEqual: case NodeType::Lesser: case NodeType::LesserEqual: if (!this->program.opt.optimize_andor) compile_command(*this->commands.andor, { conv_int(0) }); compile_condition(conds_node); break; case NodeType::AND: // 1-8 compile_multi_andor(conds_node, 1); break; case NodeType::OR: // 21-28 compile_multi_andor(conds_node, 21); break; default: Unreachable(); } compile_command(*this->commands.goto_if_false, { else_ptr }); } auto CompilerContext::get_args(const Command& command, const std::vector<any>& params) -> ArgList { ArgList args; args.reserve(params.size()); for(auto& p : params) args.emplace_back(get_arg(p)); return args; } auto CompilerContext::get_args(const Command& command, const SyntaxTree& command_node) -> ArgList { Expects(command_node.child_count() >= 1); // command_name + [args...] ArgList args; args.reserve(command_node.child_count() - 1); for(auto it = std::next(command_node.begin()); it != command_node.end(); ++it) args.emplace_back( get_arg(**it) ); return args; } ArgVariant CompilerContext::get_arg(const Commands::MatchArgument& a) { if(is<int32_t>(a)) return conv_int(get<int32_t>(a)); else if(is<float>(a)) return get<float>(a); else return get_arg(*get<const SyntaxTree*>(a)); } ArgVariant CompilerContext::get_arg(const any& param) { if(auto opt = any_cast<int32_t>(&param)) return conv_int(*opt); else if(auto opt = any_cast<float>(&param)) return *opt; else if(auto opt = any_cast<shared_ptr<Label>>(&param)) return std::move(*opt); else Unreachable(); // implement more on necessity } ArgVariant CompilerContext::get_arg(const SyntaxTree& arg_node) { switch(arg_node.type()) { case NodeType::Integer: { return conv_int(arg_node.annotation<int32_t>()); } case NodeType::Float: { return arg_node.annotation<float>(); } case NodeType::Text: { if(auto opt_int = arg_node.maybe_annotation<int32_t>()) { return conv_int(*opt_int); } else if(auto opt_flt = arg_node.maybe_annotation<float>()) { return *opt_flt; } else if(auto opt_var = arg_node.maybe_annotation<shared_ptr<Var>>()) { return CompiledVar{ std::move(*opt_var), nullopt }; } else if(auto opt_var = arg_node.maybe_annotation<const ArrayAnnotation&>()) { if(is<shared_ptr<Var>>(opt_var->index)) return CompiledVar { opt_var->base, get<shared_ptr<Var>>(opt_var->index) }; else return CompiledVar { opt_var->base, get<int32_t>(opt_var->index) }; } else if(auto opt_label = arg_node.maybe_annotation<shared_ptr<Label>>()) { auto label = std::move(*opt_label); if(!label->may_branch_from(*this->script, program)) { auto sckind_ = to_string(label->script.lock()->type); program.error(arg_node, "reference to local label outside of its {} script", sckind_); program.note(*label->script.lock(), "label belongs to this script"); } return label; } else if(auto opt_text = arg_node.maybe_annotation<const TextLabelAnnotation&>()) { // TODO FIXME this is not the correct place to put this check, but I'm too lazy atm to put in the analyzes phase. if(program.opt.warn_conflict_text_label_var && symbols.find_var(opt_text->string, this->current_scope)) program.warning(arg_node, "text label collides with some variable name"); auto type = opt_text->is_varlen? CompiledString::Type::StringVar : CompiledString::Type::TextLabel8; return CompiledString{ type, opt_text->preserve_case, opt_text->string }; } else if(auto opt_umodel = arg_node.maybe_annotation<const ModelAnnotation&>()) { assert(opt_umodel->where.expired() == false); int32_t i32 = opt_umodel->where.lock()->find_model_at(opt_umodel->id); return conv_int(i32); } else { Unreachable(); } break; } case NodeType::String: { if(auto opt_text = arg_node.maybe_annotation<const TextLabelAnnotation&>()) { auto type = opt_text->is_varlen? CompiledString::Type::StringVar : CompiledString::Type::TextLabel8; return CompiledString{ type, opt_text->preserve_case, opt_text->string }; } else if(auto opt_buffer = arg_node.maybe_annotation<const String128Annotation&>()) { return CompiledString { CompiledString::Type::String128, false, opt_buffer->string }; } else { Unreachable(); } break; } default: Unreachable(); } } bool CompilerContext::is_same_var(const ArgVariant& lhs, const ArgVariant& rhs) { if(is<CompiledVar>(lhs) && is<CompiledVar>(rhs)) { return get<CompiledVar>(lhs) == get<CompiledVar>(rhs); } return false; }
25,507
7,946
/**************************************************************************** * * Copyright (c) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "../PreFlightCheck.hpp" #include <HealthFlags.h> #include <lib/parameters/param.h> #include <systemlib/mavlink_log.h> #include <uORB/Subscription.hpp> #include <uORB/topics/sensor_preflight.h> #include <uORB/topics/subsystem_info.h> bool PreFlightCheck::imuConsistencyCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, const bool report_status) { float test_limit = 1.0f; // pass limit re-used for each test // Get sensor_preflight data if available and exit with a fail recorded if not uORB::SubscriptionData<sensor_preflight_s> sensors_sub{ORB_ID(sensor_preflight)}; sensors_sub.update(); const sensor_preflight_s &sensors = sensors_sub.get(); // Use the difference between IMU's to detect a bad calibration. // If a single IMU is fitted, the value being checked will be zero so this check will always pass. param_get(param_find("COM_ARM_IMU_ACC"), &test_limit); if (sensors.accel_inconsistency_m_s_s > test_limit) { if (report_status) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Accels inconsistent - Check Cal"); set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_ACC, false, status); set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_ACC2, false, status); } return false; } else if (sensors.accel_inconsistency_m_s_s > test_limit * 0.8f) { if (report_status) { mavlink_log_info(mavlink_log_pub, "Preflight Advice: Accels inconsistent - Check Cal"); } } // Fail if gyro difference greater than 5 deg/sec and notify if greater than 2.5 deg/sec param_get(param_find("COM_ARM_IMU_GYR"), &test_limit); if (sensors.gyro_inconsistency_rad_s > test_limit) { if (report_status) { mavlink_log_critical(mavlink_log_pub, "Preflight Fail: Gyros inconsistent - Check Cal"); set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_GYRO, false, status); set_health_flags_healthy(subsystem_info_s::SUBSYSTEM_TYPE_GYRO2, false, status); } return false; } else if (sensors.gyro_inconsistency_rad_s > test_limit * 0.5f) { if (report_status) { mavlink_log_info(mavlink_log_pub, "Preflight Advice: Gyros inconsistent - Check Cal"); } } return true; }
3,894
1,439
/****************************************************************************** * * Project: KML Translator * Purpose: Implements OGRLIBKMLDriver * Author: Brian Case, rush at winkey dot org * ****************************************************************************** * Copyright (c) 2010, Brian Case * * 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 <ogrsf_frmts.h> #include <ogr_feature.h> #include "ogr_p.h" #include <kml/dom.h> #include <iostream> using kmldom::ExtendedDataPtr; using kmldom::SchemaPtr; using kmldom::SchemaDataPtr; using kmldom::SimpleDataPtr; using kmldom::DataPtr; using kmldom::TimeStampPtr; using kmldom::TimeSpanPtr; using kmldom::TimePrimitivePtr; using kmldom::PointPtr; using kmldom::LineStringPtr; using kmldom::PolygonPtr; using kmldom::MultiGeometryPtr; using kmldom::GeometryPtr; using kmldom::FeaturePtr; using kmldom::GroundOverlayPtr; using kmldom::IconPtr; #include "ogr_libkml.h" #include "ogrlibkmlfield.h" void ogr2altitudemode_rec ( GeometryPtr poKmlGeometry, int iAltitudeMode, int isGX ) { PointPtr poKmlPoint; LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: poKmlPoint = AsPoint ( poKmlGeometry ); if ( !isGX ) poKmlPoint->set_altitudemode ( iAltitudeMode ); else poKmlPoint->set_gx_altitudemode ( iAltitudeMode ); break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); if ( !isGX ) poKmlLineString->set_altitudemode ( iAltitudeMode ); else poKmlLineString->set_gx_altitudemode ( iAltitudeMode ); break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); if ( !isGX ) poKmlPolygon->set_altitudemode ( iAltitudeMode ); else poKmlPolygon->set_gx_altitudemode ( iAltitudeMode ); break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { ogr2altitudemode_rec ( poKmlMultiGeometry-> get_geometry_array_at ( i ), iAltitudeMode, isGX ); } break; default: break; } } void ogr2extrude_rec ( int nExtrude, GeometryPtr poKmlGeometry ) { PointPtr poKmlPoint; LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: poKmlPoint = AsPoint ( poKmlGeometry ); poKmlPoint->set_extrude ( nExtrude ); break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); poKmlLineString->set_extrude ( nExtrude ); break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); poKmlPolygon->set_extrude ( nExtrude ); break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { ogr2extrude_rec ( nExtrude, poKmlMultiGeometry-> get_geometry_array_at ( i ) ); } break; default: break; } } void ogr2tessellate_rec ( int nTessellate, GeometryPtr poKmlGeometry ) { LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); poKmlLineString->set_tessellate ( nTessellate ); break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); poKmlPolygon->set_tessellate ( nTessellate ); break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { ogr2tessellate_rec ( nTessellate, poKmlMultiGeometry-> get_geometry_array_at ( i ) ); } break; default: break; } } /************************************************************************/ /* OGRLIBKMLSanitizeUTF8String() */ /************************************************************************/ static char* OGRLIBKMLSanitizeUTF8String(const char* pszString) { if (!CPLIsUTF8(pszString, -1) && CSLTestBoolean(CPLGetConfigOption("OGR_FORCE_ASCII", "YES"))) { static int bFirstTime = TRUE; if (bFirstTime) { bFirstTime = FALSE; CPLError(CE_Warning, CPLE_AppDefined, "%s is not a valid UTF-8 string. Forcing it to ASCII.\n" "If you still want the original string and change the XML file encoding\n" "afterwards, you can define OGR_FORCE_ASCII=NO as configuration option.\n" "This warning won't be issued anymore", pszString); } else { CPLDebug("OGR", "%s is not a valid UTF-8 string. Forcing it to ASCII", pszString); } return CPLForceToASCII(pszString, -1, '?'); } else return CPLStrdup(pszString); } /****************************************************************************** function to output ogr fields in kml args: poOgrFeat pointer to the feature the field is in poOgrLayer pointer to the layer the feature is in poKmlFactory pointer to the libkml dom factory poKmlPlacemark pointer to the placemark to add to returns: nothing env vars: LIBKML_TIMESTAMP_FIELD default: OFTDate or OFTDateTime named timestamp LIBKML_TIMESPAN_BEGIN_FIELD default: OFTDate or OFTDateTime named begin LIBKML_TIMESPAN_END_FIELD default: OFTDate or OFTDateTime named end LIBKML_DESCRIPTION_FIELD default: none LIBKML_NAME_FIELD default: OFTString field named name ******************************************************************************/ void field2kml ( OGRFeature * poOgrFeat, OGRLIBKMLLayer * poOgrLayer, KmlFactory * poKmlFactory, PlacemarkPtr poKmlPlacemark ) { int i; SchemaDataPtr poKmlSchemaData = poKmlFactory->CreateSchemaData ( ); SchemaPtr poKmlSchema = poOgrLayer->GetKmlSchema ( ); /***** set the url to the schema *****/ if ( poKmlSchema && poKmlSchema->has_id ( ) ) { std::string oKmlSchemaID = poKmlSchema->get_id ( ); std::string oKmlSchemaURL = "#"; oKmlSchemaURL.append ( oKmlSchemaID ); poKmlSchemaData->set_schemaurl ( oKmlSchemaURL ); } /***** get the field config *****/ struct fieldconfig oFC; get_fieldconfig( &oFC ); TimeSpanPtr poKmlTimeSpan = NULL; int nFields = poOgrFeat->GetFieldCount ( ); int iSkip1 = -1; int iSkip2 = -1; for ( i = 0; i < nFields; i++ ) { /***** if the field is set to skip, do so *****/ if ( i == iSkip1 || i == iSkip2 ) continue; /***** if the field isn't set just bail now *****/ if ( !poOgrFeat->IsFieldSet ( i ) ) continue; OGRFieldDefn *poOgrFieldDef = poOgrFeat->GetFieldDefnRef ( i ); OGRFieldType type = poOgrFieldDef->GetType ( ); const char *name = poOgrFieldDef->GetNameRef ( ); SimpleDataPtr poKmlSimpleData = NULL; int year, month, day, hour, min, sec, tz; switch ( type ) { case OFTString: // String of ASCII chars { char* pszUTF8String = OGRLIBKMLSanitizeUTF8String( poOgrFeat->GetFieldAsString ( i )); if( pszUTF8String[0] == '\0' ) { CPLFree( pszUTF8String ); continue; } /***** name *****/ if ( EQUAL ( name, oFC.namefield ) ) { poKmlPlacemark->set_name ( pszUTF8String ); CPLFree( pszUTF8String ); continue; } /***** description *****/ else if ( EQUAL ( name, oFC.descfield ) ) { poKmlPlacemark->set_description ( pszUTF8String ); CPLFree( pszUTF8String ); continue; } /***** altitudemode *****/ else if ( EQUAL ( name, oFC.altitudeModefield ) ) { const char *pszAltitudeMode = pszUTF8String ; int isGX = FALSE; int iAltitudeMode = kmldom::ALTITUDEMODE_CLAMPTOGROUND; if ( EQUAL ( pszAltitudeMode, "clampToGround" ) ) iAltitudeMode = kmldom::ALTITUDEMODE_CLAMPTOGROUND; else if ( EQUAL ( pszAltitudeMode, "relativeToGround" ) ) iAltitudeMode = kmldom::ALTITUDEMODE_RELATIVETOGROUND; else if ( EQUAL ( pszAltitudeMode, "absolute" ) ) iAltitudeMode = kmldom::ALTITUDEMODE_ABSOLUTE; else if ( EQUAL ( pszAltitudeMode, "relativeToSeaFloor" ) ) { iAltitudeMode = kmldom::GX_ALTITUDEMODE_RELATIVETOSEAFLOOR; isGX = TRUE; } else if ( EQUAL ( pszAltitudeMode, "clampToSeaFloor" ) ) { iAltitudeMode = kmldom::GX_ALTITUDEMODE_CLAMPTOSEAFLOOR; isGX = TRUE; } if ( poKmlPlacemark->has_geometry ( ) ) { GeometryPtr poKmlGeometry = poKmlPlacemark->get_geometry ( ); ogr2altitudemode_rec ( poKmlGeometry, iAltitudeMode, isGX ); } CPLFree( pszUTF8String ); continue; } /***** timestamp *****/ else if ( EQUAL ( name, oFC.tsfield ) ) { TimeStampPtr poKmlTimeStamp = poKmlFactory->CreateTimeStamp ( ); poKmlTimeStamp->set_when ( pszUTF8String ); poKmlPlacemark->set_timeprimitive ( poKmlTimeStamp ); CPLFree( pszUTF8String ); continue; } /***** begin *****/ if ( EQUAL ( name, oFC.beginfield ) ) { if ( !poKmlTimeSpan ) { poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( ); poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan ); } poKmlTimeSpan->set_begin ( pszUTF8String ); CPLFree( pszUTF8String ); continue; } /***** end *****/ else if ( EQUAL ( name, oFC.endfield ) ) { if ( !poKmlTimeSpan ) { poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( ); poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan ); } poKmlTimeSpan->set_end ( pszUTF8String ); CPLFree( pszUTF8String ); continue; } /***** icon *****/ else if ( EQUAL ( name, oFC.iconfield ) ) { CPLFree( pszUTF8String ); continue; } /***** other *****/ poKmlSimpleData = poKmlFactory->CreateSimpleData ( ); poKmlSimpleData->set_name ( name ); poKmlSimpleData->set_text ( pszUTF8String ); CPLFree( pszUTF8String ); break; } case OFTDate: // Date { poOgrFeat->GetFieldAsDateTime ( i, &year, &month, &day, &hour, &min, &sec, &tz ); int iTimeField; for ( iTimeField = i + 1; iTimeField < nFields; iTimeField++ ) { if ( iTimeField == iSkip1 || iTimeField == iSkip2 ) continue; OGRFieldDefn *poOgrFieldDef2 = poOgrFeat->GetFieldDefnRef ( i ); OGRFieldType type2 = poOgrFieldDef2->GetType ( ); const char *name2 = poOgrFieldDef2->GetNameRef ( ); if ( EQUAL ( name2, name ) && type2 == OFTTime && ( EQUAL ( name, oFC.tsfield ) || EQUAL ( name, oFC.beginfield ) || EQUAL ( name, oFC.endfield ) ) ) { int year2, month2, day2, hour2, min2, sec2, tz2; poOgrFeat->GetFieldAsDateTime ( iTimeField, &year2, &month2, &day2, &hour2, &min2, &sec2, &tz2 ); hour = hour2; min = min2; sec = sec2; tz = tz2; if ( 0 > iSkip1 ) iSkip1 = iTimeField; else iSkip2 = iTimeField; } } goto Do_DateTime; } case OFTTime: // Time { poOgrFeat->GetFieldAsDateTime ( i, &year, &month, &day, &hour, &min, &sec, &tz ); int iTimeField; for ( iTimeField = i + 1; iTimeField < nFields; iTimeField++ ) { if ( iTimeField == iSkip1 || iTimeField == iSkip2 ) continue; OGRFieldDefn *poOgrFieldDef2 = poOgrFeat->GetFieldDefnRef ( i ); OGRFieldType type2 = poOgrFieldDef2->GetType ( ); const char *name2 = poOgrFieldDef2->GetNameRef ( ); if ( EQUAL ( name2, name ) && type2 == OFTTime && ( EQUAL ( name, oFC.tsfield ) || EQUAL ( name, oFC.beginfield ) || EQUAL ( name, oFC.endfield ) ) ) { int year2, month2, day2, hour2, min2, sec2, tz2; poOgrFeat->GetFieldAsDateTime ( iTimeField, &year2, &month2, &day2, &hour2, &min2, &sec2, &tz2 ); year = year2; month = month2; day = day2; if ( 0 > iSkip1 ) iSkip1 = iTimeField; else iSkip2 = iTimeField; } } goto Do_DateTime; } case OFTDateTime: // Date and Time { poOgrFeat->GetFieldAsDateTime ( i, &year, &month, &day, &hour, &min, &sec, &tz ); Do_DateTime: /***** timestamp *****/ if ( EQUAL ( name, oFC.tsfield ) ) { char *timebuf = OGRGetXMLDateTime ( year, month, day, hour, min, sec, tz ); TimeStampPtr poKmlTimeStamp = poKmlFactory->CreateTimeStamp ( ); poKmlTimeStamp->set_when ( timebuf ); poKmlPlacemark->set_timeprimitive ( poKmlTimeStamp ); CPLFree( timebuf ); continue; } /***** begin *****/ if ( EQUAL ( name, oFC.beginfield ) ) { char *timebuf = OGRGetXMLDateTime ( year, month, day, hour, min, sec, tz ); if ( !poKmlTimeSpan ) { poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( ); poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan ); } poKmlTimeSpan->set_begin ( timebuf ); CPLFree( timebuf ); continue; } /***** end *****/ else if ( EQUAL ( name, oFC.endfield ) ) { char *timebuf = OGRGetXMLDateTime ( year, month, day, hour, min, sec, tz ); if ( !poKmlTimeSpan ) { poKmlTimeSpan = poKmlFactory->CreateTimeSpan ( ); poKmlPlacemark->set_timeprimitive ( poKmlTimeSpan ); } poKmlTimeSpan->set_end ( timebuf ); CPLFree( timebuf ); continue; } /***** other *****/ poKmlSimpleData = poKmlFactory->CreateSimpleData ( ); poKmlSimpleData->set_name ( name ); poKmlSimpleData->set_text ( poOgrFeat-> GetFieldAsString ( i ) ); break; } case OFTInteger: // Simple 32bit integer /***** extrude *****/ if ( EQUAL ( name, oFC.extrudefield ) ) { if ( poKmlPlacemark->has_geometry ( ) && -1 < poOgrFeat->GetFieldAsInteger ( i ) ) { GeometryPtr poKmlGeometry = poKmlPlacemark->get_geometry ( ); ogr2extrude_rec ( poOgrFeat->GetFieldAsInteger ( i ), poKmlGeometry ); } continue; } /***** tessellate *****/ if ( EQUAL ( name, oFC.tessellatefield ) ) { if ( poKmlPlacemark->has_geometry ( ) && -1 < poOgrFeat->GetFieldAsInteger ( i ) ) { GeometryPtr poKmlGeometry = poKmlPlacemark->get_geometry ( ); ogr2tessellate_rec ( poOgrFeat->GetFieldAsInteger ( i ), poKmlGeometry ); } continue; } /***** visibility *****/ if ( EQUAL ( name, oFC.visibilityfield ) ) { if ( -1 < poOgrFeat->GetFieldAsInteger ( i ) ) poKmlPlacemark->set_visibility ( poOgrFeat-> GetFieldAsInteger ( i ) ); continue; } /***** icon *****/ else if ( EQUAL ( name, oFC.drawOrderfield ) ) { continue; } /***** other *****/ poKmlSimpleData = poKmlFactory->CreateSimpleData ( ); poKmlSimpleData->set_name ( name ); poKmlSimpleData->set_text ( poOgrFeat->GetFieldAsString ( i ) ); break; case OFTReal: // Double Precision floating point { poKmlSimpleData = poKmlFactory->CreateSimpleData ( ); poKmlSimpleData->set_name ( name ); char* pszStr = CPLStrdup( poOgrFeat->GetFieldAsString ( i ) ); /* Use point as decimal separator */ char* pszComma = strchr(pszStr, ','); if (pszComma) *pszComma = '.'; poKmlSimpleData->set_text ( pszStr ); CPLFree(pszStr); break; } case OFTStringList: // Array of strings case OFTIntegerList: // List of 32bit integers case OFTRealList: // List of doubles case OFTBinary: // Raw Binary data case OFTWideStringList: // deprecated default: /***** other *****/ poKmlSimpleData = poKmlFactory->CreateSimpleData ( ); poKmlSimpleData->set_name ( name ); poKmlSimpleData->set_text ( poOgrFeat->GetFieldAsString ( i ) ); break; } poKmlSchemaData->add_simpledata ( poKmlSimpleData ); } /***** dont add it to the placemark unless there is data *****/ if ( poKmlSchemaData->get_simpledata_array_size ( ) > 0 ) { ExtendedDataPtr poKmlExtendedData = poKmlFactory->CreateExtendedData ( ); poKmlExtendedData->add_schemadata ( poKmlSchemaData ); poKmlPlacemark->set_extendeddata ( poKmlExtendedData ); } return; } /****************************************************************************** recursive function to read altitude mode from the geometry ******************************************************************************/ int kml2altitudemode_rec ( GeometryPtr poKmlGeometry, int *pnAltitudeMode, int *pbIsGX ) { PointPtr poKmlPoint; LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: poKmlPoint = AsPoint ( poKmlGeometry ); if ( poKmlPoint->has_altitudemode ( ) ) { *pnAltitudeMode = poKmlPoint->get_altitudemode ( ); return TRUE; } else if ( poKmlPoint->has_gx_altitudemode ( ) ) { *pnAltitudeMode = poKmlPoint->get_gx_altitudemode ( ); *pbIsGX = TRUE; return TRUE; } break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); if ( poKmlLineString->has_altitudemode ( ) ) { *pnAltitudeMode = poKmlLineString->get_altitudemode ( ); return TRUE; } else if ( poKmlLineString->has_gx_altitudemode ( ) ) { *pnAltitudeMode = poKmlLineString->get_gx_altitudemode ( ); *pbIsGX = TRUE; return TRUE; } break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); if ( poKmlPolygon->has_altitudemode ( ) ) { *pnAltitudeMode = poKmlPolygon->get_altitudemode ( ); return TRUE; } else if ( poKmlPolygon->has_gx_altitudemode ( ) ) { *pnAltitudeMode = poKmlPolygon->get_gx_altitudemode ( ); *pbIsGX = TRUE; return TRUE; } break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { if ( kml2altitudemode_rec ( poKmlMultiGeometry-> get_geometry_array_at ( i ), pnAltitudeMode, pbIsGX ) ) return TRUE; } break; default: break; } return FALSE; } /****************************************************************************** recursive function to read extrude from the geometry ******************************************************************************/ int kml2extrude_rec ( GeometryPtr poKmlGeometry, int *pnExtrude ) { PointPtr poKmlPoint; LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: poKmlPoint = AsPoint ( poKmlGeometry ); if ( poKmlPoint->has_extrude ( ) ) { *pnExtrude = poKmlPoint->get_extrude ( ); return TRUE; } break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); if ( poKmlLineString->has_extrude ( ) ) { *pnExtrude = poKmlLineString->get_extrude ( ); return TRUE; } break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); if ( poKmlPolygon->has_extrude ( ) ) { *pnExtrude = poKmlPolygon->get_extrude ( ); return TRUE; } break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { if ( kml2extrude_rec ( poKmlMultiGeometry-> get_geometry_array_at ( i ), pnExtrude ) ) return TRUE; } break; default: break; } return FALSE; } /****************************************************************************** recursive function to read tessellate from the geometry ******************************************************************************/ int kml2tessellate_rec ( GeometryPtr poKmlGeometry, int *pnTessellate ) { LineStringPtr poKmlLineString; PolygonPtr poKmlPolygon; MultiGeometryPtr poKmlMultiGeometry; size_t nGeom; size_t i; switch ( poKmlGeometry->Type ( ) ) { case kmldom::Type_Point: break; case kmldom::Type_LineString: poKmlLineString = AsLineString ( poKmlGeometry ); if ( poKmlLineString->has_tessellate ( ) ) { *pnTessellate = poKmlLineString->get_tessellate ( ); return TRUE; } break; case kmldom::Type_LinearRing: break; case kmldom::Type_Polygon: poKmlPolygon = AsPolygon ( poKmlGeometry ); if ( poKmlPolygon->has_tessellate ( ) ) { *pnTessellate = poKmlPolygon->get_tessellate ( ); return TRUE; } break; case kmldom::Type_MultiGeometry: poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry ); nGeom = poKmlMultiGeometry->get_geometry_array_size ( ); for ( i = 0; i < nGeom; i++ ) { if ( kml2tessellate_rec ( poKmlMultiGeometry-> get_geometry_array_at ( i ), pnTessellate ) ) return TRUE; } break; default: break; } return FALSE; } /****************************************************************************** function to read kml into ogr fields ******************************************************************************/ void kml2field ( OGRFeature * poOgrFeat, FeaturePtr poKmlFeature ) { /***** get the field config *****/ struct fieldconfig oFC; get_fieldconfig( &oFC ); /***** name *****/ if ( poKmlFeature->has_name ( ) ) { const std::string oKmlName = poKmlFeature->get_name ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.namefield ); if ( iField > -1 ) poOgrFeat->SetField ( iField, oKmlName.c_str ( ) ); } /***** description *****/ if ( poKmlFeature->has_description ( ) ) { const std::string oKmlDesc = poKmlFeature->get_description ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.descfield ); if ( iField > -1 ) poOgrFeat->SetField ( iField, oKmlDesc.c_str ( ) ); } if ( poKmlFeature->has_timeprimitive ( ) ) { TimePrimitivePtr poKmlTimePrimitive = poKmlFeature->get_timeprimitive ( ); /***** timestamp *****/ if ( poKmlTimePrimitive->IsA ( kmldom::Type_TimeStamp ) ) { TimeStampPtr poKmlTimeStamp = AsTimeStamp ( poKmlTimePrimitive ); if ( poKmlTimeStamp->has_when ( ) ) { const std::string oKmlWhen = poKmlTimeStamp->get_when ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.tsfield ); if ( iField > -1 ) { int nYear, nMonth, nDay, nHour, nMinute, nTZ; float fSecond; if ( OGRParseXMLDateTime ( oKmlWhen.c_str ( ), &nYear, &nMonth, &nDay, &nHour, &nMinute, &fSecond, &nTZ ) ) poOgrFeat->SetField ( iField, nYear, nMonth, nDay, nHour, nMinute, ( int )fSecond, nTZ ); } } } /***** timespan *****/ if ( poKmlTimePrimitive->IsA ( kmldom::Type_TimeSpan ) ) { TimeSpanPtr poKmlTimeSpan = AsTimeSpan ( poKmlTimePrimitive ); /***** begin *****/ if ( poKmlTimeSpan->has_begin ( ) ) { const std::string oKmlWhen = poKmlTimeSpan->get_begin ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.beginfield ); if ( iField > -1 ) { int nYear, nMonth, nDay, nHour, nMinute, nTZ; float fSecond; if ( OGRParseXMLDateTime ( oKmlWhen.c_str ( ), &nYear, &nMonth, &nDay, &nHour, &nMinute, &fSecond, &nTZ ) ) poOgrFeat->SetField ( iField, nYear, nMonth, nDay, nHour, nMinute, ( int )fSecond, nTZ ); } } /***** end *****/ if ( poKmlTimeSpan->has_end ( ) ) { const std::string oKmlWhen = poKmlTimeSpan->get_end ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.endfield ); if ( iField > -1 ) { int nYear, nMonth, nDay, nHour, nMinute, nTZ; float fSecond; if ( OGRParseXMLDateTime ( oKmlWhen.c_str ( ), &nYear, &nMonth, &nDay, &nHour, &nMinute, &fSecond, &nTZ ) ) poOgrFeat->SetField ( iField, nYear, nMonth, nDay, nHour, nMinute, ( int )fSecond, nTZ ); } } } } /***** placemark *****/ PlacemarkPtr poKmlPlacemark = AsPlacemark ( poKmlFeature ); GroundOverlayPtr poKmlGroundOverlay = AsGroundOverlay ( poKmlFeature ); if ( poKmlPlacemark && poKmlPlacemark->has_geometry ( ) ) { GeometryPtr poKmlGeometry = poKmlPlacemark->get_geometry ( ); /***** altitudeMode *****/ int bIsGX = FALSE; int nAltitudeMode = -1; int iField = poOgrFeat->GetFieldIndex ( oFC.altitudeModefield ); if ( iField > -1 ) { if ( kml2altitudemode_rec ( poKmlGeometry, &nAltitudeMode, &bIsGX ) ) { if ( !bIsGX ) { switch ( nAltitudeMode ) { case kmldom::ALTITUDEMODE_CLAMPTOGROUND: poOgrFeat->SetField ( iField, "clampToGround" ); break; case kmldom::ALTITUDEMODE_RELATIVETOGROUND: poOgrFeat->SetField ( iField, "relativeToGround" ); break; case kmldom::ALTITUDEMODE_ABSOLUTE: poOgrFeat->SetField ( iField, "absolute" ); break; } } else { switch ( nAltitudeMode ) { case kmldom::GX_ALTITUDEMODE_RELATIVETOSEAFLOOR: poOgrFeat->SetField ( iField, "relativeToSeaFloor" ); break; case kmldom::GX_ALTITUDEMODE_CLAMPTOSEAFLOOR: poOgrFeat->SetField ( iField, "clampToSeaFloor" ); break; } } } } /***** tessellate *****/ int nTessellate = -1; kml2tessellate_rec ( poKmlGeometry, &nTessellate ); iField = poOgrFeat->GetFieldIndex ( oFC.tessellatefield ); if ( iField > -1 ) poOgrFeat->SetField ( iField, nTessellate ); /***** extrude *****/ int nExtrude = -1; kml2extrude_rec ( poKmlGeometry, &nExtrude ); iField = poOgrFeat->GetFieldIndex ( oFC.extrudefield ); if ( iField > -1 ) poOgrFeat->SetField ( iField, nExtrude ); } /***** ground overlay *****/ else if ( poKmlGroundOverlay ) { /***** icon *****/ int iField = poOgrFeat->GetFieldIndex ( oFC.iconfield ); if ( iField > -1 ) { if ( poKmlGroundOverlay->has_icon ( ) ) { IconPtr icon = poKmlGroundOverlay->get_icon ( ); if ( icon->has_href ( ) ) { poOgrFeat->SetField ( iField, icon->get_href ( ).c_str ( ) ); } } } /***** drawOrder *****/ iField = poOgrFeat->GetFieldIndex ( oFC.drawOrderfield ); if ( iField > -1 ) { if ( poKmlGroundOverlay->has_draworder ( ) ) { poOgrFeat->SetField ( iField, poKmlGroundOverlay->get_draworder ( ) ); } } /***** altitudeMode *****/ iField = poOgrFeat->GetFieldIndex ( oFC.altitudeModefield ); if ( iField > -1 ) { if ( poKmlGroundOverlay->has_altitudemode ( ) ) { switch ( poKmlGroundOverlay->get_altitudemode ( ) ) { case kmldom::ALTITUDEMODE_CLAMPTOGROUND: poOgrFeat->SetField ( iField, "clampToGround" ); break; case kmldom::ALTITUDEMODE_RELATIVETOGROUND: poOgrFeat->SetField ( iField, "relativeToGround" ); break; case kmldom::ALTITUDEMODE_ABSOLUTE: poOgrFeat->SetField ( iField, "absolute" ); break; } } else if ( poKmlGroundOverlay->has_gx_altitudemode ( ) ) { switch ( poKmlGroundOverlay->get_gx_altitudemode ( ) ) { case kmldom::GX_ALTITUDEMODE_RELATIVETOSEAFLOOR: poOgrFeat->SetField ( iField, "relativeToSeaFloor" ); break; case kmldom::GX_ALTITUDEMODE_CLAMPTOSEAFLOOR: poOgrFeat->SetField ( iField, "clampToSeaFloor" ); break; } } } } /***** visibility *****/ int nVisibility = -1; if ( poKmlFeature->has_visibility ( ) ) nVisibility = poKmlFeature->get_visibility ( ); int iField = poOgrFeat->GetFieldIndex ( oFC.visibilityfield ); if ( iField > -1 ) poOgrFeat->SetField ( iField, nVisibility ); ExtendedDataPtr poKmlExtendedData = NULL; if ( poKmlFeature->has_extendeddata ( ) ) { poKmlExtendedData = poKmlFeature->get_extendeddata ( ); /***** loop over the schemadata_arrays *****/ size_t nSchemaData = poKmlExtendedData->get_schemadata_array_size ( ); size_t iSchemaData; for ( iSchemaData = 0; iSchemaData < nSchemaData; iSchemaData++ ) { SchemaDataPtr poKmlSchemaData = poKmlExtendedData->get_schemadata_array_at ( iSchemaData ); /***** loop over the simpledata array *****/ size_t nSimpleData = poKmlSchemaData->get_simpledata_array_size ( ); size_t iSimpleData; for ( iSimpleData = 0; iSimpleData < nSimpleData; iSimpleData++ ) { SimpleDataPtr poKmlSimpleData = poKmlSchemaData->get_simpledata_array_at ( iSimpleData ); /***** find the field index *****/ int iField = -1; if ( poKmlSimpleData->has_name ( ) ) { const string oName = poKmlSimpleData->get_name ( ); const char *pszName = oName.c_str ( ); iField = poOgrFeat->GetFieldIndex ( pszName ); } /***** if it has trxt set the field *****/ if ( iField > -1 && poKmlSimpleData->has_text ( ) ) { string oText = poKmlSimpleData->get_text ( ); /* SerializePretty() adds a new line before the data */ /* ands trailing spaces. I believe this is wrong */ /* as it breaks round-tripping */ /* Trim trailing spaces */ while (oText.size() != 0 && oText[oText.size()-1] == ' ') oText.resize(oText.size()-1); /* Skip leading newline and spaces */ const char* pszText = oText.c_str ( ); if (pszText[0] == '\n') pszText ++; while (pszText[0] == ' ') pszText ++; poOgrFeat->SetField ( iField, pszText ); } } } if (nSchemaData == 0 && poKmlExtendedData->get_data_array_size() > 0 ) { int bLaunderFieldNames = CSLTestBoolean(CPLGetConfigOption("LIBKML_LAUNDER_FIELD_NAMES", "YES")); size_t nDataArraySize = poKmlExtendedData->get_data_array_size(); for(size_t i=0; i < nDataArraySize; i++) { const DataPtr& data = poKmlExtendedData->get_data_array_at(i); if (data->has_name() && data->has_value()) { CPLString osName = data->get_name(); if (bLaunderFieldNames) osName = OGRLIBKMLLayer::LaunderFieldNames(osName); int iField = poOgrFeat->GetFieldIndex ( osName ); if (iField >= 0) { poOgrFeat->SetField ( iField, data->get_value().c_str() ); } } } } } } /****************************************************************************** function create a simplefield from a FieldDefn ******************************************************************************/ SimpleFieldPtr FieldDef2kml ( OGRFieldDefn * poOgrFieldDef, KmlFactory * poKmlFactory ) { SimpleFieldPtr poKmlSimpleField = poKmlFactory->CreateSimpleField ( ); const char *pszFieldName = poOgrFieldDef->GetNameRef ( ); poKmlSimpleField->set_name ( pszFieldName ); /***** get the field config *****/ struct fieldconfig oFC; get_fieldconfig( &oFC ); SimpleDataPtr poKmlSimpleData = NULL; switch ( poOgrFieldDef->GetType ( ) ) { case OFTInteger: case OFTIntegerList: if ( EQUAL ( pszFieldName, oFC.tessellatefield ) || EQUAL ( pszFieldName, oFC.extrudefield ) || EQUAL ( pszFieldName, oFC.visibilityfield ) || EQUAL ( pszFieldName, oFC.drawOrderfield ) ) break; poKmlSimpleField->set_type ( "int" ); return poKmlSimpleField; case OFTReal: case OFTRealList: poKmlSimpleField->set_type ( "float" ); return poKmlSimpleField; case OFTBinary: poKmlSimpleField->set_type ( "bool" ); return poKmlSimpleField; case OFTString: case OFTStringList: if ( EQUAL ( pszFieldName, oFC.namefield ) || EQUAL ( pszFieldName, oFC.descfield ) || EQUAL ( pszFieldName, oFC.altitudeModefield ) || EQUAL ( pszFieldName, oFC.iconfield ) ) break; poKmlSimpleField->set_type ( "string" ); return poKmlSimpleField; /***** kml has these types but as timestamp/timespan *****/ case OFTDate: case OFTTime: case OFTDateTime: if ( EQUAL ( pszFieldName, oFC.tsfield ) || EQUAL ( pszFieldName, oFC.beginfield ) || EQUAL ( pszFieldName, oFC.endfield ) ) break; default: poKmlSimpleField->set_type ( "string" ); return poKmlSimpleField; } return NULL; } /****************************************************************************** function to add the simpleFields in a schema to a featuredefn ******************************************************************************/ void kml2FeatureDef ( SchemaPtr poKmlSchema, OGRFeatureDefn * poOgrFeatureDefn ) { size_t nSimpleFields = poKmlSchema->get_simplefield_array_size ( ); size_t iSimpleField; for ( iSimpleField = 0; iSimpleField < nSimpleFields; iSimpleField++ ) { SimpleFieldPtr poKmlSimpleField = poKmlSchema->get_simplefield_array_at ( iSimpleField ); const char *pszType = "string"; string osName = "Unknown"; string osType; if ( poKmlSimpleField->has_type ( ) ) { osType = poKmlSimpleField->get_type ( ); pszType = osType.c_str ( ); } /* FIXME? We cannot set displayname as the field name because in kml2field() we make the */ /* lookup on fields based on their name. We would need some map if we really */ /* want to use displayname, but that might not be a good idea because displayname */ /* may have HTML formatting, which makes it impractical when converting to other */ /* drivers or to make requests */ /* Example: http://www.jasonbirch.com/files/newt_combined.kml */ /*if ( poKmlSimpleField->has_displayname ( ) ) { osName = poKmlSimpleField->get_displayname ( ); } else*/ if ( poKmlSimpleField->has_name ( ) ) { osName = poKmlSimpleField->get_name ( ); } if ( EQUAL ( pszType, "bool" ) || EQUAL ( pszType, "int" ) || EQUAL ( pszType, "short" ) || EQUAL ( pszType, "ushort" ) ) { OGRFieldDefn oOgrFieldName ( osName.c_str(), OFTInteger ); poOgrFeatureDefn->AddFieldDefn ( &oOgrFieldName ); } else if ( EQUAL ( pszType, "float" ) || EQUAL ( pszType, "double" ) || /* a too big uint wouldn't fit in a int, so we map it to OFTReal for now ... */ EQUAL ( pszType, "uint" ) ) { OGRFieldDefn oOgrFieldName ( osName.c_str(), OFTReal ); poOgrFeatureDefn->AddFieldDefn ( &oOgrFieldName ); } else /* string, or any other unrecognized type */ { OGRFieldDefn oOgrFieldName ( osName.c_str(), OFTString ); poOgrFeatureDefn->AddFieldDefn ( &oOgrFieldName ); } } return; } /******************************************************************************* * function to fetch the field config options * *******************************************************************************/ void get_fieldconfig( struct fieldconfig *oFC) { oFC->namefield = CPLGetConfigOption ( "LIBKML_NAME_FIELD", "Name" ); oFC->descfield = CPLGetConfigOption ( "LIBKML_DESCRIPTION_FIELD", "description" ); oFC->tsfield = CPLGetConfigOption ( "LIBKML_TIMESTAMP_FIELD", "timestamp" ); oFC->beginfield = CPLGetConfigOption ( "LIBKML_BEGIN_FIELD", "begin" ); oFC->endfield = CPLGetConfigOption ( "LIBKML_END_FIELD", "end" ); oFC->altitudeModefield = CPLGetConfigOption ( "LIBKML_ALTITUDEMODE_FIELD", "altitudeMode" ); oFC->tessellatefield = CPLGetConfigOption ( "LIBKML_TESSELLATE_FIELD", "tessellate" ); oFC->extrudefield = CPLGetConfigOption ( "LIBKML_EXTRUDE_FIELD", "extrude" ); oFC->visibilityfield = CPLGetConfigOption ( "LIBKML_VISIBILITY_FIELD", "visibility" ); oFC->drawOrderfield = CPLGetConfigOption ( "LIBKML_DRAWORDER_FIELD", "drawOrder" ); oFC->iconfield = CPLGetConfigOption ( "LIBKML_ICON_FIELD", "icon" ); }
47,585
14,471
#include"CreateWindow.h" //setting const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; //camera GLCamera camera(glm::vec3(0.0f, 0.0f, 6.0f)); float lastX = SCR_WIDTH / 2.0f; float lastY = SCR_HEIGHT / 2.0f; bool firstMouse = true; //timing float deltaTime = 0.0f; // time between current frame and last frame float lastTime = 0.0f; GLFWwindow* CreateWindow(unsigned int width, unsigned int height, const char* Title) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef _APPLE_ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // _APPLE_ //glfw:create window GLFWwindow* window = glfwCreateWindow(width, height, Title, NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return nullptr; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, FrameBufferSizeCallback); glfwSetCursorPosCallback(window, MouseCallback); glfwSetScrollCallback(window, ScrollCallback); //tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); //glad if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return nullptr; } return window; } void ProcessInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera.ProcessKeyboard(FORWARD, deltaTime); } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera.ProcessKeyboard(BACKWARD, deltaTime); } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera.ProcessKeyboard(LEFT, deltaTime); } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera.ProcessKeyboard(RIGHT, deltaTime); } if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) { camera.ProcessKeyboard(RISE, deltaTime); } if (glfwGetKey(window, GLFW_KEY_CAPS_LOCK) == GLFW_PRESS) { camera.ProcessKeyboard(FALL, deltaTime); } } void FrameBufferSizeCallback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void MouseCallback(GLFWwindow* window, double xPos, double yPos) { if (firstMouse) { lastX = xPos; lastY = yPos; firstMouse = false; } float xoffset = xPos - lastX; float yoffset = lastY - yPos; lastX = xPos; lastY = yPos; camera.ProcessMouseMovement(xoffset, yoffset); } void ScrollCallback(GLFWwindow* window, double xOffset, double yOffset) { camera.ProcessMouseScroll(yOffset); }
2,768
1,126
// // Copyright (c) Prokura Innovations. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // #include <condition_variable> #include <cstdio> #include <iostream> #include <mutex> #include <queue> #include <string> #include <sstream> // Header file of Socket.IO C ++ Client // Socket.IO C++ Clientのヘッダファイル #include <sio_client.h> class SampleClient { public: // Socket.IOのインスタンス // instance of Socket.IO sio::client client; sio::socket::ptr socket; // Mutexes to synchronize the sio thread with the main thread // sioのスレッドとメインスレッドの同期をとるためのmutex類 std::mutex sio_mutex; std::condition_variable_any sio_cond; // queue for storing sio messages // sioのメッセージを貯めるためのキュー std::queue<sio::message::ptr> sio_queue; bool is_connected = false; // Event listener called when disconnecting // 切断時に呼び出されるイベントリスナ void on_close() { // Disconnected std::cout << "切断しました。" << std::endl; exit(EXIT_FAILURE); } // Event listener called when an error occurs //エラー発生時に呼び出されるイベントリスナ void on_fail() { // There was an error. std::cout << "エラーがありました。" << std::endl; exit(EXIT_FAILURE); } // Event listener called at connection // 接続時に呼び出されるイベントリスナ void on_open() { // There was an error.... std::cout << "Connected" << std::endl; std::unique_lock<std::mutex> lock(sio_mutex); is_connected = true; // Wake up the main thread after the connection process is over // 接続処理が終わったのち、待っているメインスレッドを起こす sio_cond.notify_all(); } // Event listener for "run" command // "run"コマンドのイベントリスナ void on_run(sio::event &e) { std::unique_lock<std::mutex> lock(sio_mutex); sio_queue.push(e.get_message()); // enqueue the event and wake up the waiting main thread // イベントをキューに登録し、待っているメインスレッドを起こす sio_cond.notify_all(); } // Main processing // メイン処理 void run() { // Set listener for connection and error events // 接続およびエラーイベントのリスナを設定する client.set_close_listener(std::bind(&SampleClient::on_close, this)); client.set_fail_listener(std::bind(&SampleClient::on_fail, this)); client.set_open_listener(std::bind(&SampleClient::on_open, this)); // Issue a connection request // 接続要求を出す client.connect("http ://nicwebpage.herokuapp.com/"); { // Wait until the connection process running on another thread ends // 別スレッドで動く接続処理が終わるまで待つ std::unique_lock<std::mutex> lock(sio_mutex); if (!is_connected) { sio_cond.wait(sio_mutex); } } // Register a listener for the "run" command socket = client.socket("JT601"); socket->emit("joinPi"); while (true) { // If the event queue is empty, wait until the queue is refilled // イベントキューが空の場合、キューが補充されるまで待つ // std::unique_lock<std::mutex> lock(sio_mutex); // while (sio_queue.empty()) // { // sio_cond.wait(lock); // } // // Retrieve the registered data from the event queue // // イベントキューから登録されたデータを取り出す // sio::message::ptr recv_data(sio_queue.front()); char output[] = "hello world"; // char buf[1024]; // FILE *fp = nullptr; // get the value of the command member of the object // objectのcommandメンバの値を取得する // std::string command = recv_data->get_map().at("command")->get_string(); std::cout << "run:" << output << std::endl; // Execute command and get the execution result as a string // commandを実行し、実行結果を文字列として取得する // if ((fp = popen(command.c_str(), "r")) != nullptr) // { // while (!feof(fp)) // { // size_t len = fread(buf, 1, sizeof(buf), fp); // output << std::string(buf, len); // } // } // else // { // // If an error is detected, get the error message // // エラーを検出した場合はエラーメッセージを取得する // output << strerror(errno); // } // pclose(fp); sio::message::ptr send_data(sio::object_message::create()); std::map<std::string, sio::message::ptr> &map = send_data->get_map(); // Set the execution result of the command to the output of the object // コマンドの実行結果をobjectのoutputに設定する map.insert(std::make_pair("output", sio::string_message::create(output))); // send sio :: message to server // sio::messageをサーバに送る socket->emit("data", send_data); // remove the processed event from the queue // 処理が終わったイベントをキューから取り除く // sio_queue.pop(); } } }; int main() { // 引数を1つとり、名前とする // Take one argument and name it // if (argc != 2) { // // Specify the connection destination and name as arguments. // std::cerr << "接続先と名前を引数に指定してください。" << std::endl; // exit(EXIT_FAILURE); // } SampleClient client; client.run(); // client.run(argv[1]); return EXIT_SUCCESS; }
5,480
1,980
//----------------------------------------------------// // // // File: Node.cpp // // This scene graph is a basic example for the // // object relational management of the scene // // This is the basic node class // // // // Author: // // Kostas Vardis // // // // These files are provided as part of the BSc course // // of Computer Graphics at the Athens University of // // Economics and Business (AUEB) // // // //----------------------------------------------------// // includes //////////////////////////////////////// #include "../HelpLib.h" // - Library for including GL libraries, checking for OpenGL errors, writing to Output window, etc. #include "Node.h" // - Header file for the Node class // defines ///////////////////////////////////////// // Constructor Node::Node(const char* name): m_name(name), m_parent(nullptr) { } // Destructor Node::~Node() { } void Node::SetName(const char * str) { if (!str) return; m_name = std::string(str); } void Node::Init() { } void Node::Update() { } void Node::Draw() { } const char * Node::GetName() { return m_name.c_str(); } glm::mat4x4 Node::GetTransform() { if (m_parent) return m_parent->GetTransform(); else return glm::mat4x4(1); } glm::vec3 Node::GetWorldPosition() { glm::vec4 p4(0,0,0,1); glm::vec4 result = GetTransform()*p4; return glm::vec3(result/result.w); } // eof ///////////////////////////////// class Node
1,841
497
/* * scout_webots_runner.cpp * * Created on: Sep 18, 2020 11:13 * Description: * * Copyright (c) 2020 Ruixiang Du (rdu) */ #include <signal.h> #include <webots_ros/set_float.h> #include "scout_base/scout_messenger.hpp" #include "scout_webots_sim/scout_webots_runner.hpp" #include "scout_webots_sim/scout_webots_interface.hpp" namespace westonrobot { ScoutWebotsRunner::ScoutWebotsRunner(ros::NodeHandle *nh, ros::NodeHandle *pnh) : nh_(nh), pnh_(pnh) { std::cout << "Creating runner" << std::endl; } void ScoutWebotsRunner::AddExtension( std::shared_ptr<WebotsExtension> extension) { extensions_.push_back(extension); } int ScoutWebotsRunner::Run() { // get the list of availables controllers std::string controllerName; ros::Subscriber name_sub = nh_->subscribe( "model_name", 100, &ScoutWebotsRunner::ControllerNameCallback, this); while (controller_count_ == 0 || controller_count_ < name_sub.getNumPublishers()) { ros::spinOnce(); ros::spinOnce(); ros::spinOnce(); } ros::spinOnce(); // if there is more than one controller available, it let the user choose if (controller_count_ == 1) controllerName = controller_list_[0]; else { int wantedController = 0; std::cout << "Choose the # of the controller you want to use:\n"; std::cin >> wantedController; if (1 <= wantedController && wantedController <= controller_count_) controllerName = controller_list_[wantedController - 1]; else { ROS_ERROR("Invalid number for controller choice."); return 1; } } ROS_INFO("Using controller: '%s'", controllerName.c_str()); name_sub.shutdown(); // fetch parameters before connecting to robot std::string port_name; std::string odom_frame; std::string base_frame; std::string odom_topic_name; bool is_omni_wheel = false; bool is_simulated = false; int sim_rate = 50; bool is_scout_mini = false; pnh_->param<std::string>("port_name", port_name, std::string("can0")); pnh_->param<std::string>("odom_frame", odom_frame, std::string("odom")); pnh_->param<std::string>("base_frame", base_frame, std::string("base_link")); pnh_->param<bool>("is_omni_wheel", is_omni_wheel, false); pnh_->param<bool>("simulated_robot", is_simulated, true); pnh_->param<int>("control_rate", sim_rate, 50); pnh_->param<std::string>("odom_topic_name", odom_topic_name, std::string("odom")); pnh_->param<bool>("is_scout_mini", is_scout_mini, false); std::shared_ptr<ScoutWebotsInterface> robot = std::make_shared<ScoutWebotsInterface>(nh_); // init robot components robot->Initialize(controllerName); if (!extensions_.empty()) { for (auto &ext : extensions_) ext->Setup(nh_, controllerName, static_broadcaster_); } std::unique_ptr<ScoutMessenger<ScoutWebotsInterface>> messenger = std::unique_ptr<ScoutMessenger<ScoutWebotsInterface>>( new ScoutMessenger<ScoutWebotsInterface>(robot, nh_)); messenger->SetOdometryFrame(odom_frame); messenger->SetBaseFrame(base_frame); messenger->SetOdometryTopicName(odom_topic_name); messenger->SetSimulationMode(); messenger->SetupSubscription(); const uint32_t time_step = 1000 / sim_rate; ROS_INFO( "Chosen time step: '%d', make sure you set the same time step in Webots \"basicTimeStep\"" "scene", time_step); ROS_INFO("Entering ROS main loop..."); // main loop time_step_client_ = nh_->serviceClient<webots_ros::set_int>( "/" + controllerName + "/robot/time_step"); time_step_srv_.request.value = time_step; ros::Rate loop_rate(sim_rate); ros::AsyncSpinner spinner(2); spinner.start(); while (ros::ok()) { if (time_step_client_.call(time_step_srv_) && time_step_srv_.response.success) { messenger->Update(); } else { static int32_t error_cnt = 0; ROS_ERROR("Failed to call service time_step for next step."); if (++error_cnt > 50) break; } // ros::spinOnce(); loop_rate.sleep(); } time_step_srv_.request.value = 0; time_step_client_.call(time_step_srv_); spinner.stop(); ros::shutdown(); return 0; } void ScoutWebotsRunner::Stop() { ROS_INFO("User stopped the 'scout_webots_node'."); time_step_srv_.request.value = 0; time_step_client_.call(time_step_srv_); ros::shutdown(); } void ScoutWebotsRunner::ControllerNameCallback( const std_msgs::String::ConstPtr &name) { controller_count_++; controller_list_.push_back(name->data); ROS_INFO("Controller #%d: %s.", controller_count_, controller_list_.back().c_str()); } } // namespace westonrobot
4,632
1,679
/* ========================================================================= */ /* ------------------------------------------------------------------------- */ /*! \file gvznode.cc \date May 2012 \author TNick \brief Contains the implementation of GVzNode class *//* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Please read COPYING and README files in root folder ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* ------------------------------------------------------------------------- */ /* ========================================================================= */ // // // // /* INCLUDES ------------------------------------------------------------ */ #ifdef DE_WITH_GRAPHVIZ #include <dot-editor.h> #include <QDebug> #include <QPainter> #include <QBrush> #include <QPen> #include <QFont> #include <QStyleOptionGraphicsItem> #include <impl/gviz/gvzedge.h> #include "gvznode.h" /* INCLUDES ============================================================ */ // // // // /* DEFINITIONS --------------------------------------------------------- */ /* DEFINITIONS ========================================================= */ // // // // /* DATA ---------------------------------------------------------------- */ /* related to NdShape */ const char * GVzNode::shape_names[] = { "Mcircle", "Mdiamond", "Msquare", "box", "box3d", "circle", "component", "diamond", "doublecircle", "doubleoctagon", "egg", "ellipse", "folder", "hexagon", "house", "invhouse", "invtrapezium", "invtriangle", "none", "note", "octagon", "oval", "parallelogram", "pentagon", "plaintext", "point", "polygon", "rect", "rectangle", "septagon", "square", "tab", "trapezium", "triangle", "tripleoctagon", 0 }; /* DATA ================================================================ */ // // // // /* CLASS --------------------------------------------------------------- */ /* ------------------------------------------------------------------------- */ GVzNode::GVzNode ( QGraphicsItem * fth_g, Agnode_t * node, GVzNode * parent_n ) : QGraphicsItem( fth_g ) { setFlags( ItemIsMovable | ItemIsSelectable | ItemIsFocusable); dot_n_ = node; fth_ = parent_n; st_lst_ = STNONE; updateCachedData(); } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ GVzNode::~GVzNode () { edg_l_.clear(); } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ QString GVzNode::label () const { if (dot_n_ == NULL) return QString(); textlabel_t * tl = ND_label (dot_n_); if (tl == NULL) return QString(); return tl->text; } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ QRectF GVzNode::boundingRect () const { qreal penWidth = 1; qreal w = ND_width( dot_n_ ) * 72; qreal h = ND_height( dot_n_ ) * 72; return QRectF( - ( w / 2 + penWidth / 2 ), - ( h / 2 + penWidth / 2 ), w + penWidth, h + penWidth ); } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ void octogonInRect (QRectF & r, QPointF * pts) { /* 9 POINTS EXPECTED */ qreal x_3 = r.width() / 3; qreal y_3 = r.height() / 3; qreal x_2_3 = x_3 * 2; qreal y_2_3 = y_3 * 2; pts[0].setX (r.left() ); pts[0].setY( r.top() + y_3); pts[1].setX (r.left() + x_3 ); pts[1].setY( r.top()); pts[2].setX (r.left() + x_2_3 ); pts[2].setY( r.top()); pts[3].setX (r.right() ); pts[3].setY( r.top() + y_3); pts[4].setX (r.right() ); pts[4].setY( r.top() + y_2_3); pts[5].setX (r.left() + x_2_3 ); pts[5].setY( r.bottom()); pts[6].setX (r.left() + x_3 ); pts[6].setY( r.bottom()); pts[7].setX (r.left() ); pts[7].setY( r.top() + y_2_3); pts[8] = pts[0]; } /* ========================================================================= */ #define q_agfindattr(a,b) agfindattr( a, const_cast<char *>( b ) ) /* ------------------------------------------------------------------------- */ void GVzNode::paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget ) { Q_UNUSED (option); Q_UNUSED (widget); QPointF pts[16]; QRectF bb2; qreal a; if (dot_n_ == NULL) return; Agsym_t * atr_clr = q_agfindattr (dot_n_, "color"); Agsym_t * atr_fillclr = q_agfindattr (dot_n_, "fillcolor"); Agsym_t * atr_bgcolor = q_agfindattr (dot_n_, "bgcolor"); Agsym_t * atr_style = q_agfindattr (dot_n_, "style"); // Agsym_t * atr_fontcolor = q_agfindattr (dot_n_, "fontcolor"); // Agsym_t * atr_fontname = q_agfindattr (dot_n_, "fontname"); // Agsym_t * atr_fontsize = q_agfindattr (dot_n_, "fontsize"); // Agsym_t * atr_label = q_agfindattr (dot_n_, "label"); char * vl; if (atr_clr != NULL){ vl = agxget (dot_n_, atr_clr->index); painter->setPen (QColor( vl ).toRgb()); } if (atr_fillclr != NULL){ QBrush brs; vl = agxget (dot_n_, atr_fillclr->index); brs.setColor (QColor( vl )); brs.setStyle (Qt:: SolidPattern); painter->setBrush (brs); } if (atr_bgcolor != NULL){ /* ? where to use this? */ vl = agxget (dot_n_, atr_bgcolor->index); } if (atr_style != NULL){ /* ? where to use this? */ vl = agxget (dot_n_, atr_style->index); } QRectF bb = boundingRect(); if (isHighlited()) { painter->setPen (QColor( Qt::red )); painter->setBrush (QBrush( QColor( 0x00, 0xf5, 0xf5, 0x50 ) )); } /* draw based on provided shape */ switch ( shp_ ) { case SHP_RECT: case SHP_RECTANGLE: case SHP_SQUARE: case SHP_BOX: painter->drawRect (bb); break; case SHP_NONE: break; case SHP_MCIRCLE: { a = bb.height() / 8; bb2 = bb.adjusted( a, a, -a, -a); painter->drawEllipse (bb); painter->drawRect (bb2); break;} case SHP_MDIAMOND: case SHP_MSQUARE: { painter->drawRect (bb); pts[0].setX (bb.left() ); pts[0].setY( bb.top()+bb.height()/2); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( pts[0].y()); pts[3].setX (pts[1].x() ); pts[3].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 4); break;} case SHP_CIRCLE: case SHP_ELLIPSE: case SHP_OVAL: case SHP_EGG: painter->drawEllipse (bb); break; case SHP_DOUBLECIRCLE: { a = 2;//bb.width() / 10; bb2 = bb.adjusted( a, a, -a, -a); painter->drawEllipse (bb); painter->drawEllipse (bb2); break;} case SHP_BOX3D: { a = bb.width() / 8; bb2 = bb.adjusted (0, a, -a, 0); painter->drawRect (bb2); pts[0].setX (bb2.left() ); pts[0].setY( bb2.top()); pts[1].setX (bb2.left()+a ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()); pts[3].setX (bb.right() ); pts[3].setY( bb2.bottom()-a); pts[4].setX (bb2.right() ); pts[4].setY( bb2.bottom()); painter->drawPolyline (&pts[0], 5); painter->drawLine (pts[2], bb2.topRight()); break;} case SHP_COMPONENT: { a = bb.width() / 12; bb2 = bb.adjusted (a, 0, 0, 0); painter->drawRect (bb2); bb2 = QRectF (bb.left(), bb.top()+a, a*2, a); painter->drawRect (bb2); bb2.translate (0, bb.height() - a*3); painter->drawRect (bb2); break;} case SHP_DIAMOND: { pts[0].setX (bb.left() ); pts[0].setY( bb.top()+bb.height()/2); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( pts[0].y()); pts[3].setX (pts[1].x() ); pts[3].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 4); break;} case SHP_TRIPLEOCTAGON: { a = bb.height() / 16; bb2 = bb.adjusted (a, a, -a, -a); octogonInRect (bb, &pts[0]); painter->drawPolyline (&pts[0], 9); octogonInRect (bb2, &pts[0]); painter->drawPolyline (&pts[0], 9); bb2 = bb2.adjusted (a, a, -a, -a); octogonInRect (bb2, &pts[0]); painter->drawConvexPolygon (&pts[0], 8); break;} case SHP_DOUBLEOCTAGON: { a = bb.height() / 16; bb2 = bb.adjusted (a, a, -a, -a); octogonInRect (bb, &pts[0]); painter->drawPolyline (&pts[0], 9); octogonInRect (bb2, &pts[0]); painter->drawConvexPolygon (&pts[0], 8); break;} case SHP_OCTAGON: { octogonInRect (bb, &pts[0]); painter->drawConvexPolygon (&pts[0], 8); break;} case SHP_HEXAGON: { a = bb.height() / 2; pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a); pts[1].setX (bb.left()+a ); pts[1].setY( bb.top()); pts[2].setX (bb.right()-a ); pts[2].setY( bb.top()); pts[3].setX (bb.right() ); pts[3].setY( bb.top()+a); pts[4].setX (bb.right()-a ); pts[4].setY( bb.bottom()); pts[5].setX (bb.left()+a ); pts[5].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 6); break;} case SHP_HOUSE: { a = bb.height() / 3; pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()+a); pts[3].setX (bb.right() ); pts[3].setY( bb.bottom()); pts[4].setX (bb.left() ); pts[4].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 5); break;} case SHP_INVHOUSE: { a = bb.height() / 3; pts[0].setX (bb.left() ); pts[0].setY( bb.bottom()-a); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.bottom()); pts[2].setX (bb.right() ); pts[2].setY( bb.bottom()-a); pts[3].setX (bb.right() ); pts[3].setY( bb.top()); pts[4].setX (bb.left() ); pts[4].setY( bb.top()); painter->drawConvexPolygon (&pts[0], 5); break;} case SHP_TRIANGLE: { pts[0].setX (bb.left() ); pts[0].setY( bb.bottom()); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 3); break;} case SHP_INVTRIANGLE: { pts[0].setX (bb.left() ); pts[0].setY( bb.top()); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.bottom()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()); painter->drawConvexPolygon (&pts[0], 3); break;} case SHP_TRAPEZIUM: { a = bb.width() / 8; pts[0].setX (bb.left() ); pts[0].setY( bb.bottom()); pts[1].setX (bb.left()+a ); pts[1].setY( bb.top()); pts[2].setX (bb.right()-a ); pts[2].setY( bb.top()); pts[3].setX (bb.right() ); pts[3].setY( bb.bottom()); pts[4] = pts[0]; painter->drawConvexPolygon (&pts[0], 4); break;} case SHP_INVTRAPEZIUM: { a = bb.width() / 8; pts[0].setX (bb.left() ); pts[0].setY( bb.top()); pts[1].setX (bb.left()+a ); pts[1].setY( bb.bottom()); pts[2].setX (bb.right()-a ); pts[2].setY( bb.bottom()); pts[3].setX (bb.right() ); pts[3].setY( bb.top()); painter->drawConvexPolygon (&pts[0], 4); break;} case SHP_NOTE: { a = bb.width() / 8; pts[0].setX (bb.left() ); pts[0].setY( bb.top()); pts[1].setX (bb.right()-a ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()+a); pts[3].setX (bb.right() ); pts[3].setY( bb.bottom()); pts[4].setX (bb.left() ); pts[4].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 5); pts[3] = pts[2]; pts[2].setX (pts[1].x()); /* y already == to 3.y) */ painter->drawPolyline (&pts[1], 3); break;} case SHP_PLAINTEXT: break; case SHP_PARALLELOGRAM: { a = bb.width() / 8; pts[0].setX (bb.left() ); pts[0].setY( bb.bottom()); pts[1].setX (bb.left()+a ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()); pts[3].setX (bb.right()-a ); pts[3].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 4); break;} case SHP_POLYGON: case SHP_SEPTAGON: { qreal a_1_3 = bb.height() / 3; qreal a_2_3 = a_1_3 * 2; pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a_2_3); pts[1].setX (bb.left()+a_1_3/2 ); pts[1].setY( bb.top()+a_1_3/2); pts[2].setX (bb.left()+bb.width()/2 ); pts[2].setY( bb.top()); pts[3].setX (bb.right()-a_1_3/2 ); pts[3].setY( pts[1].y()); pts[4].setX (bb.right() ); pts[4].setY( pts[0].y()); pts[5].setX (bb.right()-a_1_3 ); pts[5].setY( bb.bottom()); pts[6].setX (bb.left()+a_1_3 ); pts[6].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 7); break;} case SHP_POINT: { painter->drawEllipse (bb); break;} case SHP_PENTAGON: { a = bb.height() / 3; pts[0].setX (bb.left() ); pts[0].setY( bb.top()+a); pts[1].setX (bb.left()+bb.width()/2 ); pts[1].setY( bb.top()); pts[2].setX (bb.right() ); pts[2].setY( bb.top()+a); pts[3].setX (bb.right()-a ); pts[3].setY( bb.bottom()); pts[4].setX (bb.left()+a ); pts[4].setY( bb.bottom()); painter->drawConvexPolygon (&pts[0], 5); break;} case SHP_FOLDER: { qreal a = bb.width() / 8; QRectF bb2 (bb.right()-a*2, bb.top(), a*2, a); painter->drawRect (bb); painter->drawRect (bb2); break;} case SHP_TAB: { qreal a = bb.width() / 8; QRectF bb2 (bb.left(), bb.top(), a*2, a); painter->drawRect (bb); painter->drawRect (bb2); break;} default: painter->drawRoundedRect (bb, 5, 5); } /* the label */ textlabel_t * tl = ND_label (dot_n_); QString lbl = tl->text; if (tl->html) { /** @todo html rendering */ } else { } if (lbl.isEmpty() == false) { painter->setPen (QColor( tl->fontcolor ).toRgb()); QFont f = painter->font(); f.setFamily (tl->fontname); f.setPointSize (tl->fontsize); painter->setFont (f); QTextOption to; to.setWrapMode (QTextOption::WordWrap); Qt::AlignmentFlag align; switch ( tl->valign ) { case 't': align = Qt::AlignTop; break; case 'b': align = Qt::AlignBottom; break; default: align = Qt::AlignVCenter; } /* stuuuuuupid */ align = (Qt::AlignmentFlag) (0x0004 | align); to.setAlignment (align); lbl.replace ("\\N", "\n", Qt::CaseInsensitive); lbl.replace ("\\T", "\t", Qt::CaseInsensitive); lbl.replace ("\\R", "\r", Qt::CaseInsensitive); lbl.replace ("\\\\", "\\"); painter->drawText (bb, lbl, to); } // if (atr_label != NULL){ // vl = agxget (dot_n_, atr_label->index); // if (atr_fontcolor != NULL){ // vl = agxget (dot_n_, atr_fontcolor->index); // painter->setPen (QColor( vl ).toRgb()); // } // if (atr_fontname != NULL){ // vl = agxget (dot_n_, atr_fontname->index); // QFont f = painter->font(); // f.setFamily (vl); // painter->setFont (f); // } // if (atr_fontsize != NULL){ // vl = agxget (dot_n_, atr_fontsize->index); // QFont f = painter->font(); // a = QString (vl ).toDouble( &b_ok); // if (b_ok && ( a > 1 )) // { // f.setPointSize (a); // painter->setFont (f); // } // } } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ void GVzNode::updateCachedData () { if (dot_n_ == NULL) return; /* position */ pointf center = ND_coord (dot_n_); setPos (center.x, -center.y); /* shape */ shape_desc * shp = ND_shape (dot_n_); shp_ = SHP_UDEF; if (shp->usershape == false) { int i; int j; for ( i = 0; ; i++ ) { if (shape_names[i] == NULL) { break; } j = strcmp (shape_names[i], shp->name); if (j == 0) { shp_ = (NdShape)i; break; } else if (j > 0) { break; } } } } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ QList<GVzNode*> GVzNode::nodes () const { QList<GVzNode*> l_nodes; GVzEdge * edg; foreach( edg, edg_l_ ) { GVzNode * nd = edg->destination(); if (nd != NULL) { l_nodes.append (nd); } } return l_nodes; } /* ========================================================================= */ /* ------------------------------------------------------------------------- */ void GVzNode::setHighlite (bool b_sts) { if (b_sts) { st_lst_ = (States) (st_lst_ | ST_HIGHLITE); } else { st_lst_ = (States) (st_lst_ & (~ST_HIGHLITE)); } update(); } /* ========================================================================= */ #endif // DE_WITH_GRAPHVIZ /* CLASS =============================================================== */ // // // // /* ------------------------------------------------------------------------- */ /* ========================================================================= */ /* graph with color */ /* digraph graph_name { node [ style = filled fillcolor = "#FCE975" color ="#ff007f" fontcolor="#005500" ] a -> b } */ /* test graph for node shapes */ /* digraph shapes_test { node_Mcircle [ shape=Mcircle label="Mcircle" ] node_Mdiamond [ shape=Mdiamond label="Mdiamond" ] node_Msquare [ shape=Msquare label="Msquare" ] node_box [ shape=box label="box" ] node_box3d [ shape=box3d label="box3d" ] node_circle [ shape=circle label="circle" ] node_component [ shape=component label="component" ] node_diamond [ shape=diamond label="diamond" ] node_doublecircle [ shape=doublecircle label="doublecircle" ] node_doubleoctagon [ shape=doubleoctagon label="doubleoctagon" ] node_egg [ shape=egg label="egg" ] node_ellipse [ shape=ellipse label="ellipse" ] node_folder [ shape=folder label="folder" ] node_hexagon [ shape=hexagon label="hexagon" ] node_house [ shape=house label="house" ] node_invhouse [ shape=invhouse label="invhouse" ] node_invtrapezium [ shape=invtrapezium label="invtrapezium" ] node_invtriangle [ shape=invtriangle label="invtriangle" ] node_none [ shape=none label="none" ] node_note [ shape=note label="note" ] node_octagon [ shape=octagon label="octagon" ] node_oval [ shape=oval label="oval" ] node_parallelogram [ shape=parallelogram label="parallelogram" ] node_pentagon [ shape=pentagon label="pentagon" ] node_plaintext [ shape=plaintext label="plaintext" ] node_point [ shape=point label="point" ] node_polygon [ shape=polygon label="polygon" ] node_rect [ shape=rect label="rect" ] node_rectangle [ shape=rectangle label="rectangle" ] node_septagon [ shape=septagon label="septagon" ] node_square [ shape=square label="square" ] node_tab [ shape=tab label="tab" ] node_trapezium [ shape=trapezium label="trapezium" ] node_triangle [ shape=triangle label="triangle" ] node_tripleoctagon [ shape=tripleoctagon label="tripleoctagon" ] } */
18,686
8,808
#include "Halide.h" namespace { class Interpolate : public Halide::Generator<Interpolate> { public: GeneratorParam<int> levels_{"levels", 10}; Input<Buffer<float>> input_{"input", 3}; Output<Buffer<float>> output_{"output", 3}; void generate() { Var x("x"), y("y"), c("c"); const int levels = levels_; // Input must have four color channels - rgba input_.dim(2).set_bounds(0, 4); Func downsampled[levels]; Func downx[levels]; Func interpolated[levels]; Func upsampled[levels]; Func upsampledx[levels]; Func clamped = Halide::BoundaryConditions::repeat_edge(input_); downsampled[0](x, y, c) = select(c < 3, clamped(x, y, c) * clamped(x, y, 3), clamped(x, y, 3)); for (int l = 1; l < levels; ++l) { Func prev = downsampled[l-1]; if (l == 4) { // Also add a boundary condition at a middle pyramid level // to prevent the footprint of the downsamplings to extend // too far off the base image. Otherwise we look 512 // pixels off each edge. Expr w = input_.width()/(1 << l); Expr h = input_.height()/(1 << l); prev = lambda(x, y, c, prev(clamp(x, 0, w), clamp(y, 0, h), c)); } downx[l](x, y, c) = (prev(x*2-1, y, c) + 2.0f * prev(x*2, y, c) + prev(x*2+1, y, c)) * 0.25f; downsampled[l](x, y, c) = (downx[l](x, y*2-1, c) + 2.0f * downx[l](x, y*2, c) + downx[l](x, y*2+1, c)) * 0.25f; } interpolated[levels-1](x, y, c) = downsampled[levels-1](x, y, c); for (int l = levels-2; l >= 0; --l) { upsampledx[l](x, y, c) = (interpolated[l+1](x/2, y, c) + interpolated[l+1]((x+1)/2, y, c)) / 2.0f; upsampled[l](x, y, c) = (upsampledx[l](x, y/2, c) + upsampledx[l](x, (y+1)/2, c)) / 2.0f; interpolated[l](x, y, c) = downsampled[l](x, y, c) + (1.0f - downsampled[l](x, y, 3)) * upsampled[l](x, y, c); } Func normalize("normalize"); normalize(x, y, c) = interpolated[0](x, y, c) / interpolated[0](x, y, 3); // Schedule if (auto_schedule) { output_ = normalize; } else { Var yo, yi, xo, xi, ci; if (get_target().has_gpu_feature()) { // Some gpus don't have enough memory to process the entire // image, so we process the image in tiles. // We can't compute the entire output stage at once on the GPU // - it takes too much GPU memory on some of our build bots, // so we wrap the final stage in a CPU stage. Func cpu_wrapper = normalize.in(); cpu_wrapper .reorder(c, x, y) .bound(c, 0, 3) .tile(x, y, xo, yo, xi, yi, input_.width()/4, input_.height()/4) .vectorize(xi, 8); normalize .compute_at(cpu_wrapper, xo) .reorder(c, x, y) .gpu_tile(x, y, xi, yi, 16, 16) .unroll(c); // Start from level 1 to save memory - level zero will be computed on demand for (int l = 1; l < levels; ++l) { int tile_size = 32 >> l; if (tile_size < 1) tile_size = 1; if (tile_size > 8) tile_size = 8; downsampled[l] .compute_root() .gpu_tile(x, y, c, xi, yi, ci, tile_size, tile_size, 4); if (l == 1 || l == 4) { interpolated[l] .compute_at(cpu_wrapper, xo) .gpu_tile(x, y, c, xi, yi, ci, 8, 8, 4); } else { int parent = l > 4 ? 4 : 1; interpolated[l] .compute_at(interpolated[parent], x) .gpu_threads(x, y, c); } } // The cpu wrapper is our new output Func output_ = cpu_wrapper; } else { for (int l = 1; l < levels-1; ++l) { downsampled[l] .compute_root() .parallel(y, 8) .vectorize(x, 4); interpolated[l] .compute_root() .parallel(y, 8) .unroll(x, 2) .unroll(y, 2) .vectorize(x, 8); } normalize .reorder(c, x, y) .bound(c, 0, 3) .unroll(c) .tile(x, y, xi, yi, 2, 2) .unroll(xi) .unroll(yi) .parallel(y, 8) .vectorize(x, 8) .bound(x, 0, input_.width()) .bound(y, 0, input_.height()); output_ = normalize; } } // Estimates (for autoscheduler; ignored otherwise) { input_.dim(0).set_bounds_estimate(0, 1536) .dim(1).set_bounds_estimate(0, 2560) .dim(2).set_bounds_estimate(0, 4); output_.dim(0).set_bounds_estimate(0, 1536) .dim(1).set_bounds_estimate(0, 2560) .dim(2).set_bounds_estimate(0, 3); } } }; } // namespace HALIDE_REGISTER_GENERATOR(Interpolate, interpolate)
5,902
1,972
// SPDX-License-Identifier: Apache-2.0 /** * Copyright (C) 2020 Parichay Kapoor <pk.kapoor@samsung.com> * * @file addition_layer.cpp * @date 30 July 2020 * @see https://github.com/nnstreamer/nntrainer * @author Parichay Kapoor <pk.kapoor@samsung.com> * @bug No known bugs except for NYI items * @brief This is Addition Layer Class for Neural Network * */ #include <addition_layer.h> #include <layer_internal.h> #include <nntrainer_error.h> #include <nntrainer_log.h> #include <parse_util.h> #include <util_func.h> namespace nntrainer { int AdditionLayer::initialize(Manager &manager) { int status = ML_ERROR_NONE; if (getNumInputs() == 0) { ml_loge("Error: number of inputs are not initialized"); return ML_ERROR_INVALID_PARAMETER; } for (unsigned int idx = 0; idx < getNumInputs(); ++idx) { if (input_dim[idx].getDataLen() == 1) { ml_logw("Warning: the length of previous layer dimension is one"); } } /** input dimension indicates the dimension for all the inputs to follow */ output_dim[0] = input_dim[0]; return status; } void AdditionLayer::forwarding(bool training) { Tensor &hidden_ = net_hidden[0]->getVariableRef(); TensorDim &in_dim = input_dim[0]; /** @todo check possibility for in-place of addition layer */ for (unsigned int idx = 0; idx < getNumInputs(); ++idx) { if (in_dim != net_input[idx]->getDim()) throw std::invalid_argument("Error: addition layer requires same " "shape from all input layers"); if (!idx) { hidden_.fill(net_input[idx]->getVariableRef(), false); } else { hidden_.add_i(net_input[idx]->getVariableRef()); } } } void AdditionLayer::calcDerivative() { for (unsigned int i = 0; i < getNumInputs(); ++i) { net_input[i]->getGradientRef() = net_hidden[0]->getGradientRef(); } } void AdditionLayer::setProperty(const PropertyType type, const std::string &value) { int status = ML_ERROR_NONE; switch (type) { case PropertyType::num_inputs: { if (!value.empty()) { unsigned int num_inputs; status = setUint(num_inputs, value); throw_status(status); setNumInputs(num_inputs); } } break; default: LayerV1::setProperty(type, value); break; } } } /* namespace nntrainer */
2,340
811
#ifndef _DOOR_HPP #define _DOOR_HPP #include <string> #include <vector> #include "content.hpp" #include "entity.hpp" namespace duckhero { struct DoorInfo { int x; int y; std::string map; }; class Door : public Entity { private: SDL_Texture * _texture; public: int key_id; bool unlocked; Door(); Door(const Door& other); Door& operator=(const Door& other); ~Door(); std::string GetSpritePath() override; SDL_Rect GetCollisionBox(int x, int y) override; bool CanInteract() override; void Interact(void * level_screen_pointer) override; void Update() override; void Draw(SDL_Renderer * r, int x_offset, int y_offset) override; }; } #endif
684
284
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include <carla/PythonUtil.h> #include <carla/client/Client.h> #include <carla/client/World.h> static void SetTimeout(carla::client::Client &client, double seconds) { client.SetTimeout(TimeDurationFromSeconds(seconds)); } void export_client() { using namespace boost::python; namespace cc = carla::client; class_<cc::Client>("Client", init<std::string, uint16_t, size_t>((arg("host"), arg("port"), arg("worker_threads")=0u))) .def("set_timeout", &::SetTimeout, (arg("seconds"))) .def("get_client_version", &cc::Client::GetClientVersion) .def("get_server_version", CONST_CALL_WITHOUT_GIL(cc::Client, GetServerVersion)) .def("get_world", &cc::Client::GetWorld) ; }
923
320
class Solution { public: void rotateby90(vector<vector<int> >& matrix, int n) { // code here for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { swap(matrix[i][j],matrix[j][i]); } } for(int i=0;i<n;i++) { int j=0,k=n-1; while(j<k) { swap(matrix[j][i],matrix[k][i]); j++;k--; } } } };
501
185
#pragma once #include "dde_x.h" void load_land_coef(std::string &path, std::string sfx, std::vector<DataPoint> &img); void load_land(std::string p, DataPoint &temp); void load_img(std::string p, DataPoint &temp); void load_land(std::string p, DataPoint &temp); void cal_rect(DataPoint &temp); void load_fitting_coef_one(std::string name, DataPoint &temp); void load_bldshps(Eigen::MatrixXf &bldshps, std::string &name, Eigen::VectorXf &ide_sg_vl, std::string sg_vl_path); void load_inner_land_corr(Eigen::VectorXi &cor); void load_jaw_land_corr(Eigen::VectorXi &jaw_cor); void load_slt( std::vector <int> *slt_line, std::vector<std::pair<int, int> > *slt_point_rect, std::string path_slt, std::string path_rect);
749
301
// Copyright (c) 2012 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 "content/renderer/devtools/devtools_agent_filter.h" #include "base/bind.h" #include "content/child/child_process.h" #include "content/common/devtools_messages.h" #include "content/renderer/devtools/devtools_agent.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebDevToolsAgent.h" using blink::WebDevToolsAgent; using blink::WebString; namespace content { namespace { class MessageImpl : public WebDevToolsAgent::MessageDescriptor { public: MessageImpl( const std::string& method, const std::string& message, int routing_id) : method_(method), msg_(message), routing_id_(routing_id) { } ~MessageImpl() override {} WebDevToolsAgent* Agent() override { DevToolsAgent* agent = DevToolsAgent::FromRoutingId(routing_id_); if (!agent) return 0; return agent->GetWebAgent(); } WebString Message() override { return WebString::FromUTF8(msg_); } WebString Method() override { return WebString::FromUTF8(method_); } private: std::string method_; std::string msg_; int routing_id_; }; } // namespace DevToolsAgentFilter::DevToolsAgentFilter() : io_task_runner_(ChildProcess::current()->io_task_runner()), current_routing_id_(0) {} bool DevToolsAgentFilter::OnMessageReceived(const IPC::Message& message) { // Dispatch debugger commands directly from IO. current_routing_id_ = message.routing_id(); IPC_BEGIN_MESSAGE_MAP(DevToolsAgentFilter, message) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DispatchOnInspectorBackend, OnDispatchOnInspectorBackend) IPC_END_MESSAGE_MAP() return false; } DevToolsAgentFilter::~DevToolsAgentFilter() {} void DevToolsAgentFilter::OnDispatchOnInspectorBackend( int session_id, int call_id, const std::string& method, const std::string& message) { if (embedded_worker_routes_.find(current_routing_id_) != embedded_worker_routes_.end()) { return; } if (WebDevToolsAgent::ShouldInterruptForMethod(WebString::FromUTF8(method))) { WebDevToolsAgent::InterruptAndDispatch( session_id, new MessageImpl(method, message, current_routing_id_)); } } void DevToolsAgentFilter::AddEmbeddedWorkerRouteOnMainThread( int32_t routing_id) { io_task_runner_->PostTask( FROM_HERE, base::Bind(&DevToolsAgentFilter::AddEmbeddedWorkerRoute, this, routing_id)); } void DevToolsAgentFilter::RemoveEmbeddedWorkerRouteOnMainThread( int32_t routing_id) { io_task_runner_->PostTask( FROM_HERE, base::Bind(&DevToolsAgentFilter::RemoveEmbeddedWorkerRoute, this, routing_id)); } void DevToolsAgentFilter::AddEmbeddedWorkerRoute(int32_t routing_id) { embedded_worker_routes_.insert(routing_id); } void DevToolsAgentFilter::RemoveEmbeddedWorkerRoute(int32_t routing_id) { embedded_worker_routes_.erase(routing_id); } } // namespace content
3,128
1,004
/* * SPDX-License-Identifier: LGPL-2.0-only * License-Filename: LICENSES/LGPLv2-KDAB * * The KD Tools Library is Copyright (C) 2001-2010 Klaralvdalens Datakonsult AB. */ #include "kdsingleapplicationguard.h" #if QT_VERSION >= 0x040400 || defined(DOXYGEN_RUN) #ifndef QT_NO_SHAREDMEMORY #include "kdsharedmemorylocker.h" #include "kdlockedsharedmemorypointer.h" #include <QVector> #include <QCoreApplication> #include <QSharedMemory> #include <QSharedData> #include <QBasicTimer> #include <QElapsedTimer> #include <QTime> #include <algorithm> #include <limits> #include <cstdlib> #include <cstring> #include <cassert> #ifndef Q_WS_WIN #include <csignal> #include <unistd.h> #endif #ifdef Q_WS_WIN #include <windows.h> #ifndef _SSIZE_T_DEFINED typedef signed int ssize_t; #endif #endif using namespace kdtools; #ifndef KDSINGLEAPPLICATIONGUARD_TIMEOUT_SECONDS #define KDSINGLEAPPLICATIONGUARD_TIMEOUT_SECONDS 10 #endif #ifndef KDSINGLEAPPLICATIONGUARD_NUMBER_OF_PROCESSES #define KDSINGLEAPPLICATIONGUARD_NUMBER_OF_PROCESSES 10 #endif #ifndef KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE #define KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE 32768 #endif static unsigned int KDSINGLEAPPLICATIONGUARD_SHM_VERSION = 0; Q_GLOBAL_STATIC_WITH_ARGS( int, registerInstanceType, (qRegisterMetaType<KDSingleApplicationGuard::Instance>()) ) /*! \class KDSingleApplicationGuard::Instance \relates KDSingleApplicationGuard \ingroup core \brief Information about instances a KDSingleApplicationGuard knows about Instance represents instances of applications under KDSingleApplicationGuard protection, and allows access to their pid() and the arguments() they were started with. */ class KDSingleApplicationGuard::Instance::Private : public QSharedData { friend class ::KDSingleApplicationGuard::Instance; public: Private( const QStringList & args, bool truncated, qint64 pid ) : pid( pid ), arguments( args ), truncated( truncated ) {} private: qint64 pid; QStringList arguments; bool truncated; }; struct ProcessInfo; /*! \internal */ class KDSingleApplicationGuard::Private { friend class ::KDSingleApplicationGuard; friend class ::KDSingleApplicationGuard::Instance; friend struct ::ProcessInfo; KDSingleApplicationGuard * const q; public: Private( Policy policy, KDSingleApplicationGuard* qq ); ~Private(); void create( const QStringList& arguments ); bool checkOperational( const char * function, const char * act ) const; bool checkOperationalPrimary( const char * function, const char * act ) const; struct segmentheader { size_t size : 16; }; static void sharedmem_free( char* ); static char* sharedmem_malloc( size_t size ); private: void shutdownInstance(); void poll(); private: static KDSingleApplicationGuard* primaryInstance; private: QBasicTimer timer; QSharedMemory mem; int id; Policy policy; bool operational; bool exitRequested; }; /*! \internal */ KDSingleApplicationGuard::Instance::Instance( const QStringList & args, bool truncated, qint64 p ) : d( new Private( args, truncated, p ) ) { d->ref.ref(); (void)registerInstanceType(); } /*! Default constructor. Constructs in Instance that is \link isNull() null\endlink. \sa isNull() */ KDSingleApplicationGuard::Instance::Instance() : d( 0 ) {} /*! Copy constructor. */ KDSingleApplicationGuard::Instance::Instance( const Instance & other ) : d( other.d ) { if ( d ) d->ref.ref(); } /*! Destructor. */ KDSingleApplicationGuard::Instance::~Instance() { if ( d && !d->ref.deref() ) delete d; } /*! \fn KDSingleApplicationGuard::Instance::swap( Instance & other ) Swaps the contents of this and \a other. This function never throws exceptions. */ /*! \fn KDSingleApplicationGuard::Instance::operator=( Instance other ) Assigns the contents of \a other to this. This function is strongly exception-safe. */ /*! \fn std::swap( KDSingleApplicationGuard::Instance & lhs, KDSingleApplicationGuard::Instance & rhs ) \relates KDSingleApplicationGuard::Instance Specialisation of std::swap() for KDSingleApplicationGuard::Instance. Calls swap(). */ /*! \fn qSwap( KDSingleApplicationGuard::Instance & lhs, KDSingleApplicationGuard::Instance & rhs ) \relates KDSingleApplicationGuard::Instance Specialisation of qSwap() for KDSingleApplicationGuard::Instance. Calls swap(). */ /*! \fn KDSingleApplicationGuard::Instance::isNull() const Returns whether this instance is null. */ /*! Returns whether this instance is valid. A valid instance is neither null, nor does it have a negative PID. */ bool KDSingleApplicationGuard::Instance::isValid() const { return d && d->pid >= 0 ; } /*! Returns whether the #arguments are complete (\c false) or not (\c true), e.g. because they have been truncated due to limited storage space. \sa arguments() */ bool KDSingleApplicationGuard::Instance::areArgumentsTruncated() const { return d && d->truncated; } /*! Returns the arguments that this instance was started with. \sa areArgumentsTruncated() */ const QStringList & KDSingleApplicationGuard::Instance::arguments() const { if ( d ) return d->arguments; static const QStringList empty; return empty; } /*! Returns the process-id (PID) of this instance. */ qint64 KDSingleApplicationGuard::Instance::pid() const { if ( d ) return d->pid; else return -1; } /*! \class KDSingleApplicationGuard KDSingleApplicationGuard \ingroup core \brief A guard to protect an application from having several instances. KDSingleApplicationGuard can be used to make sure only one instance of an application is running at the same time. \note As KDSingleApplicationGuard currently uses QSharedMemory, Qt 4.4 or later is required. */ /*! \fn void KDSingleApplicationGuard::instanceStarted(const KDSingleApplicationGuard::Instance & instance) This signal is emitted by the primary instance whenever another instance \a instance started. */ /*! \fn void KDSingleApplicationGuard::instanceExited(const KDSingleApplicationGuard::Instance & instance) This signal is emitted by the primary instance whenever another instance \a instance exited. */ /*! \fn void KDSingleApplicationGuard::raiseRequested() This signal is emitted when the current running application is requested to raise its main window. */ /*! \fn void KDSingleApplicationGuard::exitRequested() This signal is emitted when the current running application has been asked to exit by calling kill on the instance. */ /*! \fn void KDSingleApplicationGuard::becamePrimaryInstance() This signal is emitted when the current running application becomes the new primary application. The old primary application has quit. */ /*! \fn void KDSingleApplicationGuard::becameSecondaryInstance() This signal is emmited when the primary instance became secondary instance. This happens when the instance doesn't update its status for some (default 10) seconds. Another instance got primary instance in that case. */ /*! \fn void KDSingleApplicationGuard::policyChanged( KDSingleApplicationGuard::Policy policy ) This signal is emitted when the #policy of the system changes. */ enum Command { NoCommand = 0x00, ExitedInstance = 0x01, NewInstance = 0x02, FreeInstance = 0x04, ShutDownCommand = 0x08, KillCommand = 0x10, BecomePrimaryCommand = 0x20, RaiseCommand = 0x40 }; static const quint16 PrematureEndOfOptions = -1; static const quint16 RegularEndOfOptions = -2; struct ProcessInfo { static const size_t MarkerSize = sizeof(quint16); explicit ProcessInfo( Command c = FreeInstance, const QStringList& arguments = QStringList(), qint64 p = -1 ) : pid( p ), command( c ), timestamp( 0 ), commandline( 0 ) { setArguments( arguments ); } void setArguments( const QStringList & arguments ); QStringList arguments( bool * prematureEnd ) const; qint64 pid; quint32 command; quint32 timestamp; char* commandline; }; static inline bool operator==( const ProcessInfo & lhs, const ProcessInfo & rhs ) { return lhs.command == rhs.command && ( lhs.commandline == rhs.commandline || ( lhs.commandline != 0 && rhs.commandline != 0 && ::strcmp( lhs.commandline, rhs.commandline ) == 0 ) ); } static inline bool operator!=( const ProcessInfo & lhs, const ProcessInfo & rhs ) { return !operator==( lhs, rhs ); } /*! This struct contains information about the managed process system. \internal */ struct InstanceRegister { explicit InstanceRegister( KDSingleApplicationGuard::Policy policy = KDSingleApplicationGuard::NoPolicy ) : policy( policy ), maxInstances( KDSINGLEAPPLICATIONGUARD_NUMBER_OF_PROCESSES ), version( 0 ) { std::fill_n( commandLines, KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE, 0 ); ::memcpy( magicCookie, "kdsingleapp", 12 ); } /*! Returns whether this register was properly initialized by the first instance. */ bool isValid() const { return ::strcmp( magicCookie, "kdsingleapp" ) == 0; } char magicCookie[ 12 ]; unsigned int policy : 8; quint32 maxInstances : 20; unsigned int version : 4; ProcessInfo info[ KDSINGLEAPPLICATIONGUARD_NUMBER_OF_PROCESSES ]; char commandLines[ KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE ]; Q_DISABLE_COPY( InstanceRegister ) }; void ProcessInfo::setArguments( const QStringList & arguments ) { if( commandline != 0 ) KDSingleApplicationGuard::Private::sharedmem_free( commandline ); commandline = 0; if( arguments.isEmpty() ) return; size_t totalsize = MarkerSize; for ( const QString& arg : arguments ) { const QByteArray utf8 = arg.toUtf8(); totalsize += utf8.size() + MarkerSize; } InstanceRegister* const reg = reinterpret_cast<InstanceRegister*>( KDSingleApplicationGuard::Private::primaryInstance->d->mem.data() ); this->commandline = KDSingleApplicationGuard::Private::sharedmem_malloc( totalsize ); if( this->commandline == 0 ) { qWarning("KDSingleApplicationguard: out of memory when trying to save arguments.\n"); return; } char* const commandline = this->commandline + reinterpret_cast<qptrdiff>(reg->commandLines); int argpos = 0; for ( const QString & arg : arguments ) { const QByteArray utf8 = arg.toUtf8(); const int required = MarkerSize + utf8.size() + MarkerSize ; const int available = KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE - argpos ; if ( required > available || utf8.size() > std::numeric_limits<quint16>::max() ) { // write a premature-eoo marker, and quit memcpy( commandline + argpos, &PrematureEndOfOptions, MarkerSize ); argpos += MarkerSize; qWarning( "KDSingleApplicationGuard: argument list is too long (bytes required: %d, used: %d, available: %d", required, argpos - 2, available ); return; } else { const quint16 len16 = utf8.size(); // write the size of the data... memcpy( commandline + argpos, &len16, MarkerSize ); argpos += MarkerSize; // then the data memcpy( commandline + argpos, utf8.data(), len16 ); argpos += len16; } } const ssize_t available = KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE - argpos; assert( available >= static_cast<ssize_t>( MarkerSize ) ); memcpy( commandline + argpos, &RegularEndOfOptions, MarkerSize ); argpos += MarkerSize; } QStringList ProcessInfo::arguments( bool * prematureEnd ) const { QStringList result; if( commandline == 0 ) { if( prematureEnd ) *prematureEnd = true; return result; } InstanceRegister* const reg = reinterpret_cast<InstanceRegister*>( KDSingleApplicationGuard::Private::primaryInstance->d->mem.data() ); const char* const commandline = this->commandline + reinterpret_cast<qptrdiff>(reg->commandLines); int argpos = 0; while ( true ) { const int available = KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE - argpos ; assert( available >= 2 ); quint16 marker; memcpy( &marker, commandline + argpos, MarkerSize ); argpos += MarkerSize; if ( marker == PrematureEndOfOptions ) { if ( prematureEnd ) *prematureEnd = true; break; } if ( marker == RegularEndOfOptions ) { if ( prematureEnd ) *prematureEnd = false; break; } const int requested = MarkerSize + marker + MarkerSize ; if ( requested > available ) { const long long int p = pid; qWarning( "KDSingleApplicationGuard: inconsistency detected when parsing command-line argument for process %lld", p ); if ( prematureEnd ) *prematureEnd = true; break; } result.push_back( QString::fromUtf8( commandline + argpos, marker ) ); argpos += marker; } return result; } KDSingleApplicationGuard::Private::~Private() { if( primaryInstance == q ) primaryInstance = 0; } bool KDSingleApplicationGuard::Private::checkOperational( const char * function, const char * act ) const { assert( function ); assert( act ); if ( !operational ) qWarning( "KDSingleApplicationGuard::%s: need to be operational to %s", function, act ); return operational; } bool KDSingleApplicationGuard::Private::checkOperationalPrimary( const char * function, const char * act ) const { if ( !checkOperational( function, act ) ) return false; if ( id != 0 ) qWarning( "KDSingleApplicationGuard::%s: need to be primary to %s", function, act ); return id == 0; } struct segmentheader { size_t size : 16; }; void KDSingleApplicationGuard::Private::sharedmem_free( char* pointer ) { InstanceRegister* const reg = reinterpret_cast<InstanceRegister*>( KDSingleApplicationGuard::Private::primaryInstance->d->mem.data() ); char* const heap = reg->commandLines; char* const heap_ptr = heap + reinterpret_cast<qptrdiff>(pointer) - sizeof( segmentheader ); const segmentheader* const header = reinterpret_cast< const segmentheader* >( heap_ptr ); const size_t size = header->size; char* end = heap + KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE; std::copy( heap_ptr + size, end, heap_ptr ); std::fill( end - size, end, 0 ); for( uint i = 0; i < reg->maxInstances; ++i ) { if( reg->info[ i ].commandline > pointer ) reg->info[ i ].commandline -= size + sizeof( segmentheader ); } } char* KDSingleApplicationGuard::Private::sharedmem_malloc( size_t size ) { InstanceRegister* const reg = reinterpret_cast<InstanceRegister*>( KDSingleApplicationGuard::Private::primaryInstance->d->mem.data() ); char* heap = reg->commandLines; while( heap + sizeof( segmentheader ) + size < reg->commandLines + KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE ) { segmentheader* const header = reinterpret_cast< segmentheader* >( heap ); if( header->size == 0 ) { header->size = size; return heap + sizeof( segmentheader ) - reinterpret_cast<qptrdiff>(reg->commandLines); } heap += sizeof( header ) + header->size; } return 0; } void KDSingleApplicationGuard::Private::shutdownInstance() { KDLockedSharedMemoryPointer< InstanceRegister > instances( &q->d->mem ); instances->info[ q->d->id ].command |= ExitedInstance; if( q->isPrimaryInstance() ) { // ohh... we need a new primary instance... for ( int i = 1, end = instances->maxInstances ; i < end ; ++i ) { if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance | ShutDownCommand | KillCommand ) ) == 0 ) { instances->info[ i ].command |= BecomePrimaryCommand; return; } } // none found? then my species is dead :-( } } KDSingleApplicationGuard* KDSingleApplicationGuard::Private::primaryInstance = 0; /*! Requests that the instance kills itself (by emitting exitRequested). If the instance has since exited, does nothing. \sa shutdown(), raise() */ void KDSingleApplicationGuard::Instance::kill() { KDLockedSharedMemoryPointer< InstanceRegister > instances( &KDSingleApplicationGuard::Private::primaryInstance->d->mem ); for ( int i = 0, end = instances->maxInstances ; i < end ; ++i ) { if( instances->info[ i ].pid != d->pid ) continue; if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance ) ) == 0 ) instances->info[ i ].command = KillCommand; } } /*! Requests that the instance shuts itself down (by calling QCoreApplication::quit()). If the instance has since exited, does nothing. \sa kill(), raise() */ void KDSingleApplicationGuard::Instance::shutdown() { KDLockedSharedMemoryPointer< InstanceRegister > instances( &KDSingleApplicationGuard::Private::primaryInstance->d->mem ); for ( int i = 0, end = instances->maxInstances ; i < end ; ++i ) { if( instances->info[ i ].pid != d->pid ) continue; if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance ) ) == 0 ) instances->info[ i ].command = ShutDownCommand; } } /*! Requests that the instance raises its main window. The effects are implementation-defined: the KDSingleApplicationGuard corresponding to the instance will emit its \link KDSingleApplicationGuard::raiseRequested() raiseRequested()\endlink signal. If the instance has since exited, does nothing. \sa kill(), shutdown() */ void KDSingleApplicationGuard::Instance::raise() { KDLockedSharedMemoryPointer< InstanceRegister > instances( &KDSingleApplicationGuard::Private::primaryInstance->d->mem ); for ( int i = 0, end = instances->maxInstances ; i < end ; ++i ) { if( instances->info[ i ].pid != d->pid ) continue; if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance ) ) == 0 ) instances->info[ i ].command = RaiseCommand; } } #ifndef Q_WS_WIN // static void KDSingleApplicationGuard::SIGINT_handler( int sig ) { if( sig == SIGINT && Private::primaryInstance != 0 ) Private::primaryInstance->d->shutdownInstance(); ::exit( 1 ); } #endif /*! \enum KDSingleApplicationGuard::Policy Defines the policy that a KDSingleApplicationGuard can enforce: */ /*! \var KDSingleApplicationGuard::NoPolicy instanceStarted() is emitted, and the new instance allowed to continue. */ /*! \var KDSingleApplicationGuard::AutoKillOtherInstances instanceStarted() is emitted, and the new instance is killed (Instance::kill()). */ /*! Creates a new KDSingleApplicationGuard with arguments QCoreApplication::arguments() and policy AutoKillOtherInstances, passing \a parent to the base class constructor, as usual. */ KDSingleApplicationGuard::KDSingleApplicationGuard( QObject * parent ) : QObject( parent ), d( new Private( AutoKillOtherInstances, this ) ) { d->create( QCoreApplication::arguments() ); } /*! Creates a new KDSingleApplicationGuard with arguments QCoreApplication::arguments() and policy \a policy, passing \a parent to the base class constructor, as usual. */ KDSingleApplicationGuard::KDSingleApplicationGuard( Policy policy, QObject * parent ) : QObject( parent ), d( new Private( policy, this ) ) { d->create( QCoreApplication::arguments() ); } /*! Creates a new KDSingleApplicationGuard with arguments \a arguments and policy AutoKillOtherInstances, passing \a parent to the base class constructor, as usual. */ KDSingleApplicationGuard::KDSingleApplicationGuard( const QStringList & arguments, QObject * parent ) : QObject( parent ), d( new Private( AutoKillOtherInstances, this ) ) { d->create( arguments ); } /*! Creates a new KDSingleApplicationGuard with arguments \a arguments and policy \a policy, passing \a parent to the base class constructor, as usual. */ KDSingleApplicationGuard::KDSingleApplicationGuard( const QStringList & arguments, Policy policy, QObject * parent ) : QObject( parent ), d( new Private( policy, this ) ) { d->create( arguments ); } KDSingleApplicationGuard::Private::Private( Policy policy_, KDSingleApplicationGuard * qq ) : q( qq ), id( -1 ), policy( policy_ ), operational( false ), exitRequested( false ) { } void KDSingleApplicationGuard::Private::create( const QStringList & arguments ) { if ( !QCoreApplication::instance() ) { qWarning( "KDSingleApplicationGuard: you need to construct a Q(Core)Application before you can construct a KDSingleApplicationGuard" ); return; } const QString name = QCoreApplication::applicationName(); if ( name.isEmpty() ) { qWarning( "KDSingleApplicationGuard: QCoreApplication::applicationName must not be empty" ); return; } (void)registerInstanceType(); if ( primaryInstance == 0 ) primaryInstance = q; mem.setKey( name ); // if another instance crashed, the shared memory segment is still there on Unix // the following lines trigger deletion in that case #ifndef Q_WS_WIN mem.attach(); mem.detach(); #endif const bool created = mem.create( sizeof( InstanceRegister ) ); if( !created ) { QString errorMsg; if( mem.error() != QSharedMemory::NoError && mem.error() != QSharedMemory::AlreadyExists ) errorMsg += QString::fromLatin1( "QSharedMemomry::create() failed: %1" ).arg( mem.errorString() ); if( !mem.attach() ) { if( mem.error() != QSharedMemory::NoError ) errorMsg += QString::fromLatin1( "QSharedMemomry::attach() failed: %1" ).arg( mem.errorString() ); qWarning( "KDSingleApplicationGuard: Could neither create nor attach to shared memory segment." ); qWarning( "%s\n", errorMsg.toLocal8Bit().constData() ); return; } const int maxWaitMSecs = 1000 * 60; // stop waiting after 60 seconds QElapsedTimer waitTimer; waitTimer.start(); // lets wait till the other instance initialized the register bool initialized = false; while( !initialized && waitTimer.elapsed() < maxWaitMSecs ) { const KDLockedSharedMemoryPointer< InstanceRegister > instances( &mem ); initialized = instances->isValid(); #ifdef Q_WS_WIN ::Sleep(20); #else usleep(20000); #endif } const KDLockedSharedMemoryPointer< InstanceRegister > instances( &mem ); if ( instances->version != 0 ) { qWarning( "KDSingleApplicationGuard: Detected version mismatch. " "Highest supported version: %ud, actual version: %ud", KDSINGLEAPPLICATIONGUARD_SHM_VERSION, instances->version ); return; } } KDLockedSharedMemoryPointer< InstanceRegister > instances( &mem ); if( !created ) { assert( instances->isValid() ); // we're _not_ the first instance // but the bool killOurSelf = false; // find a new slot... id = std::find( instances->info, instances->info + instances->maxInstances, ProcessInfo() ) - instances->info; ProcessInfo& info = instances->info[ id ]; info = ProcessInfo( NewInstance, arguments, QCoreApplication::applicationPid() ); killOurSelf = instances->policy == AutoKillOtherInstances; policy = static_cast<Policy>( instances->policy ); // but the signal that we tried to start was sent to the primary application if( killOurSelf ) exitRequested = true; } else { // ok.... we are the first instance new ( instances.get() ) InstanceRegister( policy ); // create a new list (in shared memory) id = 0; // our id = 0 // and we've no command instances->info[ 0 ] = ProcessInfo( NoCommand, arguments, QCoreApplication::applicationPid() ); } #ifndef Q_WS_WIN ::signal( SIGINT, SIGINT_handler ); #endif // now listen for commands timer.start( 750, q ); operational = true; } /*! Destroys this SingleApplicationGuard. If this instance has been the primary instance and no other instance is existing anymore, the application is shut down completely. Otherwise the destructor selects another instance to be the primary instances. */ KDSingleApplicationGuard::~KDSingleApplicationGuard() { if( d->id == -1 ) return; d->shutdownInstance(); } /*! \property KDSingleApplicationGuard::operational Contains whether this KDSingleApplicationGuard is operational. A non-operational KDSingleApplicationGuard cannot be used in any meaningful way. Reasons for a KDSingleApplicationGuard being non-operational include: \li it was constructed before QApplication (or at least QCoreApplication) was constructed \li it failed to create or attach to the shared memory segment that is used for communication Get this property's value using %isOperational(). */ bool KDSingleApplicationGuard::isOperational() const { return d->operational; } /*! \property KDSingleApplicationGuard::exitRequested Contains wheter this istance has been requested to exit. This will happen when this instance was just started, but the policy is AutoKillOtherInstances or by explicitely calling kill on this instance(). Get this property's value using %isExitRequested(). */ bool KDSingleApplicationGuard::isExitRequested() const { return d->exitRequested; }; /*! \property KDSingleApplicationGuard::primaryInstance Contains whether this instance is the primary instance. The primary instance is the first instance which was started or else the instance which got selected by KDSingleApplicationGuard's destructor, when the primary instance was shut down. Get this property's value using %isPrimaryInstance(), and monitor changes to it using becamePrimaryInstance(). */ bool KDSingleApplicationGuard::isPrimaryInstance() const { return d->id == 0; } /*! \property KDSingleApplicationGuard::policy Specifies the policy KDSingleApplicationGuard is using when new instances are started. This can only be set in the primary instance. Get this property's value using %policy(), set it using %setPolicy(), and monitor changes to it using policyChanged(). */ KDSingleApplicationGuard::Policy KDSingleApplicationGuard::policy() const { return d->policy; } void KDSingleApplicationGuard::setPolicy( Policy policy ) { if ( !d->checkOperationalPrimary( "setPolicy", "change the policy" ) ) return; if( d->policy == policy ) return; d->policy = policy; emit policyChanged( policy ); KDLockedSharedMemoryPointer< InstanceRegister > instances( &d->mem ); instances->policy = policy; } /*! Returns a list of all currently running instances. */ QVector<KDSingleApplicationGuard::Instance> KDSingleApplicationGuard::instances() const { if ( !d->checkOperational( "instances", "report on other instances" ) ) return QVector<Instance>(); if ( Private::primaryInstance == 0 ) { Private::primaryInstance = const_cast<KDSingleApplicationGuard*>( this ); } QVector<Instance> result; const KDLockedSharedMemoryPointer< InstanceRegister > instances( const_cast< QSharedMemory* >( &d->mem ) ); for ( int i = 0, end = instances->maxInstances ; i < end ; ++i ) { const ProcessInfo& info = instances->info[ i ]; if( ( info.command & ( FreeInstance | ExitedInstance ) ) == 0 ) { bool truncated; const QStringList arguments = info.arguments( &truncated ); result.push_back( Instance( arguments, truncated, info.pid ) ); } } return result; } /*! Shuts down all other instances. This can only be called from the the primary instance. Shut down is done gracefully via QCoreApplication::quit(). */ void KDSingleApplicationGuard::shutdownOtherInstances() { if ( !d->checkOperationalPrimary( "shutdownOtherInstances", "shut other instances down" ) ) return; KDLockedSharedMemoryPointer< InstanceRegister > instances( &d->mem ); for ( int i = 1, end = instances->maxInstances ; i < end ; ++i ) { if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance ) ) == 0 ) instances->info[ i ].command = ShutDownCommand; } } /*! Kills all other instances. This can only be called from the the primary instance. Killing is done via emitting exitRequested. It's up to the receiving instance to react properly. */ void KDSingleApplicationGuard::killOtherInstances() { if ( !d->checkOperationalPrimary( "killOtherInstances", "kill other instances" ) ) return; KDLockedSharedMemoryPointer< InstanceRegister > instances( &d->mem ); for ( int i = 1, end = instances->maxInstances ; i < end ; ++i ) { if( ( instances->info[ i ].command & ( FreeInstance | ExitedInstance ) ) == 0 ) instances->info[ i ].command = KillCommand; } } bool KDSingleApplicationGuard::event( QEvent * event ) { if ( event->type() == QEvent::Timer ) { const QTimerEvent * const te = static_cast<QTimerEvent*>( event ); if ( te->timerId() == d->timer.timerId() ) { d->poll(); return true; } } return QObject::event( event ); } void KDSingleApplicationGuard::Private::poll() { const quint32 now = QDateTime::currentDateTime().toTime_t(); if ( primaryInstance == 0 ) { primaryInstance = q; } if ( q->isPrimaryInstance() ) { // only the primary instance will get notified about new instances QVector< Instance > exitedInstances; QVector< Instance > startedInstances; { KDLockedSharedMemoryPointer< InstanceRegister > instances( &mem ); if( instances->info[ id ].pid != QCoreApplication::applicationPid() ) { for ( int i = 1, end = instances->maxInstances ; i < end && id == 0 ; ++i ) { if( instances->info[ i ].pid == QCoreApplication::applicationPid() ) id = i; } emit q->becameSecondaryInstance(); return; } instances->info[ id ].timestamp = now; for ( int i = 1, end = instances->maxInstances ; i < end ; ++i ) { ProcessInfo& info = instances->info[ i ]; if( info.command & NewInstance ) { bool truncated; const QStringList arguments = info.arguments( &truncated ); startedInstances.push_back( Instance( arguments, truncated, info.pid ) ); info.command &= ~NewInstance; // clear NewInstance flag } if( info.command & ExitedInstance ) { bool truncated; const QStringList arguments = info.arguments( &truncated ); exitedInstances.push_back( Instance( arguments, truncated, info.pid ) ); info.command = FreeInstance; // set FreeInstance flag } } } // one signal for every new instance - _after_ the memory segment was unlocked again for( QVector< Instance >::const_iterator it = startedInstances.constBegin(); it != startedInstances.constEnd(); ++it ) emit q->instanceStarted( *it ); for( QVector< Instance >::const_iterator it = exitedInstances.constBegin(); it != exitedInstances.constEnd(); ++it ) emit q->instanceExited( *it ); } else { // do we have a command? bool killOurSelf = false; bool shutDownOurSelf = false; bool policyDidChange = false; { KDLockedSharedMemoryPointer< InstanceRegister > instances( &mem ); const Policy oldPolicy = policy; policy = static_cast<Policy>( instances->policy ); policyDidChange = policy != oldPolicy; // check for the primary instance health status if( now - instances->info[ 0 ].timestamp > KDSINGLEAPPLICATIONGUARD_TIMEOUT_SECONDS ) { std::swap( instances->info[ 0 ], instances->info[ id ] ); id = 0; instances->info[ id ].timestamp = now; emit q->becamePrimaryInstance(); instances->info[ id ].command &= ~BecomePrimaryCommand; // afterwards, reset the flag } if( instances->info[ id ].command & BecomePrimaryCommand ) { // we became primary! instances->info[ 0 ] = instances->info[ id ]; instances->info[ id ] = ProcessInfo(); // change our id to 0 and declare the old slot as free id = 0; instances->info[ id ].timestamp = now; emit q->becamePrimaryInstance(); } if( instances->info[ id ].command & RaiseCommand ) { // raise ourself! emit q->raiseRequested(); instances->info[ id ].command &= ~RaiseCommand; // afterwards, reset the flag } killOurSelf = instances->info[ id ].command & KillCommand; // check for kill command shutDownOurSelf = instances->info[ id ].command & ShutDownCommand; // check for shut down command instances->info[ id ].command &= ~( KillCommand | ShutDownCommand | BecomePrimaryCommand ); // reset both flags if( killOurSelf ) { instances->info[ id ].command |= ExitedInstance; // upon kill, we have to set the ExitedInstance flag id = -1; // becauso our d'tor won't be called anymore } } if( killOurSelf ) // kill our self takes precedence { exitRequested = true; emit q->exitRequested(); } else if( shutDownOurSelf ) qApp->quit(); else if( policyDidChange ) emit q->policyChanged( policy ); } } #include "moc_kdsingleapplicationguard.cpp" #ifdef KDTOOLSCORE_UNITTESTS #include <kdunittest/test.h> #include "kdautopointer.h" #include <iostream> #include <QtCore/QTime> #include <QtCore/QUuid> #include <QtTest/QSignalSpy> static void wait( int msec, QSignalSpy * spy=0, int expectedCount=INT_MAX ) { QTime t; t.start(); while ( ( !spy || spy->count() < expectedCount ) && t.elapsed() < msec ) { qApp->processEvents( QEventLoop::WaitForMoreEvents, qMax( 10, msec - t.elapsed() ) ); } } static std::ostream& operator<<( std::ostream& stream, const QStringList& list ) { stream << "QStringList("; for( QStringList::const_iterator it = list.begin(); it != list.end(); ++it ) { stream << " " << it->toLocal8Bit().data(); if( it + 1 != list.end() ) stream << ","; } stream << " )"; return stream; } namespace { class ApplicationNameSaver { Q_DISABLE_COPY( ApplicationNameSaver ) const QString oldname; public: explicit ApplicationNameSaver( const QString & name ) : oldname( QCoreApplication::applicationName() ) { QCoreApplication::setApplicationName( name ); } ~ApplicationNameSaver() { QCoreApplication::setApplicationName( oldname ); } }; } KDAB_UNITTEST_SIMPLE( KDSingleApplicationGuard, "kdcoretools" ) { // set it to an unique name const ApplicationNameSaver saver( QUuid::createUuid().toString() ); KDAutoPointer<KDSingleApplicationGuard> guard3; KDAutoPointer<QSignalSpy> spy3; KDAutoPointer<QSignalSpy> spy4; { KDSingleApplicationGuard guard1; assertEqual( guard1.policy(), KDSingleApplicationGuard::AutoKillOtherInstances ); assertEqual( guard1.instances().count(), 1 ); assertTrue( guard1.isPrimaryInstance() ); guard1.setPolicy( KDSingleApplicationGuard::NoPolicy ); assertEqual( guard1.policy(), KDSingleApplicationGuard::NoPolicy ); QSignalSpy spy1( &guard1, SIGNAL(instanceStarted(KDSingleApplicationGuard::Instance)) ); KDSingleApplicationGuard guard2; assertEqual( guard1.instances().count(), 2 ); assertEqual( guard2.instances().count(), 2 ); assertEqual( guard2.policy(), KDSingleApplicationGuard::NoPolicy ); assertFalse( guard2.isPrimaryInstance() ); wait( 1000, &spy1, 1 ); assertEqual( spy1.count(), 1 ); guard3.reset( new KDSingleApplicationGuard ); spy3.reset( new QSignalSpy( guard3.get(), SIGNAL(becamePrimaryInstance()) ) ); spy4.reset( new QSignalSpy( guard3.get(), SIGNAL(instanceExited(KDSingleApplicationGuard::Instance) ) ) ); assertFalse( guard3->isPrimaryInstance() ); } wait( 1000, spy3.get(), 1 ); wait( 1000, spy4.get(), 1 ); assertEqual( spy3->count(), 1 ); assertEqual( guard3->instances().count(), 1 ); assertTrue( guard3->isPrimaryInstance() ); guard3.reset( new KDSingleApplicationGuard ); assertEqual( guard3->instances().first().arguments(), qApp->arguments() ); QSignalSpy spyStarted( guard3.get(), SIGNAL(instanceStarted(KDSingleApplicationGuard::Instance)) ); QSignalSpy spyExited( guard3.get(), SIGNAL(instanceExited(KDSingleApplicationGuard::Instance)) ); { KDSingleApplicationGuard guard1; KDSingleApplicationGuard guard2; wait( 1000, &spyStarted, 2 ); assertEqual( spyStarted.count(), 2 ); } wait( 1000, &spyExited, 2 ); assertEqual( spyExited.count(), 2 ); spyStarted.clear(); spyExited.clear(); { // check arguments-too-long handling: QStringList args; for ( unsigned int i = 0, end = KDSINGLEAPPLICATIONGUARD_MAX_COMMAND_LINE/16 ; i != end ; ++i ) args.push_back( QLatin1String( "0123456789ABCDEF" ) ); KDSingleApplicationGuard guard3( args ); wait( 1000, &spyStarted, 1 ); const QVector<KDSingleApplicationGuard::Instance> instances = guard3.instances(); assertEqual( instances.size(), 2 ); assertTrue( instances[1].areArgumentsTruncated() ); } } #endif // KDTOOLSCORE_UNITTESTS #endif // QT_NO_SHAREDMEMORY #endif // QT_VERSION >= 0x040400 || defined(DOXYGEN_RUN)
39,201
11,890
// Selection Sort using C++ // Author : Abhishek Sharma #include<iostream> using std::cout; using std::cin; using std::endl; void insertionsort(int p[],int no_of_steps,int n) { int min_ele; int addr; int temp; for (int i = 0; i<no_of_steps; ++i) { min_ele = p[i]; addr = i; for(int j=i+1;j<n;++j) { if (p[j]<min_ele) { min_ele = p[j]; addr = j; } } temp = p[i]; p[i] = p[addr]; p[addr] = temp; } } int main() { int n,no_of_steps; cin>>n>>no_of_steps; int a[n]; for(int i=0;i<n;++i) { cin>>a[i]; } // cout<<"output:"<<endl<<endl; // for(int i=0;i<n;++i) // { // cout<<a[i]<<' '; // } insertionsort(a,no_of_steps,n); for(int i=0;i<n;++i) { cout<<a[i]<<' '; } return 0; }
936
414
/************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //************************************************************************* // Class AliNormalizationCounter // Class to store the informations relevant for the normalization in the // barrel for each run // Authors: G. Ortona, ortona@to.infn.it // D. Caffarri, davide.caffarri@pd.to.infn.it // with many thanks to P. Pillot ///////////////////////////////////////////////////////////// #include "AliLog.h" #include "AliNormalizationCounter.h" #include <AliESDEvent.h> #include <AliESDtrack.h> #include <AliAODEvent.h> #include <AliAODVZERO.h> #include <AliVParticle.h> #include <AliTriggerAnalysis.h> #include <TH1F.h> #include <TH2F.h> #include <TList.h> #include <TObjArray.h> #include <TString.h> #include <TCanvas.h> #include <AliPhysicsSelection.h> #include <AliMultiplicity.h> /// \cond CLASSIMP ClassImp(AliNormalizationCounter); /// \endcond //____________________________________________ AliNormalizationCounter::AliNormalizationCounter(): TNamed(), fCounters(), fESD(kFALSE), fMultiplicity(kFALSE), fMultiplicityEtaRange(1.0), fSpherocity(kFALSE), fSpherocitySteps(100.), fHistTrackFilterEvMult(0), fHistTrackAnaEvMult(0), fHistTrackFilterSpdMult(0), fHistTrackAnaSpdMult(0) { // empty constructor } //__________________________________________________ AliNormalizationCounter::AliNormalizationCounter(const char *name): TNamed(name,name), fCounters(name), fESD(kFALSE), fMultiplicity(kFALSE), fMultiplicityEtaRange(1.0), fSpherocity(kFALSE), fSpherocitySteps(100.), fHistTrackFilterEvMult(0), fHistTrackAnaEvMult(0), fHistTrackFilterSpdMult(0), fHistTrackAnaSpdMult(0) { ; } //______________________________________________ AliNormalizationCounter::~AliNormalizationCounter() { //destructor if(fHistTrackFilterEvMult){ delete fHistTrackFilterEvMult; fHistTrackFilterEvMult =0; } if(fHistTrackAnaEvMult){ delete fHistTrackAnaEvMult; fHistTrackAnaEvMult=0; } if(fHistTrackFilterSpdMult){ delete fHistTrackFilterSpdMult; fHistTrackFilterSpdMult=0; } if(fHistTrackAnaSpdMult){ delete fHistTrackAnaSpdMult; fHistTrackAnaSpdMult=0; } } //______________________________________________ void AliNormalizationCounter::Init() { //variables initialization fCounters.AddRubric("Event","triggered/V0AND/PileUp/PbPbC0SMH-B-NOPF-ALLNOTRD/Candles0.3/PrimaryV/countForNorm/noPrimaryV/zvtxGT10/!V0A&Candle03/!V0A&PrimaryV/Candid(Filter)/Candid(Analysis)/NCandid(Filter)/NCandid(Analysis)"); if(fMultiplicity) fCounters.AddRubric("Multiplicity", 5000); if(fSpherocity) fCounters.AddRubric("Spherocity", (Int_t)fSpherocitySteps+1); fCounters.AddRubric("Run", 1000000); fCounters.Init(); fHistTrackFilterEvMult=new TH2F("FiltCandidvsTracksinEv","FiltCandidvsTracksinEv",10000,-0.5,9999.5,200,-0.5,199.5); fHistTrackFilterEvMult->GetYaxis()->SetTitle("NCandidates"); fHistTrackFilterEvMult->GetXaxis()->SetTitle("NTracksinEvent"); fHistTrackAnaEvMult=new TH2F("AnaCandidvsTracksinEv","AnaCandidvsTracksinEv",10000,-0.5,9999.5,100,-0.5,99.5); fHistTrackAnaEvMult->GetYaxis()->SetTitle("NCandidates"); fHistTrackAnaEvMult->GetXaxis()->SetTitle("NTracksinEvent"); fHistTrackFilterSpdMult=new TH2F("FilterCandidvsSpdMult","FilterCandidvsSpdMult",5000,-0.5,4999.5,200,-0.5,199.5); fHistTrackFilterSpdMult->GetYaxis()->SetTitle("NCandidates"); fHistTrackFilterSpdMult->GetXaxis()->SetTitle("NSPDTracklets"); fHistTrackAnaSpdMult=new TH2F("AnaCandidvsSpdMult","AnaCandidvsSpdMult",5000,-0.5,4999.5,100,-0.5,99.5); fHistTrackAnaSpdMult->GetYaxis()->SetTitle("NCandidates"); fHistTrackAnaSpdMult->GetXaxis()->SetTitle("NSPDTracklets"); } //______________________________________________ Long64_t AliNormalizationCounter::Merge(TCollection* list){ if (!list) return 0; if (list->IsEmpty()) return 0;//(Long64_t)fCounters.Merge(list); TIter next(list); const TObject* obj = 0x0; while ((obj = next())) { // check that "obj" is an object of the class AliNormalizationCounter const AliNormalizationCounter* counter = dynamic_cast<const AliNormalizationCounter*>(obj); if (!counter) { AliError(Form("object named %s is not AliNormalizationCounter! Skipping it.", counter->GetName())); continue; } Add(counter); } return (Long64_t)1;//(Long64_t)fCounters->GetEntries(); } //_______________________________________ void AliNormalizationCounter::Add(const AliNormalizationCounter *norm){ fCounters.Add(&(norm->fCounters)); fHistTrackFilterEvMult->Add(norm->fHistTrackFilterEvMult); fHistTrackAnaEvMult->Add(norm->fHistTrackAnaEvMult); fHistTrackFilterSpdMult->Add(norm->fHistTrackFilterSpdMult); fHistTrackAnaSpdMult->Add(norm->fHistTrackAnaSpdMult); } //_______________________________________ /* Stores the variables used for normalization as function of run number returns kTRUE if the event is to be counted for normalization (pass event selection cuts OR has no primary vertex) */ void AliNormalizationCounter::StoreEvent(AliVEvent *event,AliRDHFCuts *rdCut,Bool_t mc, Int_t multiplicity, Double_t spherocity){ // Bool_t isEventSelected = rdCut->IsEventSelected(event); // events not passing physics selection. do nothing if(rdCut->IsEventRejectedDuePhysicsSelection()) return; Bool_t v0A=kFALSE; Bool_t v0B=kFALSE; Bool_t flag03=kFALSE; Bool_t flagPV=kFALSE; //Run Number Int_t runNumber = event->GetRunNumber(); // Evaluate the multiplicity if(fMultiplicity && multiplicity==-9999) Multiplicity(event); //Find CINT1B AliESDEvent *eventESD = (AliESDEvent*)event; if(!eventESD){AliError("ESD event not available");return;} if(mc&&event->GetEventType() != 0)return; //event must be either physics or MC if(!(event->GetEventType() == 7||event->GetEventType() == 0))return; FillCounters("triggered",runNumber,multiplicity,spherocity); //Find V0AND AliTriggerAnalysis trAn; /// Trigger Analysis AliAODVZERO* aodV0 = (AliAODVZERO*)event->GetVZEROData(); Bool_t isPP2012 = kFALSE; if(runNumber>=176326 && runNumber<=193766) isPP2012=kTRUE; if(aodV0 && !isPP2012){ v0B = trAn.IsOfflineTriggerFired(eventESD , AliTriggerAnalysis::kV0C); v0A = trAn.IsOfflineTriggerFired(eventESD , AliTriggerAnalysis::kV0A); } if(v0A&&v0B) FillCounters("V0AND",runNumber,multiplicity,spherocity); //FindPrimary vertex // AliVVertex *vtrc = (AliVVertex*)event->GetPrimaryVertex(); // if(vtrc && vtrc->GetNContributors()>0){ // fCounters.Count(Form("Event:PrimaryV/Run:%d",runNumber)); // flagPV=kTRUE; // } //trigger AliAODEvent *eventAOD = (AliAODEvent*)event; TString trigclass=eventAOD->GetFiredTriggerClasses(); if(trigclass.Contains("C0SMH-B-NOPF-ALLNOTRD")||trigclass.Contains("C0SMH-B-NOPF-ALL")){ FillCounters("PbPbC0SMH-B-NOPF-ALLNOTRD",runNumber,multiplicity,spherocity); } //FindPrimary vertex if(isEventSelected){ FillCounters("PrimaryV",runNumber,multiplicity,spherocity); flagPV=kTRUE; }else{ if(rdCut->GetWhyRejection()==0){ FillCounters("noPrimaryV",runNumber,multiplicity,spherocity); } //find good vtx outside range if(rdCut->GetWhyRejection()==6){ FillCounters("zvtxGT10",runNumber,multiplicity,spherocity); FillCounters("PrimaryV",runNumber,multiplicity,spherocity); flagPV=kTRUE; } if(rdCut->GetWhyRejection()==1){ FillCounters("PileUp",runNumber,multiplicity,spherocity); } } //to be counted for normalization if(rdCut->CountEventForNormalization()){ FillCounters("countForNorm",runNumber,multiplicity,spherocity); } //Find Candle Int_t trkEntries = (Int_t)event->GetNumberOfTracks(); for(Int_t i=0;i<trkEntries&&!flag03;i++){ AliAODTrack *track=(AliAODTrack*)event->GetTrack(i); if((track->Pt()>0.3)&&(!flag03)){ FillCounters("Candles0.3",runNumber,multiplicity,spherocity); flag03=kTRUE; break; } } if(!(v0A&&v0B)&&(flag03)){ FillCounters("!V0A&Candle03",runNumber,multiplicity,spherocity); } if(!(v0A&&v0B)&&flagPV){ FillCounters("!V0A&PrimaryV",runNumber,multiplicity,spherocity); } return; } //_____________________________________________________________________ void AliNormalizationCounter::StoreCandidates(AliVEvent *event,Int_t nCand,Bool_t flagFilter){ Int_t ntracks=event->GetNumberOfTracks(); if(flagFilter)fHistTrackFilterEvMult->Fill(ntracks,nCand); else fHistTrackAnaEvMult->Fill(ntracks,nCand); Int_t nSPD=0; if(fESD){ AliESDEvent *ESDevent=(AliESDEvent*)event; const AliMultiplicity *alimult = ESDevent->GetMultiplicity(); nSPD = alimult->GetNumberOfTracklets(); }else{ AliAODEvent *aodEvent =(AliAODEvent*)event; AliAODTracklets *trklets=aodEvent->GetTracklets(); nSPD = trklets->GetNumberOfTracklets(); } if(flagFilter)fHistTrackFilterSpdMult->Fill(nSPD,nCand); else fHistTrackAnaSpdMult->Fill(nSPD,nCand); Int_t runNumber = event->GetRunNumber(); Int_t multiplicity = Multiplicity(event); if(nCand==0)return; if(flagFilter){ if(fMultiplicity) fCounters.Count(Form("Event:Candid(Filter)/Run:%d/Multiplicity:%d",runNumber,multiplicity)); else fCounters.Count(Form("Event:Candid(Filter)/Run:%d",runNumber)); for(Int_t i=0;i<nCand;i++){ if(fMultiplicity) fCounters.Count(Form("Event:NCandid(Filter)/Run:%d/Multiplicity:%d",runNumber,multiplicity)); else fCounters.Count(Form("Event:NCandid(Filter)/Run:%d",runNumber)); } }else{ if(fMultiplicity) fCounters.Count(Form("Event:Candid(Analysis)/Run:%d/Multiplicity:%d",runNumber,multiplicity)); else fCounters.Count(Form("Event:Candid(Analysis)/Run:%d",runNumber)); for(Int_t i=0;i<nCand;i++){ if(fMultiplicity) fCounters.Count(Form("Event:NCandid(Analysis)/Run:%d/Multiplicity:%d",runNumber,multiplicity)); else fCounters.Count(Form("Event:NCandid(Analysis)/Run:%d",runNumber)); } } return; } //_______________________________________________________________________ TH1D* AliNormalizationCounter::DrawAgainstRuns(TString candle,Bool_t drawHist){ // fCounters.SortRubric("Run"); TString selection; selection.Form("event:%s",candle.Data()); TH1D* histoneD = fCounters.Get("run",selection.Data()); histoneD->Sumw2(); if(drawHist)histoneD->DrawClone(); return histoneD; } //___________________________________________________________________________ TH1D* AliNormalizationCounter::DrawRatio(TString candle1,TString candle2){ // fCounters.SortRubric("Run"); TString name; name.Form("%s/%s",candle1.Data(),candle2.Data()); TH1D* num=DrawAgainstRuns(candle1.Data(),kFALSE); TH1D* den=DrawAgainstRuns(candle2.Data(),kFALSE); den->SetTitle(candle2.Data()); den->SetName(candle2.Data()); num->Divide(num,den,1,1,"B"); num->SetTitle(name.Data()); num->SetName(name.Data()); num->DrawClone(); return num; } //___________________________________________________________________________ void AliNormalizationCounter::PrintRubrics(){ fCounters.PrintKeyWords(); } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetSum(TString candle){ TString selection="event:"; selection.Append(candle); return fCounters.GetSum(selection.Data()); } //___________________________________________________________________________ TH2F* AliNormalizationCounter::GetHist(Bool_t filtercuts,Bool_t spdtracklets,Bool_t drawHist){ if(filtercuts){ if(spdtracklets){ if(drawHist)fHistTrackFilterSpdMult->DrawCopy("LEGO2Z 0"); return fHistTrackFilterSpdMult; }else{ if(drawHist)fHistTrackFilterEvMult->DrawCopy("LEGO2Z 0"); return fHistTrackFilterEvMult; } }else{ if(spdtracklets){ if(drawHist)fHistTrackAnaSpdMult->DrawCopy("LEGO2Z 0"); return fHistTrackAnaSpdMult; }else{ if(drawHist)fHistTrackAnaEvMult->DrawCopy("LEGO2Z 0"); return fHistTrackAnaEvMult; } } } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetNEventsForNorm(){ Double_t noVtxzGT10=GetSum("noPrimaryV")*GetSum("zvtxGT10")/GetSum("PrimaryV"); return GetSum("countForNorm")-noVtxzGT10; } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetNEventsForNorm(Int_t runnumber){ TString listofruns = fCounters.GetKeyWords("RUN"); if(!listofruns.Contains(Form("%d",runnumber))){ printf("WARNING: %d is not a valid run number\n",runnumber); fCounters.Print("Run","",kTRUE); return 0.; } TString suffix;suffix.Form("/RUN:%d",runnumber); TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data()); TString noPV;noPV.Form("noPrimaryV%s",suffix.Data()); TString pV;pV.Form("PrimaryV%s",suffix.Data()); TString tbc;tbc.Form("countForNorm%s",suffix.Data()); Double_t noVtxzGT10=GetSum(noPV.Data())*GetSum(zvtx.Data())/GetSum(pV.Data()); return GetSum(tbc.Data())-noVtxzGT10; } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetNEventsForNorm(Int_t minmultiplicity, Int_t maxmultiplicity){ if(!fMultiplicity) { AliInfo("Sorry, you didn't activate the multiplicity in the counter!"); return 0.; } TString listofruns = fCounters.GetKeyWords("Multiplicity"); Int_t nmultbins = maxmultiplicity - minmultiplicity; Double_t sumnoPV=0., sumZvtx=0., sumPv=0., sumEvtNorm=0.; for (Int_t ibin=0; ibin<=nmultbins; ibin++) { // cout << " Looking at bin "<< ibin+minmultiplicity<<endl; if(!listofruns.Contains(Form("%d",ibin+minmultiplicity))){ // AliInfo(Form("WARNING: %d is not a valid multiplicity number. \n",ibin+minmultiplicity)); continue; } TString suffix;suffix.Form("/Multiplicity:%d",ibin+minmultiplicity); TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data()); TString noPV;noPV.Form("noPrimaryV%s",suffix.Data()); TString pV;pV.Form("PrimaryV%s",suffix.Data()); TString tbc;tbc.Form("countForNorm%s",suffix.Data()); sumnoPV += GetSum(noPV.Data()); sumZvtx += GetSum(zvtx.Data()); sumPv += GetSum(pV.Data()); sumEvtNorm += GetSum(tbc.Data()); } Double_t noVtxzGT10 = sumPv>0. ? sumnoPV * sumZvtx / sumPv : 0.; return sumEvtNorm - noVtxzGT10; } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetNEventsForNorm(Int_t minmultiplicity, Int_t maxmultiplicity, Double_t minspherocity, Double_t maxspherocity){ if(!fMultiplicity || !fSpherocity) { AliInfo("You must activate both multiplicity and spherocity in the counters to use this method!"); return 0.; } TString listofruns = fCounters.GetKeyWords("Multiplicity"); TString listofruns2 = fCounters.GetKeyWords("Spherocity"); TObjArray* arr=listofruns2.Tokenize(","); Int_t nSphVals=arr->GetEntries(); Int_t nmultbins = maxmultiplicity - minmultiplicity; Int_t minSphToInteger=minspherocity*fSpherocitySteps; Int_t maxSphToInteger=maxspherocity*fSpherocitySteps; Int_t nstbins = maxSphToInteger - minSphToInteger; Double_t sumnoPV=0., sumZvtx=0., sumPv=0., sumEvtNorm=0.; for (Int_t ibin=0; ibin<=nmultbins; ibin++) { if(!listofruns.Contains(Form("%d",ibin+minmultiplicity))) continue; for (Int_t ibins=0; ibins<nstbins; ibins++) { Bool_t analyze=kFALSE; for(Int_t j=0; j<nSphVals; j++) if((((TObjString*)arr->At(j))->String()).Atoi()==(ibins+minSphToInteger)) analyze=kTRUE; if(!analyze) continue; if(listofruns2.Contains(",") && !listofruns2.Contains(Form("%d",ibins+minSphToInteger))) continue; TString suffix;suffix.Form("/Multiplicity:%d/Spherocity:%d",ibin+minmultiplicity,ibins+minSphToInteger); TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data()); TString noPV;noPV.Form("noPrimaryV%s",suffix.Data()); TString pV;pV.Form("PrimaryV%s",suffix.Data()); TString tbc;tbc.Form("countForNorm%s",suffix.Data()); sumnoPV += GetSum(noPV.Data()); sumZvtx += GetSum(zvtx.Data()); sumPv += GetSum(pV.Data()); sumEvtNorm += GetSum(tbc.Data()); } } delete arr; Double_t noVtxzGT10 = sumPv>0. ? sumnoPV * sumZvtx / sumPv : 0.; return sumEvtNorm - noVtxzGT10; } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetNEventsForNormSpheroOnly(Double_t minspherocity, Double_t maxspherocity){ if(!fSpherocity) { AliInfo("Sorry, you didn't activate the sphericity in the counter!"); return 0.; } TString listofruns = fCounters.GetKeyWords("Spherocity"); TObjArray* arr=listofruns.Tokenize(","); Int_t nSphVals=arr->GetEntries(); Int_t minSphToInteger=minspherocity*fSpherocitySteps; Int_t maxSphToInteger=maxspherocity*fSpherocitySteps; Int_t nstbins = maxSphToInteger - minSphToInteger; Double_t sumnoPV=0., sumZvtx=0., sumPv=0., sumEvtNorm=0.; for (Int_t ibin=0; ibin<nstbins; ibin++) { Bool_t analyze=kFALSE; for(Int_t j=0; j<nSphVals; j++) if((((TObjString*)arr->At(j))->String()).Atoi()==(ibin+minSphToInteger)) analyze=kTRUE; if(!analyze) continue; TString suffix;suffix.Form("/Spherocity:%d",ibin+minSphToInteger); TString zvtx;zvtx.Form("zvtxGT10%s",suffix.Data()); TString noPV;noPV.Form("noPrimaryV%s",suffix.Data()); TString pV;pV.Form("PrimaryV%s",suffix.Data()); TString tbc;tbc.Form("countForNorm%s",suffix.Data()); sumnoPV += GetSum(noPV.Data()); sumZvtx += GetSum(zvtx.Data()); sumPv += GetSum(pV.Data()); sumEvtNorm += GetSum(tbc.Data()); } delete arr; Double_t noVtxzGT10 = sumPv>0. ? sumnoPV * sumZvtx / sumPv : 0.; return sumEvtNorm - noVtxzGT10; } //___________________________________________________________________________ Double_t AliNormalizationCounter::GetSum(TString candle,Int_t minmultiplicity, Int_t maxmultiplicity){ // counts events of given type in a given multiplicity range if(!fMultiplicity) { AliInfo("Sorry, you didn't activate the multiplicity in the counter!"); return 0.; } TString listofruns = fCounters.GetKeyWords("Multiplicity"); Double_t sum=0.; for (Int_t ibin=minmultiplicity; ibin<=maxmultiplicity; ibin++) { // cout << " Looking at bin "<< ibin+minmultiplicity<<endl; if(!listofruns.Contains(Form("%d",ibin))){ // AliInfo(Form("WARNING: %d is not a valid multiplicity number. \n",ibin)); continue; } TString suffix=Form("/Multiplicity:%d",ibin); TString name=Form("%s%s",candle.Data(),suffix.Data()); sum += GetSum(name.Data()); } return sum; } //___________________________________________________________________________ TH1D* AliNormalizationCounter::DrawNEventsForNorm(Bool_t drawRatio){ //usare algebra histos fCounters.SortRubric("Run"); TString selection; selection.Form("event:noPrimaryV"); TH1D* hnoPrimV = fCounters.Get("run",selection.Data()); hnoPrimV->Sumw2(); selection.Form("event:zvtxGT10"); TH1D* hzvtx= fCounters.Get("run",selection.Data()); hzvtx->Sumw2(); selection.Form("event:PrimaryV"); TH1D* hPrimV = fCounters.Get("run",selection.Data()); hPrimV->Sumw2(); hzvtx->Multiply(hnoPrimV); hzvtx->Divide(hPrimV); selection.Form("event:countForNorm"); TH1D* hCountForNorm = fCounters.Get("run",selection.Data()); hCountForNorm->Sumw2(); hCountForNorm->Add(hzvtx,-1.); if(drawRatio){ selection.Form("event:triggered"); TH1D* htriggered = fCounters.Get("run",selection.Data()); htriggered->Sumw2(); hCountForNorm->Divide(htriggered); } hCountForNorm->DrawClone(); return hCountForNorm; } //___________________________________________________________________________ Int_t AliNormalizationCounter::Multiplicity(AliVEvent* event){ Int_t multiplicity = 0; AliAODEvent *eventAOD = (AliAODEvent*)event; AliAODTracklets * aodTracklets = (AliAODTracklets*)eventAOD->GetTracklets(); Int_t ntracklets = (Int_t)aodTracklets->GetNumberOfTracklets(); for(Int_t i=0;i<ntracklets; i++){ Double_t theta = aodTracklets->GetTheta(i); Double_t eta = -TMath::Log( TMath::Tan(theta/2.) ); // check the formula if(TMath::Abs(eta)<fMultiplicityEtaRange){ // set the proper cut on eta multiplicity++; } } return multiplicity; } //___________________________________________________________________________ void AliNormalizationCounter::FillCounters(TString name, Int_t runNumber, Int_t multiplicity, Double_t spherocity){ Int_t sphToInteger=spherocity*fSpherocitySteps; if(fMultiplicity && !fSpherocity) fCounters.Count(Form("Event:%s/Run:%d/Multiplicity:%d",name.Data(),runNumber,multiplicity)); else if(fMultiplicity && fSpherocity) fCounters.Count(Form("Event:%s/Run:%d/Multiplicity:%d/Spherocity:%d",name.Data(),runNumber,multiplicity,sphToInteger)); else if(!fMultiplicity && fSpherocity) fCounters.Count(Form("Event:%s/Run:%d/Spherocity:%d",name.Data(),runNumber,sphToInteger)); else fCounters.Count(Form("Event:%s/Run:%d",name.Data(),runNumber)); return; }
22,138
8,302
#include "group_utils.h" #include "solution_utils.h" #include "settings.h" #include <QDir> namespace { QList<Group> groups; QHash<QUuid, const Group*> groupMap; QHash<QString, QList<const Group*>> userToGroupMap; const Group BAD_GROUP; const QList<const Group*> EMPTY_GROUP_LIST; void updateAll() { groupMap.clear(); userToGroupMap.clear(); for (auto& group : groups) { groupMap[group.id] = &group; if (group.sortedUserNames.size() != group.userNames.size()) group.sort(); for (const auto& userName : group.userNames) userToGroupMap[userName].append(&group); } updateUserNamesWithoutGroup(); } void saveGroups() { updateAll(); const auto& settings = Settings::instance(); Group::save(groups, settings.localGroupsPath()); if (!settings.groupsPath.isEmpty()) Group::save(groups, settings.groupsPath); } } void loadGroups() { groups.clear(); const auto& settings = Settings::instance(); if (!settings.groupsPath.isEmpty()) { QHash<QUuid, Group> allGroupMap; if (QDir().exists(settings.groupsPath)) { QList<Group> remoteGroups = Group::load(settings.groupsPath); for (const auto& group : remoteGroups) allGroupMap[group.id] = group; } if (QFile(settings.localGroupsPath()).exists()) { QList<Group> localGroups = Group::load(settings.localGroupsPath()); for (const auto& group : localGroups) allGroupMap[group.id] = group; } groups = allGroupMap.values(); saveGroups(); return; } if (QFile(settings.localGroupsPath()).exists()) groups = Group::load(settings.localGroupsPath()); updateAll(); } const QList<Group>& getGroups() { return groups; } const Group& getGroup(const QUuid& id) { auto it = groupMap.find(id); if (it == groupMap.end()) return BAD_GROUP; return *it.value(); } void removeGroup(const QUuid& id) { for (auto it = groups.begin(); it != groups.end(); ++it) { if (it->id == id) { groups.erase(it); saveGroups(); return; } } } void addGroup(const Group& group) { for (auto it = groups.begin(); it != groups.end(); ++it) { if (it->id == group.id) { *it = group; it->sortedUserNames.clear(); saveGroups(); return; } } groups.append(group); saveGroups(); } const QList<const Group*>& getGroupsByUserName(QString userName) { auto it = userToGroupMap.find(userName); if (it == userToGroupMap.end()) return EMPTY_GROUP_LIST; return it.value(); }
2,710
840
#include "../../headers/ui/Image.h" #include "../../headers/Renderer2D.h" Image::Image(const char * path, int x, int y) { pImageId = Resources::getInstance()->Load<Sprite>(path); px = x; py = y; } Image::~Image() { } void Image::Render() { Renderer2D::getInstance()->RenderGraphic(pImageId, px, py); }
309
121
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. #include "yb/common/wire_protocol.h" #include "yb/master/catalog_entity_info.h" #include "yb/master/master.pb.h" using std::set; namespace yb { namespace master { // ================================================================================================ // CDCStreamInfo // ================================================================================================ const TableId& CDCStreamInfo::table_id() const { return LockForRead()->pb.table_id(); } std::string CDCStreamInfo::ToString() const { auto l = LockForRead(); return Format("$0 [table=$1] {metadata=$2} ", id(), l->pb.table_id(), l->pb.ShortDebugString()); } // ================================================================================================ // UniverseReplicationInfo // ================================================================================================ Result<std::shared_ptr<CDCRpcTasks>> UniverseReplicationInfo::GetOrCreateCDCRpcTasks( google::protobuf::RepeatedPtrField<HostPortPB> producer_masters) { std::vector<HostPort> hp; HostPortsFromPBs(producer_masters, &hp); std::string master_addrs = HostPort::ToCommaSeparatedString(hp); std::lock_guard<decltype(lock_)> l(lock_); if (cdc_rpc_tasks_ != nullptr) { // Master Addresses changed, update YBClient with new retry logic. if (master_addrs_ != master_addrs) { if (cdc_rpc_tasks_->UpdateMasters(master_addrs).ok()) { master_addrs_ = master_addrs; } } return cdc_rpc_tasks_; } auto result = CDCRpcTasks::CreateWithMasterAddrs(producer_id_, master_addrs); if (result.ok()) { cdc_rpc_tasks_ = *result; master_addrs_ = master_addrs; } return result; } std::string UniverseReplicationInfo::ToString() const { auto l = LockForRead(); return strings::Substitute("$0 [data=$1] ", id(), l->pb.ShortDebugString()); } //////////////////////////////////////////////////////////// // SnapshotInfo //////////////////////////////////////////////////////////// SnapshotInfo::SnapshotInfo(SnapshotId id) : snapshot_id_(std::move(id)) {} SysSnapshotEntryPB::State SnapshotInfo::state() const { return LockForRead()->state(); } const std::string& SnapshotInfo::state_name() const { return LockForRead()->state_name(); } std::string SnapshotInfo::ToString() const { return YB_CLASS_TO_STRING(snapshot_id); } bool SnapshotInfo::IsCreateInProgress() const { return LockForRead()->is_creating(); } bool SnapshotInfo::IsRestoreInProgress() const { return LockForRead()->is_restoring(); } bool SnapshotInfo::IsDeleteInProgress() const { return LockForRead()->is_deleting(); } void SnapshotInfo::AddEntries( const TableDescription& table_description, std::unordered_set<NamespaceId>* added_namespaces) { SysSnapshotEntryPB& pb = mutable_metadata()->mutable_dirty()->pb; AddEntries( table_description, pb.mutable_entries(), pb.mutable_tablet_snapshots(), added_namespaces); } template <class Info> auto AddInfoEntry(Info* info, google::protobuf::RepeatedPtrField<SysRowEntry>* out) { auto lock = info->LockForRead(); FillInfoEntry(*info, out->Add()); return lock; } void SnapshotInfo::AddEntries( const TableDescription& table_description, google::protobuf::RepeatedPtrField<SysRowEntry>* out, google::protobuf::RepeatedPtrField<SysSnapshotEntryPB::TabletSnapshotPB>* tablet_infos, std::unordered_set<NamespaceId>* added_namespaces) { // Note: SysSnapshotEntryPB includes PBs for stored (1) namespaces (2) tables (3) tablets. // Add namespace entry. if (added_namespaces->emplace(table_description.namespace_info->id()).second) { TRACE("Locking namespace"); AddInfoEntry(table_description.namespace_info.get(), out); } // Add table entry. { TRACE("Locking table"); AddInfoEntry(table_description.table_info.get(), out); } // Add tablet entries. for (const scoped_refptr<TabletInfo>& tablet : table_description.tablet_infos) { SysSnapshotEntryPB::TabletSnapshotPB* const tablet_info = tablet_infos ? tablet_infos->Add() : nullptr; TRACE("Locking tablet"); auto l = AddInfoEntry(tablet.get(), out); if (tablet_info) { tablet_info->set_id(tablet->id()); tablet_info->set_state(SysSnapshotEntryPB::CREATING); } } } } // namespace master } // namespace yb
4,903
1,537
#include <cassert> #include <sstream> #include <iomanip> #include "OldZSolid.hh" #include "ZSolid.h" #include "G4Ellipsoid.hh" #include "G4Tubs.hh" #include "G4Polycone.hh" #include "G4UnionSolid.hh" #include "NP.hh" std::string OldZSolid::desc() const { std::stringstream ss ; ss << " EntityTypeName " << std::setw(15) << ZSolid::EntityTypeName(solid) << " EntityType " << std::setw(3) << ZSolid::EntityType(solid) << " label " << std::setw(10) << label << " zdelta " << std::setw(10) << std::fixed << std::setprecision(3) << zdelta << " z1 " << std::setw(10) << std::fixed << std::setprecision(3) << z1() << " z0 " << std::setw(10) << std::fixed << std::setprecision(3) << z0() ; std::string s = ss.str(); return s ; } double OldZSolid::z0() const { double _z0, _z1 ; ZSolid::ZRange(_z0, _z1, solid ); return _z0 ; } double OldZSolid::z1() const { double _z0, _z1 ; ZSolid::ZRange(_z0, _z1, solid ); return _z1 ; } int OldZSolid::classifyZCut( double zcut ) const { double az0 = zdelta + z0() ; double az1 = zdelta + z1() ; return ZSolid::ClassifyZCut( az0, az1, zcut ); } void OldZSolid::applyZCut( double zcut ) { double az1 = zdelta + z1() ; double az0 = zdelta + z0() ; bool expect = az1 > az0 ; if(!expect) exit(EXIT_FAILURE); assert( expect ); assert( zcut < az1 && zcut > az0 ); double local_zcut = zcut - zdelta ; ZSolid::ApplyZCut( solid, local_zcut ); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void OldZSolidList::dump(const char* msg) const { std::cout << msg << std::endl ; for(unsigned i=0 ; i < solids.size() ; i++) { const OldZSolid& zsi = solids[i] ; double az0 = zsi.zdelta + zsi.z0() ; double az1 = zsi.zdelta + zsi.z1() ; std::cout << std::setw(3) << i << " " << zsi.desc() << " az1 " << std::setw(10) << std::fixed << std::setprecision(3) << az1 << " az0 " << std::setw(10) << std::fixed << std::setprecision(3) << az0 << std::endl ; } } void OldZSolidList::save(const char* path) const { std::vector<double> tmp ; unsigned num = solids.size() ; for(unsigned i=0 ; i < num ; i++) { const OldZSolid& zsi = solids[i] ; tmp.push_back(zsi.z0()); tmp.push_back(zsi.z1()); tmp.push_back(zsi.zdelta); tmp.push_back(0.); double az0 = zsi.zdelta + zsi.z0() ; double az1 = zsi.zdelta + zsi.z1() ; tmp.push_back(az0); tmp.push_back(az1); tmp.push_back(0.); tmp.push_back(0.); } NP* a = NP::Make<double>( num, 2, 4 ); a->read(tmp.data()); a->save(path); } G4VSolid* OldZSolidList::makeUnionSolid(const std::string& solidname) const { dump("OldZSolidList::makeUnionSolid"); G4VSolid* solid = solids[0].solid ; for(unsigned i=1 ; i < solids.size() ; i++) { const OldZSolid& zsi = solids[i] ; solid = new G4UnionSolid( solidname+zsi.label, solid, zsi.solid, 0, G4ThreeVector(0,0,zsi.zdelta) ); } save("/tmp/ZSolids.npy"); return solid ; } unsigned OldZSolidList::classifyZCutCount( double zcut, int q_cls ) { unsigned count(0); for(unsigned idx=0 ; idx < solids.size() ; idx++ ) { OldZSolid& zsi = solids[idx] ; if( zsi.classifyZCut(zcut) == q_cls ) count += 1 ; } return count ; } /** OldZSolids::makeUnionSolidZCut --------------------------------- Hmm how to do this with a tree of solids instead of the artifically collected vector ? **/ G4VSolid* OldZSolidList::makeUnionSolidZCut(const std::string& solidname, double zcut) { unsigned num_undefined = classifyZCutCount(zcut, ZSolid::UNDEFINED ); unsigned num_include = classifyZCutCount(zcut, ZSolid::INCLUDE ); unsigned num_straddle = classifyZCutCount(zcut, ZSolid::STRADDLE ); unsigned num_exclude = classifyZCutCount(zcut, ZSolid::EXCLUDE ); unsigned num_solid = num_include + num_straddle ; std::cout << "OldZSolids::makeUnionSolidZCut" << " num_undefined " << num_undefined << " num_include " << num_include << " num_straddle " << num_straddle << " num_exclude " << num_exclude << " num_solid " << num_solid << std::endl ; assert( num_undefined == 0 ); assert( num_solid > 0 ); OldZSolid& zsi0 = solids[0] ; G4VSolid* solid = zsi0.solid ; int cls = zsi0.classifyZCut(zcut ); assert( cls == ZSolid::INCLUDE || cls == ZSolid::STRADDLE ); // first solid must be at z top and at least partially included if( cls == ZSolid::STRADDLE ) zsi0.applyZCut( zcut ); if( num_solid == 1 ) return solid ; for(unsigned idx=1 ; idx < solids.size() ; idx++) { OldZSolid& zsi = solids[idx] ; cls = zsi.classifyZCut( zcut ); if( cls == ZSolid::STRADDLE ) zsi.applyZCut( zcut ); if( cls == ZSolid::INCLUDE || cls == ZSolid::STRADDLE ) { solid = new G4UnionSolid( solidname+zsi.label, solid, zsi.solid, 0, G4ThreeVector(0,0,zsi.zdelta) ); } } return solid ; }
5,905
2,208
/************************************************ * * * rs@md * * (reactive steps @ molecular dynamics ) * * * ************************************************/ /* Copyright 2020 Myra Biedermann Licensed under the Apache License, Version 2.0 Parts of the code within this file was modified from "container_class_base.hpp" within github repository https://github.com/simonraschke/vesicle2.git, licensed under Apache License Version 2.0 Myra Biedermann thankfully acknowledges support from Simon Raschke. */ #pragma once #include <iterator> // // a container base class to derive from // // implements all iterator-related functions like begin() / end() etc. // for use in loops // as well as container-related operators like [] and () // template<typename T> struct ContainerBase { T data {}; inline auto& operator()(std::size_t i) { return data[i]; }; inline constexpr auto& operator()(std::size_t i) const { return data[i]; }; inline auto& operator[](std::size_t i) { return data[i]; }; inline constexpr auto& operator[](std::size_t i) const { return data[i]; }; inline auto begin() { return std::begin(data); }; inline auto end() { return std::end(data); }; inline auto begin() const { return std::begin(data); }; inline auto end() const { return std::end(data); }; inline auto cbegin() const { return std::cbegin(data); }; inline auto cend() const { return std::cend(data); }; inline auto rbegin() { return std::rbegin(data); }; inline auto rend() { return std::rend(data); }; inline auto rbegin() const { return std::rbegin(data); }; inline auto rend() const { return std::rend(data); }; inline auto crbegin() const { return std::crbegin(data); }; inline auto crend() const { return std::crend(data); }; inline auto size() const { return data.size(); }; inline auto& front() { return *this->begin(); } inline const auto& front() const { return *this->begin(); } inline auto& back() { auto tmp = this->end(); --tmp; return *tmp; } inline const auto& back() const { auto tmp = this->end(); --tmp; return *tmp; } virtual ~ContainerBase() = default; protected: ContainerBase() = default; };
2,485
688
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. // http://code.google.com/p/protobuf/ // // 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. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // Modified to implement C code by Dave Benson. #include <google/protobuf/compiler/c/c_bytes_field.h> #include <google/protobuf/compiler/c/c_helpers.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format_inl.h> #include <google/protobuf/descriptor.pb.h> namespace google { namespace protobuf { namespace compiler { namespace c { using internal::WireFormat; void SetBytesVariables(const FieldDescriptor* descriptor, map<string, string>* variables) { (*variables)["name"] = FieldName(descriptor); (*variables)["default"] = "\"" + CEscape(descriptor->default_value_string()) + "\""; } // =================================================================== BytesFieldGenerator:: BytesFieldGenerator(const FieldDescriptor* descriptor) : FieldGenerator(descriptor) { SetBytesVariables(descriptor, &variables_); variables_["default_value"] = descriptor->has_default_value() ? GetDefaultValue() : string("{0,NULL}"); } BytesFieldGenerator::~BytesFieldGenerator() {} void BytesFieldGenerator::GenerateStructMembers(io::Printer* printer) const { switch (descriptor_->label()) { case FieldDescriptor::LABEL_REQUIRED: printer->Print(variables_, "ProtobufCBinaryData $name$;\n"); break; case FieldDescriptor::LABEL_OPTIONAL: printer->Print(variables_, "protobuf_c_boolean has_$name$;\n"); printer->Print(variables_, "ProtobufCBinaryData $name$;\n"); break; case FieldDescriptor::LABEL_REPEATED: printer->Print(variables_, "size_t n_$name$;\n"); printer->Print(variables_, "ProtobufCBinaryData *$name$;\n"); break; } } void BytesFieldGenerator::GenerateDefaultValueDeclarations(io::Printer* printer) const { std::map<string, string> vars; vars["default_value_data"] = FullNameToLower(descriptor_->full_name()) + "__default_value_data"; printer->Print(vars, "extern uint8_t $default_value_data$[];\n"); } void BytesFieldGenerator::GenerateDefaultValueImplementations(io::Printer* printer) const { std::map<string, string> vars; vars["default_value_data"] = FullNameToLower(descriptor_->full_name()) + "__default_value_data"; vars["escaped"] = CEscape(descriptor_->default_value_string()); printer->Print(vars, "uint8_t $default_value_data$[] = \"$escaped$\";\n"); } string BytesFieldGenerator::GetDefaultValue(void) const { return "{ " + SimpleItoa(descriptor_->default_value_string().size()) + ", " + FullNameToLower(descriptor_->full_name()) + "__default_value_data }"; } void BytesFieldGenerator::GenerateStaticInit(io::Printer* printer) const { switch (descriptor_->label()) { case FieldDescriptor::LABEL_REQUIRED: printer->Print(variables_, "$default_value$"); break; case FieldDescriptor::LABEL_OPTIONAL: printer->Print(variables_, "0,$default_value$"); break; case FieldDescriptor::LABEL_REPEATED: // no support for default? printer->Print("0,NULL"); break; } } void BytesFieldGenerator::GenerateDescriptorInitializer(io::Printer* printer) const { GenerateDescriptorInitializerGeneric(printer, true, "BYTES", "NULL"); } } // namespace c } // namespace compiler } // namespace protobuf } // namespace google
4,126
1,285
/** * Copyright (c) 2017 LIBBLE team supervised by Dr. Wu-Jun LI at Nanjing University. * 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. */ #ifndef _PROTOCOL_HPP_ #define _PROTOCOL_HPP_ /* this file define the tag number used for MPI for sending different messages */ // from coordinator #define CW_PARAMS 100 // coordinator sends parameters to worker #define CW_INFO 101 // coordinator sends info to worker #define CW_GRAD 102 // coordinator sends full grad to worker #define CS_INFO 103 // coordinator sends info to server #define CSWPULL_INFO 104// coordinator sends pull w_id info to server #define CSWPUSH_INFO 105// coordinator sends push w_id info to server // from server #define SW_PARAMS 200// server sends parameters to worker #define SC_EPOCH 201 // server sends epoch to coordinator to count time #define SC_PARAMS 202// server sends parameters to coordinator in the end #define SW_C 203 // server sends c to worker #define SW_GRAD 204 // server sends full grad to worker // from worker #define WS_GRADS 300 // worker sends gradients to server #define WC_LOSS 301 // worker sends loss to coordinator #define WC_GRAD 302 // worker sends part full grad to coordinator #define WC_PARAMS 303// worker sends parameters to coordinator #define WS_PARAMS 304// worker sends parameters to coordinator #define WCP_INFO 305 // worker sends pull info to coordinator #define WCG_INFO 306 // worker sends push info to coordinator #define WS_C 307 // worker sends c to server #define WC_ACCU 308 // worker sends accuracy to coordinator #endif
2,190
675
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://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 https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "qmljsscopechain.h" #include "qmljsbind.h" #include "qmljsevaluate.h" #include "qmljsmodelmanagerinterface.h" #include "parser/qmljsengine_p.h" #include <QRegExp> using namespace QmlJS; /*! \class QmlJS::ScopeChain \brief The ScopeChain class describes the scopes used for global lookup in a specific location. \sa Document Context ScopeBuilder A ScopeChain is used to perform global lookup with the lookup() function and to access information about the enclosing scopes. Once constructed for a Document in a Context it represents the root scope of that Document. From there, a ScopeBuilder can be used to push and pop scopes corresponding to functions, object definitions, etc. It is an error to use the same ScopeChain from multiple threads; use a copy. Copying is cheap. Initial construction is currently expensive. When a QmlJSEditor::QmlJSEditorDocument is available, there's no need to construct a new ScopeChain. Instead use QmlJSEditorDocument::semanticInfo()::scopeChain(). */ QmlComponentChain::QmlComponentChain(const Document::Ptr &document) : m_document(document) { } QmlComponentChain::~QmlComponentChain() { qDeleteAll(m_instantiatingComponents); } Document::Ptr QmlComponentChain::document() const { return m_document; } QList<const QmlComponentChain *> QmlComponentChain::instantiatingComponents() const { return m_instantiatingComponents; } const ObjectValue *QmlComponentChain::idScope() const { if (!m_document) return 0; return m_document->bind()->idEnvironment(); } const ObjectValue *QmlComponentChain::rootObjectScope() const { if (!m_document) return 0; return m_document->bind()->rootObjectValue(); } void QmlComponentChain::addInstantiatingComponent(const QmlComponentChain *component) { m_instantiatingComponents.append(component); } ScopeChain::ScopeChain(const Document::Ptr &document, const ContextPtr &context) : m_document(document) , m_context(context) , m_globalScope(0) , m_cppContextProperties(0) , m_qmlTypes(0) , m_jsImports(0) , m_modified(false) { initializeRootScope(); } Document::Ptr ScopeChain::document() const { return m_document; } const ContextPtr &ScopeChain::context() const { return m_context; } const Value * ScopeChain::lookup(const QString &name, const ObjectValue **foundInScope) const { QList<const ObjectValue *> scopes = all(); for (int index = scopes.size() - 1; index != -1; --index) { const ObjectValue *scope = scopes.at(index); if (const Value *member = scope->lookupMember(name, m_context)) { if (foundInScope) *foundInScope = scope; return member; } } if (foundInScope) *foundInScope = 0; // we're confident to implement global lookup correctly, so return 'undefined' return m_context->valueOwner()->undefinedValue(); } const Value *ScopeChain::evaluate(AST::Node *node) const { Evaluate evaluator(this); return evaluator(node); } const ObjectValue *ScopeChain::globalScope() const { return m_globalScope; } void ScopeChain::setGlobalScope(const ObjectValue *globalScope) { m_modified = true; m_globalScope = globalScope; } const ObjectValue *ScopeChain::cppContextProperties() const { return m_cppContextProperties; } void ScopeChain::setCppContextProperties(const ObjectValue *cppContextProperties) { m_modified = true; m_cppContextProperties = cppContextProperties; } QSharedPointer<const QmlComponentChain> ScopeChain::qmlComponentChain() const { return m_qmlComponentScope; } void ScopeChain::setQmlComponentChain(const QSharedPointer<const QmlComponentChain> &qmlComponentChain) { m_modified = true; m_qmlComponentScope = qmlComponentChain; } QList<const ObjectValue *> ScopeChain::qmlScopeObjects() const { return m_qmlScopeObjects; } void ScopeChain::setQmlScopeObjects(const QList<const ObjectValue *> &qmlScopeObjects) { m_modified = true; m_qmlScopeObjects = qmlScopeObjects; } const TypeScope *ScopeChain::qmlTypes() const { return m_qmlTypes; } void ScopeChain::setQmlTypes(const TypeScope *qmlTypes) { m_modified = true; m_qmlTypes = qmlTypes; } const JSImportScope *ScopeChain::jsImports() const { return m_jsImports; } void ScopeChain::setJsImports(const JSImportScope *jsImports) { m_modified = true; m_jsImports = jsImports; } QList<const ObjectValue *> ScopeChain::jsScopes() const { return m_jsScopes; } void ScopeChain::setJsScopes(const QList<const ObjectValue *> &jsScopes) { m_modified = true; m_jsScopes = jsScopes; } void ScopeChain::appendJsScope(const ObjectValue *scope) { m_modified = true; m_jsScopes += scope; } QList<const ObjectValue *> ScopeChain::all() const { if (m_modified) update(); return m_all; } static void collectScopes(const QmlComponentChain *chain, QList<const ObjectValue *> *target) { foreach (const QmlComponentChain *parent, chain->instantiatingComponents()) collectScopes(parent, target); if (!chain->document()) return; if (const ObjectValue *root = chain->rootObjectScope()) target->append(root); if (const ObjectValue *ids = chain->idScope()) target->append(ids); } void ScopeChain::update() const { m_modified = false; m_all.clear(); m_all += m_globalScope; if (m_cppContextProperties) m_all += m_cppContextProperties; // the root scope in js files doesn't see instantiating components if (m_document->language() != Dialect::JavaScript || m_jsScopes.count() != 1) { if (m_qmlComponentScope) { foreach (const QmlComponentChain *parent, m_qmlComponentScope->instantiatingComponents()) collectScopes(parent, &m_all); } } ObjectValue *root = 0; ObjectValue *ids = 0; if (m_qmlComponentScope && m_qmlComponentScope->document()) { const Bind *bind = m_qmlComponentScope->document()->bind(); root = bind->rootObjectValue(); ids = bind->idEnvironment(); } if (root && !m_qmlScopeObjects.contains(root)) m_all += root; m_all += m_qmlScopeObjects; if (ids) m_all += ids; if (m_qmlTypes) m_all += m_qmlTypes; if (m_jsImports) m_all += m_jsImports; m_all += m_jsScopes; } static void addInstantiatingComponents(ContextPtr context, QmlComponentChain *chain) { const QRegExp importCommentPattern(QLatin1String("@scope\\s+(.*)")); foreach (const AST::SourceLocation &commentLoc, chain->document()->engine()->comments()) { const QString &comment = chain->document()->source().mid(commentLoc.begin(), commentLoc.length); // find all @scope annotations QStringList additionalScopes; int lastOffset = -1; forever { lastOffset = importCommentPattern.indexIn(comment, lastOffset + 1); if (lastOffset == -1) break; additionalScopes << QFileInfo(chain->document()->path() + QLatin1Char('/') + importCommentPattern.cap(1).trimmed()).absoluteFilePath(); } foreach (const QmlComponentChain *c, chain->instantiatingComponents()) additionalScopes.removeAll(c->document()->fileName()); foreach (const QString &scope, additionalScopes) { Document::Ptr doc = context->snapshot().document(scope); if (doc) { QmlComponentChain *ch = new QmlComponentChain(doc); chain->addInstantiatingComponent(ch); addInstantiatingComponents(context, ch); } } } } void ScopeChain::initializeRootScope() { ValueOwner *valueOwner = m_context->valueOwner(); const Snapshot &snapshot = m_context->snapshot(); Bind *bind = m_document->bind(); m_globalScope = valueOwner->globalObject(); m_cppContextProperties = valueOwner->cppQmlTypes().cppContextProperties(); QHash<const Document *, QmlComponentChain *> componentScopes; QmlComponentChain *chain = new QmlComponentChain(m_document); m_qmlComponentScope = QSharedPointer<const QmlComponentChain>(chain); if (const Imports *imports = m_context->imports(m_document.data())) { m_qmlTypes = imports->typeScope(); m_jsImports = imports->jsImportScope(); } if (m_document->qmlProgram()) { componentScopes.insert(m_document.data(), chain); makeComponentChain(chain, snapshot, &componentScopes); } else { // add scope chains for all components that import this file // unless there's .pragma library if (!m_document->bind()->isJsLibrary()) { foreach (Document::Ptr otherDoc, snapshot) { foreach (const ImportInfo &import, otherDoc->bind()->imports()) { if ((import.type() == ImportType::File && m_document->fileName() == import.path()) || (import.type() == ImportType::QrcFile && ModelManagerInterface::instance()->filesAtQrcPath(import.path()) .contains(m_document->fileName()))) { QmlComponentChain *component = new QmlComponentChain(otherDoc); componentScopes.insert(otherDoc.data(), component); chain->addInstantiatingComponent(component); makeComponentChain(component, snapshot, &componentScopes); } } } } if (bind->rootObjectValue()) m_jsScopes += bind->rootObjectValue(); } addInstantiatingComponents(m_context, chain); m_modified = true; } void ScopeChain::makeComponentChain( QmlComponentChain *target, const Snapshot &snapshot, QHash<const Document *, QmlComponentChain *> *components) { Document::Ptr doc = target->document(); if (!doc->qmlProgram()) return; const Bind *bind = doc->bind(); // add scopes for all components instantiating this one foreach (Document::Ptr otherDoc, snapshot) { if (otherDoc == doc) continue; if (otherDoc->bind()->usesQmlPrototype(bind->rootObjectValue(), m_context)) { if (!components->contains(otherDoc.data())) { QmlComponentChain *component = new QmlComponentChain(otherDoc); components->insert(otherDoc.data(), component); target->addInstantiatingComponent(component); makeComponentChain(component, snapshot, components); } } } }
11,879
3,454
/***************************************************************************** * * CLIPP - command line interfaces for modern C++ * * released under MIT license * * (c) 2017 André Müller; foss@andremueller-online.de * *****************************************************************************/ #include "testing.h" //------------------------------------------------------------------- struct active { int av = 0; int bv = 1; float cv = 0.0f, dv = 1.0f; double ev = 0.0, fv = 1.0; std::string gv; bool a = false, b = false, c = false, d = false, e = false, f = false, g = false, h = false, i = false; friend bool operator == (const active& x, const active& y) noexcept { if(x.a != y.a || x.b != y.b || x.c != y.c || x.d != y.d || x.e != y.e || x.f != y.f || x.g != y.g || x.h != y.h || x.i != y.i || x.av != y.av || x.bv != y.bv || x.gv != y.gv) return false; using std::abs; if(abs(x.cv - y.cv) > 1e-4f || abs(x.dv - y.dv) > 1e-4f || abs(x.ev - y.ev) > 1e-4 || abs(x.fv - y.fv) > 1e-4) return false; return true; } }; //------------------------------------------------------------------- void test(int lineNo, const std::initializer_list<const char*> args, const active& matches) { using namespace clipp; active m; auto cli = ( required("-a").set(m.a) & value("A",m.av), required("-b", "--bb").set(m.b) & value("B",m.bv), option("-c", "--cc").set(m.c) & value("C",m.cv) & opt_value("D",m.dv), option("-d", "--dd").set(m.d) & opt_value("D",m.dv), required("-e", "--ee").set(m.e) & value("E",m.ev), option("-f", "--ff").set(m.f) & opt_value("F",m.fv), value("G", m.gv).set(m.g), option("-h", "--hh", "---hhh").set(m.h), required("-i", "--ii").set(m.i) ); run_wrapped_variants({ __FILE__, lineNo }, args, cli, [&]{ m = active{}; }, [&]{ return m == matches; }); } //------------------------------------------------------------------- int main() { try { active m; test(__LINE__, {""}, m); m = active{}; m.a = true; test(__LINE__, {"-a"}, m); m = active{}; m.a = true; m.av = 65; test(__LINE__, {"-a", "65"}, m); test(__LINE__, {"-a65"}, m); m = active{}; m.b = true; test(__LINE__, {"-b"}, m); m = active{}; m.b = true; m.bv = 12; test(__LINE__, {"-b", "12"}, m); test(__LINE__, {"-b12"}, m); m = active{}; m.c = true; test(__LINE__, {"-c"}, m); m = active{}; m.c = true; m.cv = 2.3f; test(__LINE__, {"-c", "2.3"}, m); test(__LINE__, {"-c2.3"}, m); test(__LINE__, {"-c2", ".3"}, m); test(__LINE__, {"-c", "+2.3"}, m); test(__LINE__, {"-c+2.3"}, m); test(__LINE__, {"-c+2", ".3"}, m); m = active{}; m.c = true; m.cv = -2.3f; test(__LINE__, {"-c", "-2.3"}, m); test(__LINE__, {"-c-2.3"}, m); test(__LINE__, {"-c-2", ".3"}, m); m = active{}; m.c = true; m.cv = 1; m.dv = 2; test(__LINE__, {"-c", "1", "2"}, m); test(__LINE__, {"-c1", "2"}, m); test(__LINE__, {"-c1", "2"}, m); m = active{}; m.d = true; m.c = true; m.cv = 2; test(__LINE__, {"-c", "2", "-d"}, m); m = active{}; m.a = true; m.av = 1; m.c = true; m.cv = 2; test(__LINE__, {"-c", "2", "-a", "1"}, m); m = active{}; m.d = true; test(__LINE__, {"-d"}, m); m = active{}; m.d = true; m.dv = 2.3f; test(__LINE__, {"-d", "2.3"}, m); test(__LINE__, {"-d2.3"}, m); test(__LINE__, {"-d2", ".3"}, m); m = active{}; m.e = true; test(__LINE__, {"-e"}, m); m = active{}; m.e = true; m.ev = 2.3; test(__LINE__, {"-e", "2.3"}, m); test(__LINE__, {"-e2.3"}, m); test(__LINE__, {"-e2", ".3"}, m); m = active{}; m.f = true; test(__LINE__, {"-f"}, m); test(__LINE__, {"--ff"}, m); m = active{}; m.f = true; m.fv = 2.3; test(__LINE__, {"-f", "2.3"}, m); test(__LINE__, {"--ff", "2.3"}, m); test(__LINE__, {"-f2.3"}, m); test(__LINE__, {"--ff2.3"}, m); test(__LINE__, {"-f2", ".3"}, m); test(__LINE__, {"--ff2", ".3"}, m); m = active{}; m.g = true; m.gv = "xyz"; test(__LINE__, {"xyz"}, m); m = active{}; m.g = true; m.gv = "-h"; test(__LINE__, {"-h"}, m); m = active{}; m.g = true; m.gv = "--hh"; test(__LINE__, {"--hh"}, m); m = active{}; m.g = true; m.gv = "---hhh"; test(__LINE__, {"---hhh"}, m); m = active{}; m.g = true; m.gv = "--h"; test(__LINE__, {"--h"}, m); m = active{}; m.g = true; m.gv = "--hh"; test(__LINE__, {"--hh"}, m); m = active{}; m.g = true; m.gv = "-hh"; test(__LINE__, {"-hh"}, m); m = active{}; m.g = true; m.gv = "-hhh"; test(__LINE__, {"-hhh"}, m); m = active{}; m.h = true; m.g = true; m.gv = "x-y.z"; test(__LINE__, {"x-y.z", "-h"}, m); test(__LINE__, {"x-y.z", "--hh"}, m); test(__LINE__, {"x-y.z", "---hhh"}, m); m = active{}; m.i = true; m.g = true; m.gv = "xYz"; test(__LINE__, {"xYz", "-i"}, m); test(__LINE__, {"xYz", "--ii"}, m); m = active{}; m.g = true; m.gv = "-ii"; test(__LINE__, {"-ii"}, m); m = active{}; m.g = true; m.gv = "--i"; test(__LINE__, {"--i"}, m); m = active{}; m.a = true; m.av = 65; m.b = true; m.bv = 12; m.c = true; m.cv = -0.12f; m.d = true; m.dv = 2.3f; m.e = true; m.ev = 3.4; m.f = true; m.fv = 5.6; m.g = true; m.gv = "x-y.z"; m.h = true; m.i = true; test(__LINE__, {"-a", "65", "-b12", "-c", "-0.12f", "-d2.3", "-e3", ".4", "--ff", "5.6", "x-y.z", "-h", "--ii"}, m); test(__LINE__, {"-b12", "-c", "-0.12f", "-d2.3", "-e3", ".4", "-a", "65", "--ff", "5.6", "x-y.z", "-h", "--ii"}, m); test(__LINE__, {"-d2.3", "-e3", ".4", "-b12", "-c", "-0.12f", "-a", "65", "--ff", "5.6", "x-y.z", "-h", "--ii"}, m); } catch(std::exception& e) { std::cerr << e.what() << std::endl; return 1; } }
6,460
2,668
/*++ Copyright (c) 2000 Microsoft Corporation Module Name: FaxOutboundRoutingGroups.cpp Abstract: Implementation of CFaxOutboundRoutingGroups class. Author: Iv Garber (IvG) Jun, 2000 Revision History: --*/ #include "stdafx.h" #include "FaxComEx.h" #include "FaxOutboundRoutingGroups.h" #include "FaxOutboundRoutingGroup.h" // //================= FIND GROUP ======================================================= // STDMETHODIMP CFaxOutboundRoutingGroups::FindGroup( /*[in]*/ VARIANT vIndex, /*[out]*/ ContainerType::iterator &it ) /*++ Routine name : CFaxOutboundRoutingGroups::FindGroup Routine description: Find Group by given Variant : either Group Name either Group Index in the Collection Author: Iv Garber (IvG), Jun, 2000 Arguments: vIndex [in] - the Key to Find the Group it [out] - the found Group Iterator Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::FindGroup"), hr); CComVariant var; if (vIndex.vt != VT_BSTR) { // // vIndex is not BSTR ==> convert to VT_I4 // hr = var.ChangeType(VT_I4, &vIndex); if (SUCCEEDED(hr)) { VERBOSE(DBG_MSG, _T("Parameter is Number : %d"), var.lVal); // // Check the Range of the Index // if (var.lVal > m_coll.size() || var.lVal < 1) { // // Invalid Index // hr = E_INVALIDARG; AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_OUTOFRANGE, IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(GENERAL_ERR, _T("lIndex < 1 || lIndex > m_coll.size()"), hr); return hr; } // // Find the Group Object to Remove // it = m_coll.begin() + var.lVal - 1; return hr; } } // // We didnot success to convert the var to Number // So, try to convert it to the STRING // hr = var.ChangeType(VT_BSTR, &vIndex); if (FAILED(hr)) { hr = E_INVALIDARG; AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(GENERAL_ERR, _T("var.ChangeType(VT_BSTR, &vIndex)"), hr); return hr; } VERBOSE(DBG_MSG, _T("Parameter is String : %s"), var.bstrVal); CComBSTR bstrName; it = m_coll.begin(); while (it != m_coll.end()) { hr = (*it)->get_Name(&bstrName); if (FAILED(hr)) { CALL_FAIL(GENERAL_ERR, _T("(*it)->get_Name(&bstrName)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); return hr; } if (_tcsicmp(bstrName, var.bstrVal) == 0) { // // found the desired OR Group // return hr; } it++; } hr = E_INVALIDARG; CALL_FAIL(GENERAL_ERR, _T("Group Is Not Found"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); return hr; } // //===================== ADD GROUP ================================================= // STDMETHODIMP CFaxOutboundRoutingGroups::AddGroup( /*[in]*/ FAX_OUTBOUND_ROUTING_GROUP *pInfo, /*[out]*/ IFaxOutboundRoutingGroup **ppNewGroup ) /*++ Routine name : CFaxOutboundRoutingGroups::AddGroup Routine description: Create new Group Object and add it to the Collection. If ppNewGroup is NOT NULL, return in it ptr to the new Group Object. Author: Iv Garber (IvG), Jun, 2000 Arguments: pInfo [in] - Ptr to the Group's Data ppNewGroup [out] - Ptr to the new Group Object Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::AddGroup"), hr); // // Create Group Object // CComObject<CFaxOutboundRoutingGroup> *pClass = NULL; hr = CComObject<CFaxOutboundRoutingGroup>::CreateInstance(&pClass); if (FAILED(hr) || (!pClass)) { if (!pClass) { hr = E_OUTOFMEMORY; CALL_FAIL(MEM_ERR, _T("CComObject<CFaxOutboundRoutingGroup>::CreateInstance(&pClass)"), hr); } else { CALL_FAIL(GENERAL_ERR, _T("CComObject<CFaxOutboundRoutingGroup>::CreateInstance(&pClass)"), hr); } AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Init the Group Object // hr = pClass->Init(pInfo, m_pIFaxServerInner); if (FAILED(hr)) { CALL_FAIL(GENERAL_ERR, _T("pClass->Init(pInfo, m_pIFaxServerInner)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); delete pClass; return hr; } // // Get Interface from the pClass. // This will make AddRef() on the Interface. // This is the Collection's AddRef, which is freed at Collection's Dtor. // CComPtr<IFaxOutboundRoutingGroup> pObject = NULL; hr = pClass->QueryInterface(&pObject); if (FAILED(hr) || (!pObject)) { if (!pObject) { hr = E_FAIL; } CALL_FAIL(GENERAL_ERR, _T("pClass->QueryInterface(&pObject)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); delete pClass; return hr; } // // Put the Object in the collection // try { m_coll.push_back(pObject); } catch (exception &) { hr = E_OUTOFMEMORY; AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_OUTOFMEMORY, IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(MEM_ERR, _T("m_coll.push_back(pObject)"), hr); // // pObject will call Release(), which will delete the pClass // return hr; } // // We want to save the current AddRef() to Collection // pObject.Detach(); // // Return new Group Object, if required // if (ppNewGroup) { if (::IsBadWritePtr(ppNewGroup, sizeof(IFaxOutboundRoutingGroup *))) { hr = E_POINTER; CALL_FAIL(GENERAL_ERR, _T("::IsBadWritePtr(ppNewGroup, sizeof(IFaxOutboundRoutingGroup *))"), hr); return hr; } else { *ppNewGroup = m_coll.back(); (*ppNewGroup)->AddRef(); } } return hr; } // //================= ADD ======================================================= // STDMETHODIMP CFaxOutboundRoutingGroups::Add( /*[in]*/ BSTR bstrName, /*[out, retval]*/ IFaxOutboundRoutingGroup **ppGroup ) /*++ Routine name : CFaxOutboundRoutingGroups::Add Routine description: Add new Group to the Groups Collection Author: Iv Garber (IvG), Jun, 2000 Arguments: bstrName [in] - Name of the new Group ppGroup [out] - the Group Object Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::Add"), hr, _T("Name=%s"), bstrName); // // Check if the Name is valid // if (!bstrName) { hr = E_INVALIDARG; CALL_FAIL(GENERAL_ERR, _T("Empty Group Name"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); return hr; } if (_tcsicmp(bstrName, ROUTING_GROUP_ALL_DEVICES) == 0) { // // Cannot Add the "All Devices" Group // hr = E_INVALIDARG; CALL_FAIL(GENERAL_ERR, _T("All Devices Group"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_ALLDEVICESGROUP, IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Get Fax Server Handle // HANDLE faxHandle; hr = m_pIFaxServerInner->GetHandle(&faxHandle); ATLASSERT(SUCCEEDED(hr)); if (faxHandle == NULL) { // // Fax Server is not connected // hr = Fax_HRESULT_FROM_WIN32(ERROR_NOT_CONNECTED); CALL_FAIL(GENERAL_ERR, _T("faxHandle == NULL"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Add the Group to the Fax Server // if (!FaxAddOutboundGroup(faxHandle, bstrName)) { hr = Fax_HRESULT_FROM_WIN32(GetLastError()); CALL_FAIL(GENERAL_ERR, _T("FaxAddOutboundGroup(faxHandle, bstrName)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Add the Group to the Collection // FAX_OUTBOUND_ROUTING_GROUP groupData; groupData.dwNumDevices = 0; groupData.dwSizeOfStruct = sizeof(FAX_OUTBOUND_ROUTING_GROUP); groupData.lpctstrGroupName = bstrName; groupData.lpdwDevices = NULL; groupData.Status = FAX_GROUP_STATUS_EMPTY; hr = AddGroup(&groupData, ppGroup); return hr; } // //================= REMOVE ======================================================= // STDMETHODIMP CFaxOutboundRoutingGroups::Remove( /*[in]*/ VARIANT vIndex ) /*++ Routine name : CFaxOutboundRoutingGroups::Remove Routine description: Remove Group by the given key Author: Iv Garber (IvG), Jun, 2000 Arguments: vIndex [in] - the Key to Find the Group to Remove Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::Remove"), hr); // // Find the Group // ContainerType::iterator it; hr = FindGroup(vIndex, it); if (FAILED(hr)) { return hr; } // // Take the Name of the Group // CComBSTR bstrName; hr = (*it)->get_Name(&bstrName); if (FAILED(hr)) { AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(GENERAL_ERR, _T("(*it)->get_Name(&bstrName)"), hr); return hr; } // // Check that Name is valid // if (_tcsicmp(bstrName, ROUTING_GROUP_ALL_DEVICES) == 0) { // // Cannot Remove "All Devices" Group // hr = E_INVALIDARG; CALL_FAIL(GENERAL_ERR, _T("All Devices Group"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_ALLDEVICESGROUP, IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Get Fax Server Handle // HANDLE faxHandle; hr = m_pIFaxServerInner->GetHandle(&faxHandle); ATLASSERT(SUCCEEDED(hr)); if (faxHandle == NULL) { // // Fax Server is not connected // hr = Fax_HRESULT_FROM_WIN32(ERROR_NOT_CONNECTED); CALL_FAIL(GENERAL_ERR, _T("faxHandle == NULL"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Remove from Fax Server // if (!FaxRemoveOutboundGroup(faxHandle, bstrName)) { hr = Fax_HRESULT_FROM_WIN32(GetLastError()); CALL_FAIL(GENERAL_ERR, _T("FaxRemoveOutboundGroup(faxHandle, bstrName)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); return hr; } // // If successed, remove from our collection as well // try { m_coll.erase(it); } catch(exception &) { // // Failed to remove the Group // hr = E_OUTOFMEMORY; AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(MEM_ERR, _T("m_coll.erase(it)"), hr); return hr; } return hr; } // //==================== GET ITEM =================================================== // STDMETHODIMP CFaxOutboundRoutingGroups::get_Item( /*[in]*/ VARIANT vIndex, /*[out, retval]*/ IFaxOutboundRoutingGroup **ppGroup ) /*++ Routine name : CFaxOutboundRoutingGroups::get_Item Routine description: Return Item from the Collection either by Group Name either by its Index inside the Collection. Author: Iv Garber (IvG), Jun, 2000 Arguments: vIndex [in] - Group Name or Item Index ppGroup [out] - the resultant Group Object Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::get_Item"), hr); // // Check the Ptr we have got // if (::IsBadWritePtr(ppGroup, sizeof(IFaxOutboundRoutingGroup *))) { hr = E_POINTER; AtlReportError(CLSID_FaxOutboundRoutingGroups, IDS_ERROR_INVALID_ARGUMENT, IID_IFaxOutboundRoutingGroups, hr); CALL_FAIL(GENERAL_ERR, _T("::IsBadWritePtr(ppGroup, sizeof(IFaxOutboundRoutingGroup *))"), hr); return hr; } // // Find the Group // ContainerType::iterator it; hr = FindGroup(vIndex, it); if (FAILED(hr)) { return hr; }; // // Return it to Caller // (*it)->AddRef(); *ppGroup = *it; return hr; } // //==================== INIT =================================================== // STDMETHODIMP CFaxOutboundRoutingGroups::Init( /*[in]*/ IFaxServerInner *pServer ) /*++ Routine name : CFaxOutboundRoutingGroups::Init Routine description: Initialize the Groups Collection : create all Group Objects. Author: Iv Garber (IvG), Jun, 2000 Arguments: pServer [in] - Ptr to the Fax Server Object. Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER(_T("CFaxOutboundRoutingGroups::Init"), hr); // // First, set the Ptr to the Server // hr = CFaxInitInnerAddRef::Init(pServer); if (FAILED(hr)) { return hr; } // // Get Fax Handle // HANDLE faxHandle; hr = m_pIFaxServerInner->GetHandle(&faxHandle); ATLASSERT(SUCCEEDED(hr)); if (faxHandle == NULL) { // // Fax Server is not connected // hr = Fax_HRESULT_FROM_WIN32(ERROR_NOT_CONNECTED); CALL_FAIL(GENERAL_ERR, _T("faxHandle == NULL"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Call Server to Return all OR Groups // CFaxPtr<FAX_OUTBOUND_ROUTING_GROUP> pGroups; DWORD dwNum = 0; if (!FaxEnumOutboundGroups(faxHandle, &pGroups, &dwNum)) { hr = Fax_HRESULT_FROM_WIN32(GetLastError()); CALL_FAIL(GENERAL_ERR, _T("FaxEnumOutboundGroups(faxHandle, &pGroups, &dwNum)"), hr); AtlReportError(CLSID_FaxOutboundRoutingGroups, GetErrorMsgId(hr), IID_IFaxOutboundRoutingGroups, hr); return hr; } // // Fill the Collection with Objects // for (DWORD i=0 ; i<dwNum ; i++ ) { hr = AddGroup(&pGroups[i]); if (FAILED(hr)) { return hr; } } return hr; } // //==================== CREATE ======================================== // HRESULT CFaxOutboundRoutingGroups::Create ( /*[out, retval]*/IFaxOutboundRoutingGroups **ppGroups ) /*++ Routine name : CFaxOutboundRoutingGroups::Create Routine description: Static function to create the Fax Outbound Routing Groups Collection Object Author: Iv Garber (IvG), Jun, 2000 Arguments: ppGroups [out] -- the new Fax OR Groups Collection Object Return Value: Standard HRESULT code --*/ { HRESULT hr = S_OK; DBG_ENTER (_T("CFaxOutboundRoutingGroups::Create"), hr); // // Create Instance of the Collection // CComObject<CFaxOutboundRoutingGroups> *pClass; hr = CComObject<CFaxOutboundRoutingGroups>::CreateInstance(&pClass); if (FAILED(hr)) { CALL_FAIL(GENERAL_ERR, _T("CComObject<CFaxOutboundRoutingGroups>::CreateInstance(&pClass)"), hr); return hr; } // // Return the desired Interface Ptr // hr = pClass->QueryInterface(ppGroups); if (FAILED(hr)) { CALL_FAIL(GENERAL_ERR, _T("pClass->QueryInterface(ppGroups)"), hr); return hr; } return hr; } // CFaxOutboundRoutingGroups::Create() // //===================== SUPPORT ERROR INFO ====================================== // STDMETHODIMP CFaxOutboundRoutingGroups::InterfaceSupportsErrorInfo( REFIID riid ) /*++ Routine name : CFaxOutboundRoutingGroups::InterfaceSupportsErrorInfo Routine description: ATL's implementation of the ISupportErrorInfo Interface. Author: Iv Garber (IvG), Jun, 2000 Arguments: riid [in] - Reference to the Interface Return Value: Standard HRESULT code --*/ { static const IID* arr[] = { &IID_IFaxOutboundRoutingGroups }; for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) { if (InlineIsEqualGUID(*arr[i],riid)) return S_OK; } return S_FALSE; }
17,627
6,718
// Copyright (c) 2019 LLambert // // 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, sub-license, 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 "BitConverter.h" namespace DotnetLibrary { Boolean BitConverter::IsLittleEndian = AmILittleEndian(); Boolean BitConverter::AmILittleEndian() { Double d = 1.0; Byte* b = (Byte*) &d; return (b[0] == 0); } Array* BitConverter::GetBytes(Byte* ptr, Int32 count) { Array* ret = new Array(ByteType, count); memcpy(ret->Address(0), ptr, count); return ret; } void BitConverter::PutBytes(Byte* dst, Array* src, Int32 start_index, Int32 count) { if (src == nullptr) throw new ArgumentNullException(); if (start_index < 0 || (start_index > src->get_Length() - 1)) throw new ArgumentOutOfRangeException(); // avoid integer overflow (with large pos/neg start_index values) if (src->get_Length() - count < start_index) throw new ArgumentException(); memcpy(dst, src->Address(start_index), count); } Int64 BitConverter::DoubleToInt64Bits(Double value) { return *(Int64*) &value; } Double BitConverter::Int64BitsToDouble(Int64 value) { return *(Double*) &value; } Array* BitConverter::GetBytes(Boolean value) { return GetBytes((Byte*) &value, 1); } Array* BitConverter::GetBytes(Char value) { // treat Char as Int16 because on some systems Char is 4 bytes but .Net isn't Int16 val = (Int16) value; return GetBytes((Byte*) &val, sizeof(Int16)); } Array* BitConverter::GetBytes(Double value) { return GetBytes((Byte*) &value, sizeof(Double)); } Array* BitConverter::GetBytes(Int16 value) { return GetBytes((Byte*) &value, sizeof(Int16)); } Array* BitConverter::GetBytes(Int32 value) { return GetBytes((Byte*) &value, sizeof(Int32)); } Array* BitConverter::GetBytes(Int64 value) { return GetBytes((Byte*) &value, sizeof(Int64)); } Array* BitConverter::GetBytes(Single value) { return GetBytes((Byte*) &value, sizeof(Single)); } Array* BitConverter::GetBytes(UInt16 value) { return GetBytes((Byte*) &value, sizeof(UInt16)); } Array* BitConverter::GetBytes(UInt32 value) { return GetBytes((Byte*) &value, sizeof(UInt32)); } Array* BitConverter::GetBytes(UInt64 value) { return GetBytes((Byte*) &value, sizeof(UInt64)); } Boolean BitConverter::ToBoolean(Array* value, Int32 startIndex) { if (value == nullptr) throw new ArgumentNullException(); if (startIndex < 0 || (startIndex > value->get_Length() - 1)) throw new ArgumentOutOfRangeException(); if (*(Byte*) value->Address(startIndex) != 0) return true; return false; } Char BitConverter::ToChar(Array* value, Int32 startIndex) { Int16 ret; // treat Char as Int16 because on some systems Char is 4 bytes but .Net isn't PutBytes((Byte*) &ret, value, startIndex, sizeof(Int16)); return (Char) ret; } Double BitConverter::ToDouble(Array* value, Int32 startIndex) { Double ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(Double)); return ret; } Int16 BitConverter::ToInt16(Array* value, Int32 startIndex) { Int16 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(Int16)); return ret; } Int32 BitConverter::ToInt32(Array* value, Int32 startIndex) { Int32 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(Int32)); return ret; } Int64 BitConverter::ToInt64(Array* value, Int32 startIndex) { Int64 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(Int64)); return ret; } Single BitConverter::ToSingle(Array* value, Int32 startIndex) { Single ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(Single)); return ret; } UInt16 BitConverter::ToUInt16(Array* value, Int32 startIndex) { UInt16 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(UInt16)); return ret; } UInt32 BitConverter::ToUInt32(Array* value, Int32 startIndex) { UInt32 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(UInt32)); return ret; } UInt64 BitConverter::ToUInt64(Array* value, Int32 startIndex) { UInt64 ret; PutBytes((Byte*) &ret, value, startIndex, sizeof(UInt64)); return ret; } String* BitConverter::ToString(Array* value, Int32 startIndex, Int32 length) { if (value == nullptr) throw new ArgumentNullException(); if (length == -1) length = value->get_Length() - startIndex; if (startIndex < 0 || startIndex >= value->get_Length()) { // special (but valid) case (e.g. new byte [0]) if ((startIndex == 0) && (value->get_Length() == 0)) return String::Empty; throw new ArgumentOutOfRangeException(); } if (length < 0) throw new ArgumentOutOfRangeException(); // note: re-ordered to avoid possible integer overflow if (startIndex > value->get_Length() - length) throw new ArgumentException(); if (length == 0) return String::Empty; StringBuilder builder(length * 3 - 1); Int32 end = startIndex + length; for (Int32 i = startIndex; i < end; i++) { if (i > startIndex) builder.Append(L'-'); Byte byte = *(Byte*) value->Address(i); Char high = (Char) ((byte >> 4) & 0x0f); Char low = (Char) (byte & 0x0f); if (high < 10) high += L'0'; else { high -= (Char) 10; high += L'A'; } if (low < 10) low += L'0'; else { low -= (Char) 10; low += L'A'; } builder.Append(high); builder.Append(low); } return builder.ToString(); } }
6,262
2,359
//***************************************************************** // Copyright 2015 MIT Lincoln Laboratory // Project: SPAR // Authors: OMD // Description: Unit tests for NumberedCommandReceiver // // Modifications: // Date Name Modification // ---- ---- ------------ // 09 May 2012 omd Original Version //***************************************************************** #include "numbered-command-receiver.h" #define BOOST_TEST_MODULE NumberedCommandReceiverTest #include "common/test-init.h" #include <boost/thread.hpp> #include <iostream> #include <sstream> #include <string> #include <vector> #include "extensible-ready-handler.h" #include "numbered-command-receiver-fixture.h" #include "common/logging.h" #include "common/util.h" using std::string; using std::vector; // Spawns a thread, waits a bit, then calls WriteResults with two lines, the // first line in the command_data passed to Execute and the line "DONE". class DelayedDone : public NumberedCommandHandler { public: virtual ~DelayedDone() {} virtual void Execute(LineRawData<Knot>* command_data) { // Schedule Go() on a new thread. boost::thread runner_thread( boost::bind(&DelayedDone::Go, this, command_data)); } void Go(LineRawData<Knot>* command_data) { // Sleep for a bit and then call ResultReady. boost::this_thread::sleep(boost::posix_time::milliseconds(100)); LineRawData<Knot> output_data; output_data.AddLine(command_data->Get(0)); output_data.AddLine(Knot(new string("DONE"))); WriteResults(output_data); delete command_data; Done(); } }; NumberedCommandHandler* ConstructDelayedDone() { return new DelayedDone; }; const int kBigResultsSize = 100 << 20; // Writes a HUGE results sets to make sure that works. class BigResults : public NumberedCommandHandler { public: virtual ~BigResults() {} virtual void Execute(LineRawData<Knot>* command_data) { boost::thread runner_thread(boost::bind(&BigResults::Go, this)); delete command_data; } void Go() { LineRawData<Knot> results; Knot long_line; // A huge string of 'a' characters. string* long_line_str = new string(kBigResultsSize, 'a'); results.AddLine(Knot(long_line_str)); WriteResults(results); Done(); } }; NumberedCommandHandler* ConstructBigResults() { return new BigResults; } BOOST_FIXTURE_TEST_CASE(NumberedCommandWorks, NumberedCommandReceiverFixture) { FileHandleIStream from_handler(sut_stdout_read_fd); FileHandleOStream to_handler(sut_stdin_write_fd); command_extension->AddHandler("DD", ConstructDelayedDone); // This should block until the stream is written to. string line; getline(from_handler, line); BOOST_CHECK_EQUAL(line, "READY"); line.clear(); // Inputs that should cause DelayedDone to be invoked twice. to_handler << "COMMAND 1\n" "DD foo\n" "ENDCOMMAND\n" "COMMAND 2\n" "DD bar\n" "ENDCOMMAND\n"; to_handler.flush(); // Read lines from the pipe until we see 2 more READY signals and results for // the two command above. vector<string> results; int num_ready = 0; int num_results = 0; while (num_results < 2 && num_results < 2) { getline(from_handler, line); if (line == "READY") { ++num_ready; } else if (line == "ENDRESULTS") { ++num_results; } results.push_back(line); line.clear(); } // This shouldn't have to wait since the above waited for the commands to not // only finish, but the results to arrive at the end of the pipe. command_extension->WaitForAllCommands(); // Now we should have received 2 READY signals, one after each command we // sent. Normally both would happen at once since the results of the commands // are delayed. However, there is no guarantee of that as both threads could // have been delayed until the sleep expired at which point the command might // complete before the READY token was produced. Thus, to be robust, we only // check that we got 2 ready signals. However, if any of them came after a set // of results we write a warning as we don't expect this to happen often. int num_ready_found = 0; for (size_t i = 0; i < results.size(); ++i) { if (results[i] == "READY") { ++num_ready_found; if (i > 1) { LOG(WARNING) << "Found READY after results. Unexpected."; } } } BOOST_CHECK_EQUAL(num_ready_found, 2); // We should also get results for command 1 and command 2. Since these ran in // different threads there is no ordering guarantee. However, for any one set // of results we know what the next few lines should be. int num_results_found = 0; for (size_t i = 0; i < results.size(); ++i) { if (results[i] == "RESULTS 1") { num_results_found += 1; BOOST_REQUIRE_LT(i + 2, results.size()); BOOST_CHECK_EQUAL(results[i + 1], "DD foo"); BOOST_CHECK_EQUAL(results[i + 2], "DONE"); } if (results[i] == "RESULTS 2") { num_results_found += 1; BOOST_REQUIRE_LT(i + 2, results.size()); BOOST_CHECK_EQUAL(results[i + 1], "DD bar"); BOOST_CHECK_EQUAL(results[i + 2], "DONE"); } } BOOST_CHECK_EQUAL(num_results_found, 2); } // Really big results are sent through a slightly different output path since // they are too big to be queued for output. This test ensures that these // commands work. BOOST_FIXTURE_TEST_CASE(BigResultsWork, NumberedCommandReceiverFixture) { FileHandleIStream from_handler(sut_stdout_read_fd); FileHandleOStream to_handler(sut_stdin_write_fd); command_extension->AddHandler("BIG", &ConstructBigResults); string line; getline(from_handler, line); BOOST_CHECK_EQUAL(line, "READY"); line.clear(); to_handler << "COMMAND 107\nBIG\nENDCOMMAND\n"; to_handler.flush(); // Ignore the READY line if that gets sent first. do { getline(from_handler, line); } while (line == "READY"); BOOST_CHECK_EQUAL(line, "RESULTS 107"); getline(from_handler, line); BOOST_CHECK_EQUAL(line, string(kBigResultsSize, 'a')); getline(from_handler, line); BOOST_CHECK_EQUAL(line, "ENDRESULTS"); }
6,233
2,075
#include "priv.h" #include "sccls.h" #include "menuband.h" #include "itbar.h" #include "bands.h" #include "isfband.h" #include "menubar.h" #include "../lib/dpastuff.h" // COrderList_* #include "inpobj.h" #include "theater.h" #include "resource.h" #include "oleacc.h" #include "apithk.h" #include "uemapp.h" #include "mnbase.h" #include "mnfolder.h" #include "mnstatic.h" #include "iaccess.h" #include "mluisupp.h" // BUGBUG (lamadio): Conflicts with one defined in winuserp.h #undef WINEVENT_VALID //It's tripping on this... #include "winable.h" #define DM_MISC 0 // miscellany #define PF_USINGNTSD 0x00000400 // set this if you're debugging on ntsd // This must be reset to -1 on any WM_WININICHANGE. We do it in // shbrows2.cpp, but if there are no browser windows open when the // metric changes, we end up running around with a stale value. Oh well. long g_lMenuPopupTimeout = -1; // {AD35F50A-0CC0-11d3-AE2D-00C04F8EEA99} static const CLSID CLSID_MenuBandMetrics = { 0xad35f50a, 0xcc0, 0x11d3, { 0xae, 0x2d, 0x0, 0xc0, 0x4f, 0x8e, 0xea, 0x99 } }; // Registered window messages for the menuband UINT g_nMBPopupOpen = 0; UINT g_nMBFullCancel = 0; UINT g_nMBDragCancel = 0; UINT g_nMBAutomation = 0; UINT g_nMBExecute = 0; UINT g_nMBOpenChevronMenu = 0; HCURSOR g_hCursorArrow = NULL; //UINT g_nMBIgnoreNextDeselect = 0; // Dealt with in menuisf.cpp HRESULT IUnknown_QueryServiceExec(IUnknown* punk, REFGUID guidService, const GUID *guid, DWORD cmdID, DWORD cmdParam, VARIANT* pvarargIn, VARIANT* pvarargOut); BOOL IsAncestor(HWND hwndChild, HWND hwndAncestor) { HWND hwnd = hwndChild; while (hwnd != hwndAncestor && hwnd != NULL) { hwnd = GetParent(hwnd); } return hwndAncestor == hwnd; } //================================================================= // Implementation of menuband message filter //================================================================= extern "C" void DumpMsg(LPCTSTR pszLabel, MSG * pmsg); // Just one of these, b/c we only need one message filter CMBMsgFilter g_msgfilter = { 0 }; void CMBMsgFilter::SetModal(BOOL fModal) { // There was an interesting problem: // Click on the Chevron menu. Right click Delete. // The menus were hosed // Why? // Well, I'll tell you: // We got a deactivate on the subclassed window. We have // 2 menus subclassing it: The Main menu, and the modal // chevron menu. Problem is, the main menu snagged the WM_ACTIVATE // and does a set context. This causes a Pop and releases the Message hook. // Since I still had a menu up, this caused havoc. // So I introduced a concept of a "Modal" menuband. // This says: "Ignore any request to change contexts until I'm done". When // that modal band is done, it sets the old context back in. // Seems like a hack, but we need a better underlying archtecture for // the message passing. _fModal = fModal; } void CMBMsgFilter::ReEngage(void* pvContext) { // We need to make sure that we don't dis/reengage when // switching contexts if (pvContext == _pvContext) _fEngaged = TRUE; } void CMBMsgFilter::DisEngage(void* pvContext) { if (pvContext == _pvContext) _fEngaged = FALSE; } int CMBMsgFilter::GetCount() { return FDSA_GetItemCount(&_fdsa); } int MsgFilter_GetCount() { return g_msgfilter.GetCount(); } CMenuBand * CMBMsgFilter::_GetTopPtr(void) { CMenuBand * pmb = NULL; int cItems = FDSA_GetItemCount(&_fdsa); if (0 < cItems) { MBELEM * pmbelem = FDSA_GetItemPtr(&_fdsa, cItems-1, MBELEM); pmb = pmbelem->pmb; } return pmb; } CMenuBand * CMBMsgFilter::_GetBottomMostSelected(void) { // Ick, I can't believe I just did this. Mix COM and C++ identities... Yuck. CMenuBand* pmb = NULL; if (_pmb) { IUnknown_QueryService(SAFECAST(_pmb, IMenuBand*), SID_SMenuBandBottomSelected, CLSID_MenuBand, (void**)&pmb); // Since we have the C++ identity, release the COM identity. if (pmb) pmb->Release(); } return pmb; } CMenuBand * CMBMsgFilter::_GetWindowOwnerPtr(HWND hwnd) { CMenuBand * pmb = NULL; int cItems = FDSA_GetItemCount(&_fdsa); if (0 < cItems) { // Go thru the list of bands on the stack and return the // one who owns the given window. int i; for (i = 0; i < cItems; i++) { MBELEM * pmbelem = FDSA_GetItemPtr(&_fdsa, i, MBELEM); if (pmbelem->pmb && S_OK == pmbelem->pmb->IsWindowOwner(hwnd)) { pmb = pmbelem->pmb; break; } } } return pmb; } /*---------------------------------------------------------- Purpose: Return menuband or NULL based upon hittest. pt must be in screen coords */ CMenuBand * CMBMsgFilter::_HitTest(POINT pt, HWND * phwnd) { CMenuBand * pmb = NULL; HWND hwnd = NULL; int cItems = FDSA_GetItemCount(&_fdsa); if (0 < cItems) { // Go thru the list of bands on the stack and return the // one who owns the given window. Work backwards since the // later bands are on top (z-order), if the menus ever overlap. int i = cItems - 1; while (0 <= i) { MBELEM * pmbelem = FDSA_GetItemPtr(&_fdsa, i, MBELEM); RECT rc; // Do this dynamically because the hwndBar hasn't been positioned // until after this mbelem has been pushed onto the msg filter stack. GetWindowRect(pmbelem->hwndBar, &rc); if (PtInRect(&rc, pt)) { pmb = pmbelem->pmb; hwnd = pmbelem->hwndTB; break; } i--; } } if (phwnd) *phwnd = hwnd; return pmb; } void CMBMsgFilter::RetakeCapture(void) { // The TrackPopupMenu submenus can steal the capture. Take // it back. Don't take it back if the we're in edit mode, // because the modal drag/drop loop has the capture at that // point. // We do not want to take capture unless we are engaged. // We need to do this because we are not handling mouse messages lower down // in the code. When we set the capture, the messages that we do not handle // trickle up to the top level menu, and can cause weird problems (Such // as signaling a "click out of bounds" or a context menu of the ITBar) if (_hwndCapture && !_fPreventCapture && _fEngaged) { TraceMsg(TF_MENUBAND, "CMBMsgFilter: Setting capture to %#lx", _hwndCapture); SetCapture(_hwndCapture); } } void CMBMsgFilter::SetHook(BOOL fSet, BOOL fDontIgnoreSysChar) { if (fDontIgnoreSysChar) _iSysCharStack += fSet? 1: -1; if (NULL == _hhookMsg && fSet) { TraceMsg(TF_MENUBAND, "CMBMsgFilter: Initialize"); _hhookMsg = SetWindowsHookEx(WH_GETMESSAGE, GetMsgHook, HINST_THISDLL, GetCurrentThreadId()); _fDontIgnoreSysChar = fDontIgnoreSysChar; } else if (!fSet && _iSysCharStack == 0) { TraceMsg(TF_MENUBAND, "CMBMsgFilter: Hook removed"); UnhookWindowsHookEx(_hhookMsg); _hhookMsg = NULL; } } // 1) Set Deskbars on Both Monitors and set to chevron // 2) On Monitor #2 open a chevron // 3) On Monitor #1 open a chevron then open the Start Menu // Result: Start Menu does not work. // The reason is, we set the _fModal of the global message filter. This prevents context switches. Why? // The modal flag was invented to solve context switching problems with the browser frame. So what causes this? // Well, when switching from #2 to #3, we have not switched contexts. But since we got a click out of bounds, we collapse // the previous menu. When switching from #3 to #4, neither have the context, so things get messy. void CMBMsgFilter::ForceModalCollapse() { if (_fModal) { _fModal = FALSE; SetContext(NULL, TRUE); } } void CMBMsgFilter::SetContext(void* pvContext, BOOL fSet) { TraceMsg(TF_MENUBAND, "CMBMsgFilter::SetContext from 0x%x to 0x%x", _pvContext, pvContext); // When changing a menuband context, we need to pop all of the items // in the stack. This is to prevent a race condition that can occur. // We do not want to pop all of the items off the stack if we're setting the same context. // We do a set context on Activation, Both when we switch from one Browser frame to another // but also when right clicking or causing the Rename dialog to be displayed. BOOL fPop = FALSE; if (_fModal) return; // Are we setting a new context? if (fSet) { // Is this different than the one we've got? if (pvContext != _pvContext) { // Yes, then we need to pop off all of the old items. fPop = TRUE; } _pvContext = pvContext; } else { // Then we are trying to unset the message hook. Make sure it still belongs to // this context if (pvContext == _pvContext) { // This context is trying to unset itself, and no other context owns it. // remove all the old items. fPop = TRUE; } } if (fPop) { CMenuBand* pcmb = _GetTopPtr(); if (pcmb) { PostMessage(pcmb->_pmbState->GetSubclassedHWND(), g_nMBFullCancel, 0, 0); // No release. if (FDSA_GetItemCount(&_fdsa) != 0) { while (g_msgfilter.Pop(pvContext)) ; } } } } /*---------------------------------------------------------- Purpose: Push another menuband onto the message filter's stack */ void CMBMsgFilter::Push(void* pvContext, CMenuBand * pmb, IUnknown * punkSite) { ASSERT(IS_VALID_CODE_PTR(pmb, CMenuBand)); TraceMsg(TF_MENUBAND, "CMBMsgFilter::Push called from context 0x%x", pvContext); if (pmb && pvContext == _pvContext) { BOOL bRet = TRUE; HWND hwndBand; pmb->GetWindow(&hwndBand); // If the bar isn't available use the band window HWND hwndBar = hwndBand; IOleWindow * pow; IUnknown_QueryService(punkSite, SID_SMenuPopup, IID_IOleWindow, (LPVOID *)&pow); if (pow) { pow->GetWindow(&hwndBar); pow->Release(); } if (NULL == _hhookMsg) { // We want to ignore the WM_SYSCHAR message in the message filter because // we are using the IsMenuMessage call instead of the global message hook. SetHook(TRUE, FALSE); TraceMsg(TF_MENUBAND, "CMBMsgFilter::push Setting hook from context 0x%x", pvContext); _fSetAtPush = TRUE; } if (!_fInitialized) { ASSERT(NULL == _hwndCapture); _hwndCapture = hwndBar; _fInitialized = TRUE; bRet = FDSA_Initialize(sizeof(MBELEM), CMBELEM_GROW, &_fdsa, _rgmbelem, CMBELEM_INIT); // We need to initialize this for the top level guy so that we have the correct positioning // from the start of this new set of bands. This is used to eliminate spurious WM_MOUSEMOVE // messages which cause problems. See _HandleMouseMessages for more information AcquireMouseLocation(); } if (EVAL(bRet)) { MBELEM mbelem = {0}; TraceMsg(TF_MENUBAND, "CMBMsgFilter: Push (pmp:%#08lx) onto stack", SAFECAST(pmb, IMenuPopup *)); pmb->AddRef(); mbelem.pmb = pmb; mbelem.hwndTB = hwndBand; mbelem.hwndBar = hwndBar; FDSA_AppendItem(&_fdsa, &mbelem); CMenuBand* pmbTop = _GetTopPtr(); ASSERT(pmbTop); if ((pmbTop->GetFlags() & SMINIT_LEGACYMENU) || NULL == GetCapture()) RetakeCapture(); } else { UnhookWindowsHookEx(_hhookMsg); _hhookMsg = NULL; _hwndCapture = NULL; } } } /*---------------------------------------------------------- Purpose: Pop a menuband off the message filter stack Returns the number of bands left on the stack */ int CMBMsgFilter::Pop(void* pvContext) { int nRet = 0; TraceMsg(TF_MENUBAND, "CMBMsgFilter::pop called from context 0x%x", pvContext); // This can be called from a context switch or when we're exiting menu mode, // so we'll switch off the fact that we clear _hhookMsg when we pop the top twice. if (pvContext == _pvContext && _hhookMsg) { int iItem = FDSA_GetItemCount(&_fdsa) - 1; MBELEM * pmbelem; ASSERT(0 <= iItem); pmbelem = FDSA_GetItemPtr(&_fdsa, iItem, MBELEM); if (EVAL(pmbelem->pmb)) { TraceMsg(TF_MENUBAND, "CMBMsgFilter: Pop (pmb=%#08lx) off stack", SAFECAST(pmbelem->pmb, IMenuPopup *)); pmbelem->pmb->Release(); pmbelem->pmb = NULL; } FDSA_DeleteItem(&_fdsa, iItem); if (0 == iItem) { TraceMsg(TF_MENUBAND, "CMBMsgFilter::pop removing hook from context 0x%x", pvContext); if (_fSetAtPush) SetHook(FALSE, FALSE); PreventCapture(FALSE); _fInitialized = FALSE; if (_hwndCapture && GetCapture() == _hwndCapture) { TraceMsg(TF_MENUBAND, "CMBMsgFilter: Releasing capture"); ReleaseCapture(); } _hwndCapture = NULL; } #ifdef UNIX else if (1 == iItem) { CMenuBand * pmb = _GetTopPtr(); if( pmb ) { // Change item count only if we delete successfully. if( pmb->RemoveTopLevelFocus() ) iItem = FDSA_GetItemCount(&_fdsa); } } #endif nRet = iItem; } return nRet; } LRESULT CMBMsgFilter::_HandleMouseMsgs(MSG * pmsg, BOOL bRemove) { LRESULT lRet = 0; CMenuBand * pmb; HWND hwnd = GetCapture(); // Do we still have the capture? if (hwnd != _hwndCapture) { // No; is it b/c a CTrackPopupBar has it? #if 0 // Nuke this trace because I was getting annoyed. //def DEBUG pmb = _GetTopPtr(); if (!EVAL(pmb) || !pmb->IsInSubMenu()) { // No TraceMsg(TF_WARNING, "CMBMsgFilter: someone else has the capture (%#lx)", hwnd); } #endif if (NULL == hwnd) { // There are times that we must retake the capture because // TrackPopupMenuEx has taken it, or some context menu // might have taken it, so take it back. RetakeCapture(); TraceMsg(TF_WARNING, "CMBMsgFilter: taking the capture back"); } } else { // Yes; decide what to do with it POINT pt; HWND hwndPt; MSG msgT; pt.x = GET_X_LPARAM(pmsg->lParam); pt.y = GET_Y_LPARAM(pmsg->lParam); ClientToScreen(pmsg->hwnd, &pt); if (WM_MOUSEMOVE == pmsg->message) { // The mouse cursor can send repeated WM_MOUSEMOVE messages // with the same coordinates. When the user tries to navigate // thru the menus with the keyboard, and the mouse cursor // happens to be over a menu item, these spurious mouse // messages cause us to think the menu has been invoked under // the mouse cursor. // // To avoid this unpleasant rudeness, we eat any gratuitous // WM_MOUSEMOVE messages. if (_ptLastMove.x == pt.x && _ptLastMove.y == pt.y) { pmsg->message = WM_NULL; goto Bail; } // Since this is not a duplicate point, we need to keep it around. // We will use this stored point for the above comparison AcquireMouseLocation(); if (_hcurArrow == NULL) _hcurArrow = LoadCursor(NULL, IDC_ARROW); if (GetCursor() != _hcurArrow) SetCursor(_hcurArrow); } pmb = _HitTest(pt, &hwndPt); if (pmb) { // Forward mouse message onto appropriate menuband. Note // the appropriate menuband's GetMsgFilterCB (below) will call // ScreenToClient to convert the coords correctly. // Use a stack variable b/c we don't want to confuse USER32 // by changing the coords of the real message. msgT = *pmsg; msgT.lParam = MAKELPARAM(pt.x, pt.y); lRet = pmb->GetMsgFilterCB(&msgT, bRemove); // Remember the changed message (if there was one) pmsg->message = msgT.message; } // Debug note: to debug menubands on ntsd, set the prototype // flag accordingly. This will keep menubands from going // away the moment the focus changes to the NTSD window. else if ((WM_LBUTTONDOWN == pmsg->message || WM_RBUTTONDOWN == pmsg->message) && !(g_dwPrototype & PF_USINGNTSD)) { // Mouse down happened outside the menu. Bail. pmb = _GetTopPtr(); if (EVAL(pmb)) { msgT.hwnd = pmsg->hwnd; msgT.message = g_nMBFullCancel; msgT.wParam = 0; msgT.lParam = 0; TraceMsg(TF_MENUBAND, "CMBMsgFilter (pmb=%#08lx): hittest outside, bailing", SAFECAST(pmb, IMenuPopup *)); pmb->GetMsgFilterCB(&msgT, bRemove); } #if 0 // Now send the message to the originally intended window SendMessage(pmsg->hwnd, pmsg->message, pmsg->wParam, pmsg->lParam); #endif } else { pmb = _GetTopPtr(); if (pmb) { IUnknown_QueryServiceExec(SAFECAST(pmb, IOleCommandTarget*), SID_SMenuBandBottom, &CGID_MenuBand, MBANDCID_SELECTITEM, MBSI_NONE, NULL, NULL); } } } Bail: return lRet; } /*---------------------------------------------------------- Purpose: Message hook used to track keyboard and mouse messages while the menuband is "active". The menuband can't steal the focus away -- we use this hook to catch messages. */ LRESULT CMBMsgFilter::GetMsgHook(int nCode, WPARAM wParam, LPARAM lParam) { LRESULT lRet = 0; MSG * pmsg = (MSG *)lParam; BOOL bRemove = (PM_REMOVE == wParam); // The global message filter may be in a state when we are not processing messages, // but the menubands are still displayed. A situation where this will occur is when // a dialog box is displayed because of an interaction with the menus. // Are we engaged? (Are we allowed to process messages?) if (g_msgfilter._fEngaged) { if (WM_SYSCHAR == pmsg->message) { // _fDontIgnoreSysChar is set when the Menubands ONLY want to know about // WM_SYSCHAR and nothing else. if (g_msgfilter._fDontIgnoreSysChar) { CMenuBand * pmb = g_msgfilter.GetTopMostPtr(); if (pmb) lRet = pmb->GetMsgFilterCB(pmsg, bRemove); } } else if (g_msgfilter._fInitialized) // Only filter if we are initalized (have items on the stack) { switch (nCode) { case HC_ACTION: #ifdef DEBUG if (g_dwDumpFlags & DF_GETMSGHOOK) DumpMsg(TEXT("GetMsg"), pmsg); #endif // A lesson about GetMsgHook: it gets the same message // multiple times for as long as someone calls PeekMessage // with the PM_NOREMOVE flag. So we want to take action // only when PM_REMOVE is set (so we don't handle more than // once). If we modify any messages to redirect them (on a // regular basis), we must modify all the time so we don't // confuse the app. // Messages get redirected to different bands in the stack // in this way: // // 1) Keyboard messages go to the currently open submenu // (topmost on the stack). // // 2) The PopupOpen message goes to the hwnd that belongs // to the menu band (via IsWindowOwner). // switch (pmsg->message) { case WM_SYSKEYDOWN: case WM_KEYDOWN: case WM_CHAR: case WM_KEYUP: case WM_CLOSE: // only this message filter gets WM_CLOSE { // There is a situation that can occur when the last selected // menu pane is NOT the bottom most pane. // We need to see if that last selected guy is tracking a context // menu so that we forward the messages correctly. CMenuBand * pmb = g_msgfilter._GetBottomMostSelected(); if (pmb) { // Is it tracking a context menu? if (S_OK == IUnknown_Exec(SAFECAST(pmb, IMenuBand*), &CGID_MenuBand, MBANDCID_ISTRACKING, 0, NULL, NULL)) { // Yes, forward for proper handling. lRet = pmb->GetMsgFilterCB(pmsg, bRemove); } else { // No; Then do the default processing. This can happen if there is no // context menu, but there is a selected parent and not a selected child. goto TopHandler; } } else { TopHandler: pmb = g_msgfilter._GetTopPtr(); if (pmb) lRet = pmb->GetMsgFilterCB(pmsg, bRemove); } } break; case WM_NULL: // Handle this here (we do nothing) to avoid mistaking this for // g_nMBPopupOpen below, in case g_nMBPopupOpen is 0 if // RegisterWindowMessage fails. break; default: if (bRemove && IsInRange(pmsg->message, WM_MOUSEFIRST, WM_MOUSELAST)) { lRet = g_msgfilter._HandleMouseMsgs(pmsg, bRemove); } else if (pmsg->message == g_nMBPopupOpen) { CMenuBand * pmb = g_msgfilter._GetWindowOwnerPtr(pmsg->hwnd); if (pmb) lRet = pmb->GetMsgFilterCB(pmsg, bRemove); } else if (pmsg->message == g_nMBExecute) { CMenuBand * pmb = g_msgfilter._GetWindowOwnerPtr(pmsg->hwnd); if (pmb) { VARIANT var; var.vt = VT_UINT_PTR; var.ullVal = (UINT_PTR)pmsg->hwnd; pmb->Exec(&CGID_MenuBand, MBANDCID_EXECUTE, (DWORD)pmsg->wParam, &var, NULL); } } break; } break; default: if (0 > nCode) return CallNextHookEx(g_msgfilter._hhookMsg, nCode, wParam, lParam); break; } } } // Pass it on to the next hook in the chain if (0 == lRet) return CallNextHookEx(g_msgfilter._hhookMsg, nCode, wParam, lParam); return 0; // Always return 0 } //================================================================= // Implementation of CMenuBand //================================================================= // Struct used by EXEC with a MBANDCID_GETFONTS to return fonts typedef struct tagMBANDFONTS { HFONT hFontMenu; // [out] TopLevelMenuBand's menu font HFONT hFontArrow; // [out] TopLevelMenuBand's font for drawing the cascade arrow int cyArrow; // [out] Height of TopLevelMenuBand's cascade arrow int cxArrow; // [out] Width of TopLevelMenuBand's cascade arrow int cxMargin; // [out] Margin b/t text and arrow } MBANDFONTS; #define THISCLASS CMenuBand #define SUPERCLASS CToolBand #ifdef DEBUG int g_nMenuLevel = 0; #define DBG_THIS _nMenuLevel, SAFECAST(this, IMenuPopup *) #else #define DBG_THIS 0, 0 #endif CMenuBand::CMenuBand() : SUPERCLASS() { _fCanFocus = TRUE; _fAppActive = TRUE; _nItemNew = -1; _nItemCur = -1; _nItemTimer = -1; _uIconSize = ISFBVIEWMODE_SMALLICONS; _uIdAncestor = ANCESTORDEFAULT; _nItemSubMenu = -1; } // The purpose of this method is to finish initializing Menubands, // since it can be initialized in many ways. void CMenuBand::_Initialize(DWORD dwFlags) { _fVertical = !BOOLIFY(dwFlags & SMINIT_HORIZONTAL); _fTopLevel = BOOLIFY(dwFlags & SMINIT_TOPLEVEL); _dwFlags = dwFlags; // We cannot have a horizontal menu if it is not the toplevel menu ASSERT(!_fVertical && _fTopLevel || _fVertical); if (_fTopLevel) { if (!g_nMBPopupOpen) { g_nMBPopupOpen = RegisterWindowMessage(TEXT("CMBPopupOpen")); g_nMBFullCancel = RegisterWindowMessage(TEXT("CMBFullCancel")); g_nMBDragCancel = RegisterWindowMessage(TEXT("CMBDragCancel")); g_nMBAutomation = RegisterWindowMessage(TEXT("CMBAutomation")); g_nMBExecute = RegisterWindowMessage(TEXT("CMBExecute")); g_nMBOpenChevronMenu = RegisterWindowMessage(TEXT("CMBOpenChevronMenu")); g_hCursorArrow = LoadCursor(NULL, IDC_ARROW); TraceMsg(TF_MENUBAND, "CMBPopupOpen message = %#lx", g_nMBPopupOpen); TraceMsg(TF_MENUBAND, "CMBFullCancel message = %#lx", g_nMBFullCancel); } if (!_pmbState) _pmbState = new CMenuBandState; } DEBUG_CODE( _nMenuLevel = -1; ) } CMenuBand::~CMenuBand() { // the message filter does not have a ref'd pointer to us!!! if (g_msgfilter.GetTopMostPtr() == this) g_msgfilter.SetTopMost(NULL); _CallCB(SMC_DESTROY); ATOMICRELEASE(_psmcb); // Cleanup CloseDW(0); if (_pmtbMenu) delete _pmtbMenu; if (_pmtbShellFolder) delete _pmtbShellFolder; ASSERT(_punkSite == NULL); ATOMICRELEASE(_pmpTrackPopup); ATOMICRELEASE(_pmbm); if (_fTopLevel) { if (_pmbState) delete _pmbState; } } /*---------------------------------------------------------- Purpose: Create-instance function for class factory */ HRESULT CMenuBand_CreateInstance(IUnknown* pUnkOuter, IUnknown** ppunk, LPCOBJECTINFO poi) { // aggregation checking is handled in class factory HRESULT hres = E_OUTOFMEMORY; CMenuBand* pObj = new CMenuBand(); if (pObj) { *ppunk = SAFECAST(pObj, IShellMenu*); hres = S_OK; } return hres; } /*---------------------------------------------------------- Purpose: Internal create-instance function */ CMenuBand * CMenuBand_Create(IShellFolder* psf, LPCITEMIDLIST pidl, BOOL bHorizontal) { CMenuBand * pmb = NULL; if (psf || pidl) { DWORD dwFlags = bHorizontal ? (SMINIT_HORIZONTAL | SMINIT_TOPLEVEL) : 0; pmb = new CMenuBand(); if (pmb) { pmb->_Initialize(dwFlags); pmb->SetShellFolder(psf, pidl, NULL, 0); } } return pmb; } #ifdef UNIX BOOL CMenuBand::RemoveTopLevelFocus() { if( _fTopLevel ) { _CancelMode( MPOS_CANCELLEVEL ); return TRUE; } return FALSE; } #endif void CMenuBand::_UpdateButtons() { if (_pmtbMenu) _pmtbMenu->v_UpdateButtons(FALSE); if (_pmtbShellFolder) _pmtbShellFolder->v_UpdateButtons(FALSE); _fForceButtonUpdate = FALSE; } HRESULT CMenuBand::ForwardChangeNotify(LONG lEvent, LPCITEMIDLIST pidl1, LPCITEMIDLIST pidl2) { // Given a change notify from the ShellFolder child, we will forward that notify to each of our // sub menus, but only if they have a shell folder child. HRESULT hres = E_FAIL; BOOL fDone = FALSE; CMenuToolbarBase* pmtb = _pmtbBottom; // Start With the bottom toolbar. This is // is an optimization because typically // menus that have both a Shell Folder portion // and a static portion have the majority // of the change activity in the bottom portion. // This can be NULL on a shutdown, when we're deregistering change notifies if (pmtb) { HWND hwnd = pmtb->_hwndMB; for (int iButton = 0; !fDone; iButton++) { IShellChangeNotify* ptscn; int idCmd = GetButtonCmd(hwnd, iButton); #ifdef DEBUG TCHAR szSubmenuName[MAX_PATH]; SendMessage(hwnd, TB_GETBUTTONTEXT, idCmd, (LPARAM)szSubmenuName); TraceMsg(TF_MENUBAND, "CMenuBand: Forwarding Change notify to %s", szSubmenuName); #endif // If it's not a seperator, see if there is a sub menu with a shell folder child. if (idCmd != -1 && SUCCEEDED(pmtb->v_GetSubMenu(idCmd, &SID_MenuShellFolder, IID_IShellChangeNotify, (void**)&ptscn))) { IShellMenu* psm; // Don't forward this notify if the sub menu has specifically registered for change notify (By not passing // DontRegisterChangeNotify. if (SUCCEEDED(ptscn->QueryInterface(IID_IShellMenu, (void**)&psm))) { UINT uIdParent = 0; DWORD dwFlags = 0; // Get the flags psm->GetShellFolder(&dwFlags, NULL, IID_NULL, NULL); psm->GetMenuInfo(NULL, &uIdParent, NULL, NULL); // If this menupane is an "Optimized" pane, (meaning that we don't register for change notify // and forward from a top level menu down) then we want to forward. We also // forward if this is a child of Menu Folder. If it is a child, // then it also does not register for change notify, but does not explicitly set it in it's flags // (review: Should we set it in it's flags?) // If it is not an optimized pane, then don't forward. if ((dwFlags & SMSET_DONTREGISTERCHANGENOTIFY) || uIdParent == MNFOLDER_IS_PARENT) { // There is!, then pass to the child the change. hres = ptscn->OnChange(lEvent, pidl1, pidl2); // Update Dir on a Recursive change notify forces us to update everyone... Good thing // this does not happen alot and is caused by user interaction most of the time. } psm->Release(); } ptscn->Release(); } // Did we go through all of the buttons on this toolbar? if (iButton >= ToolBar_ButtonCount(hwnd) - 1) { // Yes, then we need to switch to the next toolbar. if (_pmtbTop != _pmtbBottom && pmtb != _pmtbTop) { pmtb = _pmtbTop; hwnd = pmtb->_hwndMB; iButton = -1; // -1 because at the end of the loop the for loop will increment. } else { // No; Then we must be done. fDone = TRUE; } } } } else hres = S_OK; // Return success because we're shutting down. return hres; } // Resize the parent menubar VOID CMenuBand::ResizeMenuBar() { // If we're not shown, then we do not need to do any kind of resize. // NOTE: Horizontal menubands are always shown. Don't do any of the // vertical stuff if we're horizontal. if (!_fShow) return; // If we're horizontal, don't do any Vertical sizing stuff. if (!_fVertical) { // BandInfoChanged is only for Horizontal Menubands. _BandInfoChanged(); return; } // We need to update the buttons before a resize so that the band is the right size. _UpdateButtons(); // Have the menubar think about changing its height IUnknown_QueryServiceExec(_punkSite, SID_SMenuPopup, &CGID_MENUDESKBAR, MBCID_RESIZE, 0, NULL, NULL); } STDMETHODIMP CMenuBand::QueryInterface(REFIID riid, void **ppvObj) { HRESULT hres; static const QITAB qit[] = { QITABENT(CMenuBand, IMenuPopup), QITABENT(CMenuBand, IMenuBand), QITABENT(CMenuBand, IShellMenu), QITABENT(CMenuBand, IWinEventHandler), QITABENT(CMenuBand, IShellMenuAcc), { 0 }, }; hres = QISearch(this, (LPCQITAB)qit, riid, ppvObj); if (FAILED(hres)) hres = SUPERCLASS::QueryInterface(riid, ppvObj); // BUGBUG (lamadio) 8.5.98: Nuke this. We should not expose the this pointer, // this is a bastardization of COM. if (FAILED(hres) && IsEqualGUID(riid, CLSID_MenuBand)) { AddRef(); *ppvObj = (LPVOID)this; hres = S_OK; } return hres; } /*---------------------------------------------------------- Purpose: IServiceProvider::QueryService method */ STDMETHODIMP CMenuBand::QueryService(REFGUID guidService, REFIID riid, void **ppvObj) { HRESULT hres = E_FAIL; *ppvObj = NULL; // assume error if (IsEqualIID(guidService, SID_SMenuPopup) || IsEqualIID(guidService, SID_SMenuBandChild) || IsEqualIID(guidService, SID_SMenuBandParent) || (_fTopLevel && IsEqualIID(guidService, SID_SMenuBandTop))) { if (IsEqualIID(riid, IID_IAccessible) || IsEqualIID(riid, IID_IDispatch)) { hres = E_OUTOFMEMORY; CAccessible* pacc = new CAccessible(SAFECAST(this, IMenuBand*)); if (pacc) { hres = pacc->InitAcc(); if (SUCCEEDED(hres)) { hres = pacc->QueryInterface(riid, ppvObj); } pacc->Release(); } } else hres = QueryInterface(riid, ppvObj); } else if (IsEqualIID(guidService, SID_SMenuBandBottom) || IsEqualIID(guidService, SID_SMenuBandBottomSelected)) { // SID_SMenuBandBottom queries down BOOL fLookingForSelected = IsEqualIID(SID_SMenuBandBottomSelected, guidService); // Are we the leaf node? if (!_fInSubMenu) { if ( fLookingForSelected && (_pmtbTracked == NULL || ToolBar_GetHotItem(_pmtbTracked->_hwndMB) == -1)) { hres = E_FAIL; } else { hres = QueryInterface(riid, ppvObj); // Yes; QI ourselves } } else { // No; QS down... IMenuPopup* pmp = _pmpSubMenu; if (_pmpTrackPopup) pmp = _pmpTrackPopup; ASSERT(pmp); hres = IUnknown_QueryService(pmp, guidService, riid, ppvObj); if (FAILED(hres) && fLookingForSelected && _pmtbTracked != NULL) { hres = QueryInterface(riid, ppvObj); // Yes; QI ourselves } } } else if (IsEqualIID(guidService, SID_MenuShellFolder)) { // This is a method of some other menu in the scheme to get to specifically the MenuShellfolder, // This is for the COM Identity property. if (_pmtbShellFolder) hres = _pmtbShellFolder->QueryInterface(riid, ppvObj); } else hres = SUPERCLASS::QueryService(guidService, riid, ppvObj); return hres; } /*---------------------------------------------------------- Purpose: IWinEventHandler::IsWindowOwner method */ STDMETHODIMP CMenuBand::IsWindowOwner(HWND hwnd) { if (( _pmtbShellFolder && (_pmtbShellFolder->IsWindowOwner(hwnd) == S_OK) ) || (_pmtbMenu && (_pmtbMenu->IsWindowOwner(hwnd) == S_OK))) return S_OK; return S_FALSE; } #define MB_EICH_FLAGS (EICH_SSAVETASKBAR | EICH_SWINDOWMETRICS | EICH_SPOLICY | EICH_SSHELLMENU | EICH_KWINPOLICY) /*---------------------------------------------------------- Purpose: IWinEventHandler::OnWinEvent method Processes messages passed on from the bandsite. */ STDMETHODIMP CMenuBand::OnWinEvent(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *plres) { HRESULT hres = NOERROR; EnterModeless(); // Could our metrics be changing? (We keep track of this only for the // toplevel menu) BOOL fProcessSettingChange = FALSE; switch (uMsg) { case WM_SETTINGCHANGE: fProcessSettingChange = !lParam || (SHIsExplorerIniChange(wParam, lParam) & MB_EICH_FLAGS); break; case WM_SYSCOLORCHANGE: case WM_DISPLAYCHANGE: fProcessSettingChange = TRUE; break; } if (_fTopLevel && fProcessSettingChange && _pmbState && !_pmbState->IsProcessingChangeNotify()) { // There is a race condition that can occur during a refresh // that's really nasty. It causes another one to get pumped in the // middle of processing this one, Yuck! _pmbState->PushChangeNotify(); // There is a race condiction that can occur when the menuband is created, // but not yet initialized. This has been hit by the IEAK group.... if (_pmtbTop) { // Yes; create a new metrics object and tell the submenus // about it. CMenuBandMetrics* pmbm = new CMenuBandMetrics(_pmtbTop->_hwndMB); if (pmbm) { ATOMICRELEASE(_pmbm); _pmbm = pmbm; if (_pmtbMenu) _pmtbMenu->SetMenuBandMetrics(_pmbm); if (_pmtbShellFolder) _pmtbShellFolder->SetMenuBandMetrics(_pmbm); _CallCB(SMC_REFRESH, wParam, lParam); // We need to force a button update at some point so that the new sizes are calculated // Setting this flag will cause the buttons to be updatted before the next time it // is shown. If, however, the menu is currently displayed, then the ResizeMenuBar will // recalculate immediatly. _fForceButtonUpdate = TRUE; RECT rcOld; RECT rcNew; // Resize the MenuBar GetClientRect(_hwndParent, &rcOld); ResizeMenuBar(); GetClientRect(_hwndParent, &rcNew); // If the rect sizes haven't changed, then we need to re-layout the // band because the button widths may have changed. if (EqualRect(&rcOld, &rcNew) && _fVertical) _pmtbTop->NegotiateSize(); } } if (_pmtbMenu) hres = _pmtbMenu->OnWinEvent(hwnd, uMsg, wParam, lParam, plres); if (_pmtbShellFolder) hres = _pmtbShellFolder->OnWinEvent(hwnd, uMsg, wParam, lParam, plres); _pmbState->PopChangeNotify(); } else { if (_pmtbMenu && (_pmtbMenu->IsWindowOwner(hwnd) == S_OK) ) hres = _pmtbMenu->OnWinEvent(hwnd, uMsg, wParam, lParam, plres); if (_pmtbShellFolder && (_pmtbShellFolder->IsWindowOwner(hwnd) == S_OK) ) hres = _pmtbShellFolder->OnWinEvent(hwnd, uMsg, wParam, lParam, plres); } ExitModeless(); return hres; } /*---------------------------------------------------------- Purpose: IOleWindow::GetWindow method */ STDMETHODIMP CMenuBand::GetWindow(HWND * phwnd) { // We assert that only a real menu can be hosted in a standard // bandsite (we're talking about the horizontal menubar). // So we only return the window associated with the static // menu. if (_pmtbMenu) { *phwnd = _pmtbMenu->_hwndMB; return NOERROR; } else { *phwnd = NULL; return E_FAIL; } } /*---------------------------------------------------------- Purpose: IOleWindow::ContextSensitiveHelp method */ STDMETHODIMP CMenuBand::ContextSensitiveHelp(BOOL bEnterMode) { return SUPERCLASS::ContextSensitiveHelp(bEnterMode); } /*---------------------------------------------------------- Purpose: Handle WM_CHAR for accelerators This is handled for any vertical menu. Since we have two toolbars (potentially), this function determines which toolbar gets the message depending on the accelerator. */ HRESULT CMenuBand::_HandleAccelerators(MSG * pmsg) { TCHAR ch = (TCHAR)pmsg->wParam; HWND hwndTop = _pmtbTop->_hwndMB; HWND hwndBottom = _pmtbBottom->_hwndMB; // Here's how this works: the menu can have one or two toolbars. // // One toolbar: we simply forward the message onto the toolbar // and let it handle any potential accelerators. // // Two toolbars: get the count of accelerators that match the // given char for each toolbar. If only one toolbar has at // least one match, forward the message onto that toolbar. // Otherwise, forward the message onto the currently tracked // toolbar and let it negotiate which accelerator button to // choose (we might get a TBN_WRAPHOTITEM). // // If no match occurs, we beep. Beep beep. // if (!_pmtbTracked) SetTracked(_pmtbTop); ASSERT(_pmtbTracked); if (_pmtbTop != _pmtbBottom) { int iNumBottomAccel; int iNumTopAccel; // Tell the dup handler not to handle this one.... _fProcessingDup = TRUE; ToolBar_HasAccelerator(hwndTop, ch, &iNumTopAccel); ToolBar_HasAccelerator(hwndBottom, ch, &iNumBottomAccel); BOOL bBottom = (0 < iNumBottomAccel); BOOL bTop = (0 < iNumTopAccel); // Does one or the other (but not both) have an accelerator? if (bBottom ^ bTop) { // Yes; do the work here for that specific toolbar HWND hwnd = bBottom ? hwndBottom : hwndTop; int cAccel = bBottom ? iNumBottomAccel : iNumTopAccel; int idCmd; pmsg->message = WM_NULL; // no need to forward the message // This should never really fail since we just checked EVAL( ToolBar_MapAccelerator(hwnd, ch, &idCmd) ); DWORD dwFlags = HICF_ACCELERATOR | HICF_RESELECT; if (cAccel == 1) dwFlags |= HICF_TOGGLEDROPDOWN; int iPos = ToolBar_CommandToIndex(hwnd, idCmd); ToolBar_SetHotItem2(hwnd, iPos, dwFlags); } // No; were there no accelerators? else if ( !bTop ) { // Yes if (_fVertical) { MessageBeep(MB_OK); } else { _CancelMode(MPOS_FULLCANCEL); } } // Else allow the message to go to the top toolbar _fProcessingDup = FALSE; } return NOERROR; } /*---------------------------------------------------------- Purpose: Callback for the get message filter. We handle the keyboard messages here (rather than IInputObject:: TranslateAcceleratorIO) so that we can redirect the message *and* have the message pump still call TranslateMessage to generate WM_CHAR and WM_SYSCHAR messages. */ LRESULT CMenuBand::GetMsgFilterCB(MSG * pmsg, BOOL bRemove) { // (See the note in CMBMsgFilter::GetMsgHook about bRemove.) if (bRemove && !_fVertical && (pmsg->message == g_nMBPopupOpen) && _pmtbTracked) { // Menu is being popped open, send a WM_MENUSELECT equivalent. _pmtbTracked->v_SendMenuNotification((UINT)pmsg->wParam, FALSE); } if (_fTopLevel && // Only do this for the top level _dwFlags & SMINIT_USEMESSAGEFILTER && // They want to use the message filter // instead of IsMenuMessage bRemove && // Only do this if we're removing it. WM_SYSCHAR == pmsg->message) // We only care about WM_SYSCHAR { // We intercept Alt-key combos (when pressed together) here, // to prevent USER from going into a false menu loop check. // There are compatibility problems if we let that happen. // // Sent by USER32 when the user hits an Alt-char combination. // We need to translate this into popping down the correct // menu. Normally we intercept this in the message pump // if (_OnSysChar(pmsg, TRUE) == S_OK) { pmsg->message = WM_NULL; } } // If a user menu is up, then we do not want to intercept those messages. Intercepting // messages intended for the poped up user menu causes havoc with keyboard accessibility. // We also don't want to process messages if we're displaying a sub menu (It should be // handling them). BOOL fTracking = FALSE; if (_pmtbMenu) fTracking = _pmtbMenu->v_TrackingSubContextMenu(); if (_pmtbShellFolder && !fTracking) fTracking = _pmtbShellFolder->v_TrackingSubContextMenu(); if (!_fInSubMenu && !fTracking) { // We don't process these messages when we're in a (modal) submenu switch (pmsg->message) { case WM_SYSKEYDOWN: case WM_KEYDOWN: // Don't process IME message. Restore original VK value. if (g_fRunOnFE && VK_PROCESSKEY == pmsg->wParam) pmsg->wParam = ImmGetVirtualKey(pmsg->hwnd); if (bRemove && (VK_ESCAPE == pmsg->wParam || VK_MENU == pmsg->wParam)) { TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Received Esc in msg filter", DBG_THIS); DWORD dwSelect = (VK_ESCAPE == pmsg->wParam) ? MPOS_CANCELLEVEL : MPOS_FULLCANCEL; _CancelMode(dwSelect); pmsg->message = WM_NULL; return 1; } // Fall thru case WM_CHAR: // Hitting the spacebar should invoke the system menu if (!_fVertical && WM_CHAR == pmsg->message && TEXT(' ') == (TCHAR)pmsg->wParam) { // We need to leave this modal loop before bringing // up the system menu (otherwise the user would need to // hit Alt twice to get out.) Post the message. TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Leaving menu mode for system menu", DBG_THIS); UIActivateIO(FALSE, NULL); // Say the Alt-key is down to catch DefWindowProc's attention pmsg->lParam |= 0x20000000; pmsg->message = WM_SYSCHAR; // Use the parent of the toolbar, because toolbar does not // forward WM_SYSCHAR onto DefWindowProc. pmsg->hwnd = GetParent(_pmtbTop->_hwndMB); return 1; } else if (_fVertical && WM_CHAR == pmsg->message && pmsg->wParam != VK_RETURN) { #ifdef UNICODE // Need to do this before we ask the toolbars.. // [msadek], On win9x we get the message thru a chain from explorer /iexplore (ANSI app.). // and pass it to comctl32 (Unicode) so it will fail to match the hot key. // the system sends the message with ANSI char and we treated it as Unicode. // It looks like noone is affected with this bug (US, FE) since they have hot keys always in Latin. // Bidi platforms are affected since they do have hot keys in native language. if(!g_fRunningOnNT) { char szCh[2]; WCHAR wszCh[2]; szCh[0] = (BYTE)pmsg->wParam; szCh[1] = '\0'; if(MultiByteToWideChar(CP_ACP, 0, (LPCSTR)szCh, ARRAYSIZE(szCh), wszCh, ARRAYSIZE(wszCh))) { memcpy(&(pmsg->wParam), wszCh, sizeof(WCHAR)); } } #endif // UNICODE // We do not want to pass VK_RETURN to _HandleAccelerators // because it will try to do a character match. When it fails // it will beep. Then we pass the VK_RETURN to the tracked toolbar // and it executes the command. // Handle accelerators here _HandleAccelerators(pmsg); } // Fall thru case WM_KEYUP: // Collection point for most key messages... if (NULL == _pmtbTracked) { // Normally we default to the top toolbar, unless that toolbar // cannot receive the selection (As is the case on the top level // start menu where the fast items are (Empty). // Can the top toolbar be cycled into? if (!_pmtbTop->DontShowEmpty()) { // Yes; SetTracked(_pmtbTop); // default to the top toolbar } else { // No; Set the tracked to the bottom, and hope that he can.... SetTracked(_pmtbBottom); } } // F10 has special meaning for menus. // - F10 alone, should toggle the selection of the first item // in a horizontal menu // - Shift-F10 should display a context menu. if (VK_F10 == pmsg->wParam) { // Is this the Shift-F10 Case? if (GetKeyState(VK_SHIFT) < 0) { // Yes. We need to force this message into a context menu // message. pmsg->message = WM_CONTEXTMENU; pmsg->lParam = -1; pmsg->wParam = (WPARAM)_pmtbTracked->_hwndMB; return 0; } else if (!_fVertical) //No; Then we need to toggle in the horizontal case { // Set the hot item to the first one. int iHot = 0; if (ToolBar_GetHotItem(_pmtbMenu->_hwndMB) != -1) iHot = -1; // We're toggling the selection off. ToolBar_SetHotItem(_pmtbMenu->_hwndMB, iHot); return 0; } } // Redirect to the toolbar pmsg->hwnd = _pmtbTracked->_hwndMB; return 0; case WM_NULL: // Handle this here (we do nothing) to avoid mistaking this for // g_nMBPopupOpen below, in case g_nMBPopupOpen is 0 if // RegisterWindowMessage fails. return 0; default: // We used to handle g_nMBPopupOpen here. But we can't because calling TrackPopupMenu // (via CTrackPopupBar::Popup) w/in a GetMessageFilter is very bad. break; } } if (bRemove) { // These messages must be processed even when no submenu is open switch (pmsg->message) { case WM_CLOSE: // Being deactivated. Bail out of menus. TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): sending MPOS_FULLCANCEL", DBG_THIS); _CancelMode(MPOS_FULLCANCEL); break; default: if (IsInRange(pmsg->message, WM_MOUSEFIRST, WM_MOUSELAST)) { // If we move the mouse, collapse the tip. Careful not to blow away a balloon tip... if (_pmbState) _pmbState->HideTooltip(FALSE); if (_pmtbShellFolder) _pmtbShellFolder->v_ForwardMouseMessage(pmsg->message, pmsg->wParam, pmsg->lParam); if (_pmtbMenu) _pmtbMenu->v_ForwardMouseMessage(pmsg->message, pmsg->wParam, pmsg->lParam); // Don't let the message be dispatched now that we've // forwarded it. pmsg->message = WM_NULL; } else if (pmsg->message == g_nMBFullCancel) { // Popup TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Received private full cancel message", DBG_THIS); _SubMenuOnSelect(MPOS_CANCELLEVEL); _CancelMode(MPOS_FULLCANCEL); return 1; } break; } } return 0; } /*---------------------------------------------------------- Purpose: Handle WM_SYSCHAR This is handled for the toplevel menu only. */ HRESULT CMenuBand::_OnSysChar(MSG * pmsg, BOOL bFirstDibs) { TCHAR ch = (TCHAR)pmsg->wParam; // HACKHACK (scotth): I'm only doing all this checking because I don't // understand why the doc-obj case sometimes (and sometimes doesn't) // intercept this in its message filter. if (!bFirstDibs && _fSysCharHandled) { _fSysCharHandled = FALSE; return S_FALSE; } if (TEXT(' ') == (TCHAR)pmsg->wParam) { _fAltSpace = TRUE; // In the words of Spock..."Remember" // start menu alt+space TraceMsg(DM_MISC, "cmb._osc: alt+space _fTopLevel(1)"); UEMFireEvent(&UEMIID_SHELL, UEME_INSTRBROWSER, UEMF_INSTRUMENT, UIBW_UIINPUT, UIBL_INPMENU); } else if (!_fInSubMenu) { int idBtn; ASSERT(_fTopLevel); // There is a brief instant when we're merging a menu and pumping messages // This results in a null _pmtbMenu. if (_pmtbMenu) { // Only a toplevel menubar follows this codepath. This means only // the static menu toolbar will exist (and not the shellfolder toolbar). _pmtbTracked = _pmtbMenu; HWND hwnd = _pmtbTracked->_hwndMB; #ifdef UNICODE // [msadek], On win9x we get the message thru a chain from explorer /iexplore (ANSI app.). // and pass it to comctl32 (Unicode) so it will fail to match the hot key. // the system sends the message with ANSI char and we treated it as Unicode. // It looks like noone is affected with this bug (US, FE) since they have hot keys always in Latin. // Bidi platforms are affected since they do have hot keys in native language. if(!g_fRunningOnNT) { char szCh[2]; WCHAR wszCh[2]; szCh[0] = (BYTE)ch; szCh[1] = '\0'; if(MultiByteToWideChar(CP_ACP, 0, (LPCSTR)szCh, ARRAYSIZE(szCh), wszCh, ARRAYSIZE(wszCh))) { memcpy(&ch, wszCh, sizeof(WCHAR)); } } #endif // UNICODE if (ToolBar_MapAccelerator(hwnd, ch, &idBtn)) { // Post a message since we're already in a menu loop TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): WM_SYSCHAR: Posting CMBPopup message", DBG_THIS); UIActivateIO(TRUE, NULL); _pmtbTracked->PostPopup(idBtn, TRUE, TRUE); // browser menu alt+key, start menu alt+key TraceMsg(DM_MISC, "cmb._osc: alt+key _fTopLevel(1)"); UEMFireEvent(&UEMIID_SHELL, UEME_INSTRBROWSER, UEMF_INSTRUMENT, UIBW_UIINPUT, UIBL_INPMENU); return S_OK; } } } // Set or reset _fSysCharHandled = bFirstDibs ? TRUE : FALSE; return S_FALSE; } HRESULT CMenuBand::_ProcessMenuPaneMessages(MSG* pmsg) { if (pmsg->message == g_nMBPopupOpen) { // Popup the submenu. Since the top-level menuband receives this first, the // command must be piped down the chain to the bottom-most menuband. IOleCommandTarget * poct; QueryService(SID_SMenuBandBottom, IID_IOleCommandTarget, (LPVOID *)&poct); if (poct) { BOOL bSetItem = LOWORD(pmsg->lParam); BOOL bInitialSelect = HIWORD(pmsg->lParam); VARIANTARG vargIn; TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Received private popup menu message", DBG_THIS); DWORD dwOpt = 0; vargIn.vt = VT_I4; vargIn.lVal = (LONG)pmsg->wParam; if (bSetItem) dwOpt |= MBPUI_SETITEM; if (bInitialSelect) dwOpt |= MBPUI_INITIALSELECT; poct->Exec(&CGID_MenuBand, MBANDCID_POPUPITEM, dwOpt, &vargIn, NULL); poct->Release(); return S_OK; } } else if (pmsg->message == g_nMBDragCancel) { // If we got a drag cancel, make sure that the bottom most // menu does not have the drag enter. IUnknown_QueryServiceExec(SAFECAST(this, IOleCommandTarget*), SID_SMenuBandBottom, &CGID_MenuBand, MBANDCID_DRAGCANCEL, 0, NULL, NULL); return S_OK; } else if (pmsg->message == g_nMBOpenChevronMenu) { VARIANTARG v; v.vt = VT_I4; v.lVal = (LONG)pmsg->wParam; IUnknown_Exec(_punkSite, &CGID_DeskBand, DBID_PUSHCHEVRON, _dwBandID, &v, NULL); } else if (pmsg->message == g_nMBFullCancel) { _SubMenuOnSelect(MPOS_CANCELLEVEL); _CancelMode(MPOS_FULLCANCEL); return S_OK; } return S_FALSE; } /*---------------------------------------------------------- Purpose: IMenuBand::IsMenuMessage method The thread's message pump calls this function to see if any messages need to be redirected to the menu band. This returns S_OK if the message is handled. The message pump should not pass it onto TranslateMessage or DispatchMessage if it does. */ STDMETHODIMP CMenuBand::IsMenuMessage(MSG * pmsg) { HRESULT hres = S_FALSE; ASSERT(IS_VALID_WRITE_PTR(pmsg, MSG)); #ifdef DEBUG if (g_dwDumpFlags & DF_TRANSACCELIO) DumpMsg(TEXT("CMB::IsMM"), pmsg); #endif if (!_fShow) goto Return; switch (pmsg->message) { case WM_SYSKEYDOWN: // blow this off if it's a repeated keystroke if (!(pmsg->lParam & 0x40000000)) { SendMessage(_hwndParent, WM_CHANGEUISTATE ,MAKEWPARAM(UIS_CLEAR, UISF_HIDEACCEL), 0); // Are we pressing the Alt key to activate the menu? if (!_fMenuMode && pmsg->wParam == VK_MENU && _pmbState) { // Yes; The the menu was activated because of a keyboard, // Set the global state to show the keyboard cues. _pmbState->SetKeyboardCue(TRUE); // Since this only happens on the top level menu, // We only have to tell the "Top" menu to update it's state. _pmtbTop->SetKeyboardCue(); } } break; case WM_SYSKEYUP: // If we're in menu mode, ignore this message. // if (_fMenuMode) hres = S_OK; break; case WM_SYSCHAR: // We intercept Alt-key combos (when pressed together) here, // to prevent USER from going into a false menu loop check. // There are compatibility problems if we let that happen. // // Sent by USER32 when the user hits an Alt-char combination. // We need to translate this into popping down the correct // menu. Normally we intercept this in the message pump // // Outlook Express needs a message hook in order to filter this // message for perf we do not use that method. // Athena fix 222185 (lamadio) We also don't want to do this if we are not active! // otherwise when WAB is on top of OE, we'll steal it's messages // BUGBUG: i'm removing GetTopMostPtr check below ... breaks menu accelerators for IE5 (224040) // (lamadio): If the Message filter is "engaged", then we can process accelerators. // Engaged does not mean that the filter is running. if (g_msgfilter.IsEngaged()) { hres = (_OnSysChar(pmsg, TRUE) == S_OK) ? S_OK : S_FALSE; } break; case WM_KEYDOWN: case WM_CHAR: case WM_KEYUP: if (_fMenuMode) { // All keystrokes should be handled or eaten by menubands // if we're engaged. We must do this, otherwise hosted // components like mshtml or word will try to handle the // keystroke in CBaseBrowser. // Also, don't bother forwarding tabs if (VK_TAB != pmsg->wParam) { // Since we're answer S_OK, dispatch it ourselves. TranslateMessage(pmsg); DispatchMessage(pmsg); } hres = S_OK; } break; case WM_CONTEXTMENU: // HACKHACK (lamadio): Since the start button has the keyboard focus, // the start button will handle this. We need to forward this off to the // currently tracked item at the bottom of the chain LRESULT lres; IWinEventHandler* pweh; if (_fMenuMode && SUCCEEDED(QueryService(SID_SMenuBandBottomSelected, IID_IWinEventHandler, (LPVOID *)&pweh))) { // BUGBUG (lamadio): This will only work because only one of the two possible toolbars // handles this pweh->OnWinEvent(HWND_BROADCAST, pmsg->message, pmsg->wParam, pmsg->lParam, &lres); pweh->Release(); hres = S_OK; } break; default: // We only want to process the pane messages in IsMenuMessage when there is no // top level HWND. This is for the Deskbar menus. Outlook Express needs the // TranslateMenuMessage entry point if (_pmbState->GetSubclassedHWND() == NULL) hres = _ProcessMenuPaneMessages(pmsg); break; } Return: if (!_fMenuMode && hres != S_OK) hres = E_FAIL; return hres; } BOOL HasWindowTopmostOwner(HWND hwnd) { HWND hwndOwner = hwnd; while (hwndOwner = GetWindowOwner(hwndOwner)) { if (GetWindowLong(hwndOwner, GWL_EXSTYLE) & WS_EX_TOPMOST) return TRUE; } return FALSE; } /*---------------------------------------------------------- Purpose: IMenuBand::TranslateMenuMessage method The main app's window proc calls this so the menuband catches messages that are dispatched from a different message pump (than the thread's main pump). Translates messages specially for menubands. Some messages are processed while the menuband is active. Others are only processed when it is not. Messages that are not b/t WM_KEYFIRST and WM_KEYLAST are handled here (the browser does not send these messages to IInputObject:: TranslateAcceleratorIO). Returns: S_OK if message is processed */ STDMETHODIMP CMenuBand::TranslateMenuMessage(MSG * pmsg, LRESULT * plRet) { ASSERT(IS_VALID_WRITE_PTR(pmsg, MSG)); #ifdef DEBUG if (g_dwDumpFlags & DF_TRANSACCELIO) DumpMsg(TEXT("CMB::TMM"), pmsg); #endif switch (pmsg->message) { case WM_SYSCHAR: // In certain doc-obj situations, the OLE message filter (??) // grabs this before the main thread's message pump gets a // whack at it. So we handle it here too, in case we're in // this scenario. // // See the comments in IsMenuMessage regarding this message. return _OnSysChar(pmsg, FALSE); case WM_INITMENUPOPUP: // Normally the LOWORD(lParam) is the index of the menu that // is being popped up. TrackPopupMenu (which CMenuISF uses) // always sends this message with an index of 0. This breaks // clients (like DefView) who check this value. We need to // massage this value if we find we're the source of the // WM_INITMENUPOPUP. // // (This is not in TranslateAcceleratorIO b/c TrackPopupMenu's // message pump does not call it. The wndproc must forward // the message to this function for us to get it.) if (_fInSubMenu && _pmtbTracked) { // Massage lParam to use the right index int iPos = ToolBar_CommandToIndex(_pmtbTracked->_hwndMB, _nItemCur); pmsg->lParam = MAKELPARAM(iPos, HIWORD(pmsg->lParam)); // Return S_FALSE so this message will still be handled } break; case WM_UPDATEUISTATE: if (_pmbState) { // we don't care about UISF_HIDEFOCUS if (UISF_HIDEACCEL == HIWORD(pmsg->wParam)) _pmbState->SetKeyboardCue(UIS_CLEAR == LOWORD(pmsg->wParam) ? TRUE : FALSE); } break; case WM_ACTIVATE: // Debug note: to debug menubands on ntsd, set the prototype // flag accordingly. This will keep menubands from going // away the moment the focus changes. // Becomming inactive? if (WA_INACTIVE == LOWORD(pmsg->wParam)) { // Yes; Free up the global object // Athena fix (lamadio) 08.02.1998: Athena uses menubands. Since they // have a band per window in one thread, we needed a mechanism to switch // between them. So we used the Msgfilter to forward messages. Since there // are multiple windows, we need to set correct one. // But, On a deactivate, we need to NULL it out incase a window, // running in the same thread, has normal USER menu. We don't want to steal // their messages. if (g_msgfilter.GetTopMostPtr() == this) g_msgfilter.SetTopMost(NULL); g_msgfilter.DisEngage(_pmbState->GetContext()); HWND hwndLostTo = (HWND)(pmsg->lParam); // We won't bail on the menus if we're loosing activation to a child. if (!IsAncestor(hwndLostTo, _pmbState->GetWorkerWindow(NULL))) { if (_fMenuMode && !(g_dwPrototype & PF_USINGNTSD) && !_fDragEntered) { // Being deactivated. Bail out of menus. // (Only the toplevel band gets this message.) if (_fInSubMenu) { IMenuPopup* pmp = _pmpSubMenu; if (_pmpTrackPopup) pmp = _pmpTrackPopup; ASSERT(pmp); // This should be valid. If not, someone screwed up. pmp->OnSelect(MPOS_FULLCANCEL); } _CancelMode(MPOS_FULLCANCEL); } } } else if (WA_ACTIVE == LOWORD(pmsg->wParam) || WA_CLICKACTIVE == LOWORD(pmsg->wParam)) { // If I have activation, the Worker Window needs to be bottom... // // NOTE: Don't do this if the worker window has a topmost owner // (such as the tray). Setting a window to HWND_NOTOPMOST moves // its owner windows to HWND_NOTOPMOST as well, which in this case // was breaking the tray's "always on top" feature. // HWND hwndWorker = _pmbState->GetWorkerWindow(NULL); if (hwndWorker && !HasWindowTopmostOwner(hwndWorker) && !_fDragEntered) SetWindowPos(hwndWorker, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE); // Set the context because when a menu heirarchy becomes active because the // subclassed HWND becomes active, we need to reenable the message hook. g_msgfilter.SetContext(this, TRUE); // When we get reactivated, we need to position ourself above the start bar. Exec(&CGID_MenuBand, MBANDCID_REPOSITION, TRUE, NULL, NULL); // Becomming activated. We need to reengage the message hook so that // we get the correct messages. g_msgfilter.ReEngage(_pmbState->GetContext()); // Are we in menu mode? if (_fMenuMode) { // Need to reengage some things. // Take the capture back because we have lost it to context menus or dialogs. g_msgfilter.RetakeCapture(); } g_msgfilter.SetTopMost(this); } // // Memphis and NT5 grey their horizontal menus when the windows is inactive. // if (!_fVertical && (g_bRunOnMemphis || g_bRunOnNT5) && _pmtbMenu) { // This needs to stay here because of the above check... if (WA_INACTIVE == LOWORD(pmsg->wParam)) { _fAppActive = FALSE; } else { _fAppActive = TRUE; } // Reduces flicker by using this instead of an InvalidateWindow/UpdateWindow Pair RedrawWindow(_pmtbMenu->_hwndMB, NULL, NULL, RDW_ERASE | RDW_INVALIDATE); } break; case WM_SYSCOMMAND: if ( !_fMenuMode ) { switch (pmsg->wParam & 0xFFF0) { case SC_KEYMENU: // The user either hit the Alt key by itself or Alt-space. // If it was Alt-space, let DefWindowProc handle it so the // system menu comes up. Otherwise, we'll handle it to // toggle the menuband. // Was it Alt-space? if (_fAltSpace) { // Yes; let it go TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Caught the Alt-space", DBG_THIS); _fAltSpace = FALSE; } else if (_fShow) { // No; activate the menu TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Caught the WM_SYSCOMMAND, SC_KEYMENU", DBG_THIS); UIActivateIO(TRUE, NULL); // We sit in a modal loop here because typically // WM_SYSCOMMAND doesn't return until the menu is finished. // while (_fMenuMode) { MSG msg; if (GetMessage(&msg, NULL, 0, 0)) { if ( S_OK != IsMenuMessage(&msg) ) { TranslateMessage(&msg); DispatchMessage(&msg); } } } *plRet = 0; return S_OK; // Caller shouldn't handle this } break; } } break; default: // We only want to process the pane messages in IsMenuMessage when there is no // top level HWND. This is for the Deskbar menus. Outlook Express needs the // TranslateMenuMessage entry point if (_pmbState->GetSubclassedHWND() != NULL) return _ProcessMenuPaneMessages(pmsg); break; } return S_FALSE; } /*---------------------------------------------------------- Purpose: IObjectWithSite::SetSite method Called by the menusite to host this band. Since the menuband contains two toolbars, we set their parent window to be the site's hwnd. */ STDMETHODIMP CMenuBand::SetSite(IUnknown* punkSite) { // Do this first because SetParent needs to query to the top level browser for // sftbar who queries to the top level browser to get the drag and drop window. HRESULT hres = SUPERCLASS::SetSite(punkSite); if (_psmcb && _fTopLevel && !(_dwFlags & SMINIT_NOSETSITE)) IUnknown_SetSite(_psmcb, punkSite); IUnknown_GetWindow(punkSite, &_hwndParent); // Need this for Closing an expanded vertical menu. Start Menu knows to do this when it's top level, // but the Favorites needs to know when it's parent is the horizontal menu. VARIANT var; if (SUCCEEDED(IUnknown_QueryServiceExec(punkSite, SID_SMenuBandParent, &CGID_MenuBand, MBANDCID_ISVERTICAL, 0, NULL, &var)) && var.boolVal == VARIANT_FALSE) { _fParentIsHorizontal = TRUE; } // Tell the toolbars who their new parent is if (_pmtbMenu) _pmtbMenu->SetParent(_hwndParent); if (_pmtbShellFolder) _pmtbShellFolder->SetParent(_hwndParent); return hres; } /*---------------------------------------------------------- Purpose: IShellMenu::Initialize method */ STDMETHODIMP CMenuBand::Initialize(IShellMenuCallback* psmcb, UINT uId, UINT uIdAncestor, DWORD dwFlags) { DEBUG_CODE( _fInitialized = TRUE; ); // Initalized can be called with NULL values to only set some of them. // Default to Vertical if (!(dwFlags & SMINIT_HORIZONTAL) && !(dwFlags & SMINIT_VERTICAL)) dwFlags |= SMINIT_VERTICAL; _Initialize(dwFlags); if (uIdAncestor != ANCESTORDEFAULT) _uIdAncestor = uIdAncestor; if (_uId != -1) _uId = uId; if (psmcb) { if (!SHIsSameObject(psmcb, _psmcb)) { if (_punkSite && _fTopLevel && !(dwFlags & SMINIT_NOSETSITE)) IUnknown_SetSite(_psmcb, NULL); ATOMICRELEASE(_psmcb); _psmcb = psmcb; _psmcb->AddRef(); // We do not set the site in case this callback is shared between 2 bands (Menubar/Chevron menu) if (_punkSite && _fTopLevel && !(dwFlags & SMINIT_NOSETSITE)) IUnknown_SetSite(_psmcb, _punkSite); // Only call this if we're setting a new one. Pass the address of the user associated // data section. This is so that the callback can associate data with this pane only _CallCB(SMC_CREATE, 0, (LPARAM)&_pvUserData); } } return NOERROR; } /*---------------------------------------------------------- Purpose: IShellMenu::GetMenuInfo method */ STDMETHODIMP CMenuBand::GetMenuInfo(IShellMenuCallback** ppsmc, UINT* puId, UINT* puIdAncestor, DWORD* pdwFlags) { if (ppsmc) { *ppsmc = _psmcb; if (_psmcb) ((IShellMenuCallback*)*ppsmc)->AddRef(); } if (puId) *puId = _uId; if (puIdAncestor) *puIdAncestor = _uIdAncestor; if (pdwFlags) *pdwFlags = _dwFlags; return NOERROR; } void CMenuBand::_AddToolbar(CMenuToolbarBase* pmtb, DWORD dwFlags) { pmtb->SetSite(SAFECAST(this, IMenuBand*)); if (_hwndParent) pmtb->CreateToolbar(_hwndParent); // Treat this like a two-element stack, where this function // behaves like a "push". The one additional trick is we // could be pushing onto the top or the bottom of the "stack". if (dwFlags & SMSET_BOTTOM) { if (_pmtbBottom) { // I don't need to release, because _pmtbTop and _pmtbBottom are aliases for // _pmtbShellFolder and _pmtbMenu _pmtbTop = _pmtbBottom; _pmtbTop->SetToTop(TRUE); } _pmtbBottom = pmtb; _pmtbBottom->SetToTop(FALSE); } else // Default to Top... { if (_pmtbTop) { _pmtbBottom = _pmtbTop; _pmtbBottom->SetToTop(FALSE); } _pmtbTop = pmtb; _pmtbTop->SetToTop(TRUE); } // _pmtbBottom should never be the only toolbar that exists in the menuband. if (!_pmtbTop) _pmtbTop = _pmtbBottom; // The menuband determines there is a single toolbar by comparing // the bottom with the top. So make the bottom the same if necessary. if (!_pmtbBottom) _pmtbBottom = _pmtbTop; } /*---------------------------------------------------------- Purpose: IShellMenu::GetShellFolder method */ STDMETHODIMP CMenuBand::GetShellFolder(DWORD* pdwFlags, LPITEMIDLIST* ppidl, REFIID riid, void** ppvObj) { HRESULT hres = E_FAIL; if (_pmtbShellFolder) { *pdwFlags = _pmtbShellFolder->GetFlags(); hres = S_OK; if (ppvObj) { // HACK HACK. this should QI for a mnfolder specific interface to do this. hres = _pmtbShellFolder->GetShellFolder(ppidl, riid, ppvObj); } } return hres; } /*---------------------------------------------------------- Purpose: IShellMenu::SetShellFolder method */ STDMETHODIMP CMenuBand::SetShellFolder(IShellFolder* psf, LPCITEMIDLIST pidlFolder, HKEY hKey, DWORD dwFlags) { ASSERT(_fInitialized); HRESULT hres = E_OUTOFMEMORY; // If we're processing a change notify, we cannot do anything that will modify state. // NOTE: if we don't have a state, we can't possibly processing a change notify if (_pmbState && _pmbState->IsProcessingChangeNotify()) return E_PENDING; // Only one shellfolder menu can exist per menuband. Additionally, // a shellfolder menu can exist either at the top of the menu, or // at the bottom (when it coexists with a static menu). // Is there already a shellfolder menu? if (_pmtbShellFolder) { IShellFolderBand* psfb; EVAL(SUCCEEDED(_pmtbShellFolder->QueryInterface(IID_IShellFolderBand, (void**)&psfb))); hres = psfb->InitializeSFB(psf, pidlFolder); psfb->Release(); } else { _pmtbShellFolder = new CMenuSFToolbar(this, psf, pidlFolder, hKey, dwFlags); if (_pmtbShellFolder) { _AddToolbar(_pmtbShellFolder, dwFlags); hres = NOERROR; } } return hres; } /*---------------------------------------------------------- Purpose: IMenuBand::GetMenu method */ STDMETHODIMP CMenuBand::GetMenu(HMENU* phmenu, HWND* phwnd, DWORD* pdwFlags) { HRESULT hres = E_FAIL; // HACK HACK. this should QI for a menustatic specific interface to do this. if (_pmtbMenu) hres = _pmtbMenu->GetMenu(phmenu, phwnd, pdwFlags); return hres; } /*---------------------------------------------------------- Purpose: IMenuBand::SetMenu method */ STDMETHODIMP CMenuBand::SetMenu(HMENU hmenu, HWND hwnd, DWORD dwFlags) { // Passing a NULL hmenu is valid. It means destroy our menu object. ASSERT(_fInitialized); HRESULT hres = E_FAIL; // Only one static menu can exist per menuband. Additionally, // a static menu can exist either at the top of the menu, or // at the bottom (when it coexists with a shellfolder menu). // Is there already a static menu? if (_pmtbMenu) { // Since we're merging in a new menu, make sure to update the cache... _hmenu = hmenu; // Yes // HACK HACK. this should QI for a menustatic specific interface to do this. return _pmtbMenu->SetMenu(hmenu, hwnd, dwFlags); } else { // BUGBUG (lamadio): This is to work around a problem in the interface definintion: We have // no method of setting the Subclassed HWND outside of a SetMenu. So I'm just piggybacking // off of this. A better fix would be to introduce IMenuBand2::SetSubclass(HWND). IMenuBand // actually implements the "Subclassing", so extending this interface would be worthwhile. _hwndMenuOwner = hwnd; if (_fTopLevel) { _pmbState->SetSubclassedHWND(hwnd); } if (hmenu) { _hmenu = hmenu; _pmtbMenu = new CMenuStaticToolbar(this, hmenu, hwnd, _uId, dwFlags); if (_pmtbMenu) { _AddToolbar(_pmtbMenu, dwFlags); hres = S_OK; } else hres = E_OUTOFMEMORY; } } return hres; } /*---------------------------------------------------------- Purpose: IShellMenu::SetMenuToolbar method */ STDMETHODIMP CMenuBand::SetMenuToolbar(IUnknown* punk, DWORD dwFlags) { CMenuToolbarBase* pmtb; if (punk && SUCCEEDED(punk->QueryInterface(CLSID_MenuToolbarBase, (void**)&pmtb))) { ASSERT(_pmtbShellFolder == NULL); _pmtbShellFolder = pmtb; _AddToolbar(pmtb, dwFlags); return S_OK; } else { return E_INVALIDARG; } } /*---------------------------------------------------------- Purpose: IShellMenu::InvalidateItem method */ STDMETHODIMP CMenuBand::InvalidateItem(LPSMDATA psmd, DWORD dwFlags) { HRESULT hres = S_FALSE; // If psmd is NULL, we need to just dump the toolbars and do a full reset. if (psmd == NULL) { // If we're processing a change notify, we cannot do anything that will modify state. if (_pmbState && _pmbState->IsProcessingChangeNotify()) return E_PENDING; _pmbState->PushChangeNotify(); // Tell the callback we're refreshing so that it can // reset any cached state _CallCB(SMC_REFRESH); _fExpanded = FALSE; // We don't need to refill if the caller only wanted to // refresh the sub menus. // Refresh the Shell Folder first because // It may have no items after it's done, and the // menuband may rely on this to add a seperator if (_pmtbShellFolder) _pmtbShellFolder->v_Refresh(); // Refresh the Static menu if (_pmtbMenu) _pmtbMenu->v_Refresh(); if (_pmpSubMenu) { _fInSubMenu = FALSE; IUnknown_SetSite(_pmpSubMenu, NULL); ATOMICRELEASE(_pmpSubMenu); } _pmbState->PopChangeNotify(); } else { if (_pmtbTop) hres = _pmtbTop->v_InvalidateItem(psmd, dwFlags); // We refresh everything at this level if the psmd is null if (_pmtbBottom && hres != S_OK) hres = _pmtbBottom->v_InvalidateItem(psmd, dwFlags); } return hres; } /*---------------------------------------------------------- Purpose: IShellMenu::GetState method */ STDMETHODIMP CMenuBand::GetState(LPSMDATA psmd) { if (_pmtbTracked) return _pmtbTracked->v_GetState(-1, psmd); // todo: might want to put stuff from _CallCB (below) in here return E_FAIL; } HRESULT CMenuBand::_CallCB(DWORD dwMsg, WPARAM wParam, LPARAM lParam) { if (!_psmcb) return S_FALSE; // We don't need to check callback mask here because these are not maskable events. SMDATA smd = {0}; smd.punk = SAFECAST(this, IShellMenu*); smd.uIdParent = _uId; smd.uIdAncestor = _uIdAncestor; smd.hwnd = _hwnd; smd.hmenu = _hmenu; smd.pvUserData = _pvUserData; if (_pmtbShellFolder) _pmtbShellFolder->GetShellFolder(&smd.pidlFolder, IID_IShellFolder, (void**)&smd.psf); HRESULT hres = _psmcb->CallbackSM(&smd, dwMsg, wParam, lParam); ILFree(smd.pidlFolder); if (smd.psf) smd.psf->Release(); return hres; } /*---------------------------------------------------------- Purpose: IInputObject::TranslateAcceleratorIO This is called by the base browser only when the menuband "has the focus", and only for messages b/t WM_KEYFIRST and WM_KEYLAST. This isn't very useful for menubands. See the explanations in GetMsgFilterCB, IsMenuMessage and TranslateMenuMessage. In addition, menubands cannot ever have the activation, so this method should never be called. Returns S_OK if handled. */ STDMETHODIMP CMenuBand::TranslateAcceleratorIO(LPMSG pmsg) { AssertMsg(0, TEXT("Menuband has the activation but it shouldn't!")); return S_FALSE; } /*---------------------------------------------------------- Purpose: IInputObject::HasFocusIO */ STDMETHODIMP CMenuBand::HasFocusIO() { // We consider a menuband has the focus even if it has submenus // that are currently cascaded out. All menubands in the chain // have the focus. return _fMenuMode ? S_OK : S_FALSE; } /*---------------------------------------------------------- Purpose: IMenuPopup::SetSubMenu method The child menubar calls us with its IMenuPopup pointer. */ STDMETHODIMP CMenuBand::SetSubMenu(IMenuPopup * pmp, BOOL fSet) { ASSERT(IS_VALID_CODE_PTR(pmp, IMenuPopup)); if (fSet) { _fInSubMenu = TRUE; } else { if (_pmtbTracked) { _pmtbTracked->PopupClose(); } _fInSubMenu = FALSE; _nItemSubMenu = -1; } return S_OK; } HRESULT CMenuBand::_SiteSetSubMenu(IMenuPopup * pmp, BOOL bSet) { HRESULT hres; IMenuPopup * pmpSite; hres = IUnknown_QueryService(_punkSite, SID_SMenuPopup, IID_IMenuPopup, (LPVOID *)&pmpSite); if (SUCCEEDED(hres)) { hres = pmpSite->SetSubMenu(pmp, bSet); pmpSite->Release(); } return hres; } /*---------------------------------------------------------- Purpose: Tell the GetMsg filter that this menuband is ready to listen to messages. */ HRESULT CMenuBand::_EnterMenuMode(void) { ASSERT(!_fMenuMode); // Must not push onto stack more than once if (g_dwProfileCAP & 0x00002000) StartCAP(); DEBUG_CODE( _nMenuLevel = g_nMenuLevel++; ) _fMenuMode = TRUE; _fInSubMenu = FALSE; _nItemMove = -1; _fCascadeAnimate = TRUE; _hwndFocusPrev = NULL; if (_fTopLevel) { // BUGBUG (lamadio): this piece should be moved to the shbrowse callback // REVIEW (scotth): some embedded controls (like the surround // video ctl on the carpoint website) have another thread that // eats all the messages when the control has the focus. // This prevents us from getting any messages once we're in // menu mode. I don't understand why USER menus work yet. // One way to work around this bug is to detect this case and // set the focus to our main window for the duration. if (GetWindowThreadProcessId(GetFocus(), NULL) != GetCurrentThreadId()) { IShellBrowser* psb; if (SUCCEEDED(QueryService(SID_STopLevelBrowser, IID_IShellBrowser, (void**)&psb))) { HWND hwndT; psb->GetWindow(&hwndT); _hwndFocusPrev = SetFocus(hwndT); psb->Release(); } } _hCursorOld = GetCursor(); SetCursor(g_hCursorArrow); HideCaret(NULL); } _SiteSetSubMenu(this, TRUE); if (_pmtbTop) { HWND hwnd = _pmtbTop->_hwndMB; if (!_fVertical && -1 == _nItemNew) { // The Alt key always highlights the first menu item initially SetTracked(_pmtbTop); ToolBar_SetHotItem(hwnd, 0); NotifyWinEvent(EVENT_OBJECT_FOCUS, _pmtbTop->_hwndMB, OBJID_CLIENT, GetIndexFromChild(TRUE, 0)); } _pmtbTop->Activate(TRUE); // The toolbar usually tracks mouse events. However, as the mouse // moves over submenus, we still want the parent menubar to // behave as if it has retained the focus (that is, keep the // last selected item highlighted). This also prevents the toolbar // from handling WM_MOUSELEAVE messages unnecessarily. ToolBar_SetAnchorHighlight(hwnd, TRUE); TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Entering menu mode", DBG_THIS); NotifyWinEvent(_fVertical? EVENT_SYSTEM_MENUPOPUPSTART: EVENT_SYSTEM_MENUSTART, hwnd, OBJID_CLIENT, CHILDID_SELF); } if (_pmtbBottom) { _pmtbBottom->Activate(TRUE); ToolBar_SetAnchorHighlight(_pmtbBottom->_hwndMB, TRUE); // Turn off anchoring } g_msgfilter.Push(_pmbState->GetContext(), this, _punkSite); return S_OK; } void CMenuBand::_ExitMenuMode(void) { _fMenuMode = FALSE; _nItemCur = -1; _fPopupNewMenu = FALSE; _fInitialSelect = FALSE; if (_pmtbTop) { HWND hwnd = _pmtbTop->_hwndMB; ToolBar_SetAnchorHighlight(hwnd, FALSE); // Turn off anchoring if (!_fVertical) { // Use the first item, since we're assuming every menu must have // at least one item _pmtbTop->v_SendMenuNotification(0, TRUE); // The user may have clicked outside the menu, which would have // cancelled it. But since we set the ANCHORHIGHLIGHT attribute, // the toolbar won't receive a message to cause it to // remove the highlight. So do it explicitly now. SetTracked(NULL); UpdateWindow(hwnd); } _pmtbTop->Activate(FALSE); NotifyWinEvent(_fVertical? EVENT_SYSTEM_MENUPOPUPEND: EVENT_SYSTEM_MENUEND, hwnd, OBJID_CLIENT, CHILDID_SELF); } if (_pmtbBottom) { _pmtbBottom->Activate(FALSE); ToolBar_SetAnchorHighlight(_pmtbBottom->_hwndMB, FALSE); // Turn off anchoring } g_msgfilter.Pop(_pmbState->GetContext()); _SiteSetSubMenu(this, FALSE); if (_fTopLevel) { SetCursor(_hCursorOld); ShowCaret(NULL); g_msgfilter.SetContext(this, FALSE); // We do this here, because ShowDW(FALSE) does not get called on the // top level menu band. This resets the state, so that the accelerators // are not shown. if (_pmbState) _pmbState->SetKeyboardCue(FALSE); // Tell the menus to update their state to the current global cue state. _pmtbTop->SetKeyboardCue(); if (_pmtbTop != _pmtbBottom) _pmtbBottom->SetKeyboardCue(); } if (_hwndFocusPrev) SetFocus(_hwndFocusPrev); if (_fTopLevel) { // // The top-level menu has gone away. Win32 focus and ui-activation don't // actually change when this happens, so the browser and focused dude have // no idea that something happened and won't generate any AA event. So, we // do it here for them. Note that if there was a selection inside the focused // dude, we'll lose it. This is the best we can do for now, as we don't // currently have a way to tell the focused/ui-active guy (who knows about the // current selection) to reannounce focus. // HWND hwndFocus = GetFocus(); NotifyWinEvent(EVENT_OBJECT_FOCUS, hwndFocus, OBJID_CLIENT, CHILDID_SELF); } TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): Exited menu mode", DBG_THIS); DEBUG_CODE( g_nMenuLevel--; ) DEBUG_CODE( _nMenuLevel = -1; ) if (g_dwProfileCAP & 0x00002000) StopCAP(); } /*---------------------------------------------------------- Purpose: IInputObject::UIActivateIO Menubands CANNOT take the activation. Normally a band would return S_OK and call the site's OnFocusChangeIS method, so that its TranslateAcceleratorIO method would receive keyboard messages. However, menus are different. The window/toolbar that currently has the activation must retain that activation when the menu pops down. Because of this, menubands use a GetMessage filter to intercept messages. */ STDMETHODIMP CMenuBand::UIActivateIO(BOOL fActivate, LPMSG lpMsg) { HRESULT hres; ASSERT(NULL == lpMsg || IS_VALID_WRITE_PTR(lpMsg, MSG)); if (lpMsg != NULL) { // don't allow TAB to band (or any other 'non-explicit' activation). // (if we just cared about TAB we'd check IsVK_TABCycler). // all kinds of badness would result if we did. // the band can't take focus (see above), so it can't obey the // UIAct/OnFocChg rules (e.g. can't call OnFocusChangeIS), so // our basic activation-tracking assumptions would be broken. return S_FALSE; } if (fActivate) { TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): UIActivateIO(%d)", DBG_THIS, fActivate); if (!_fMenuMode) { _EnterMenuMode(); // BUGBUG (lamadio) : Should go in the Favorites callback. // The toplevel menuband does not set the real activation. // But the children do, so activation can be communicated // with the parent menuband. if (_fVertical) { UnkOnFocusChangeIS(_punkSite, SAFECAST(this, IInputObject*), TRUE); } else { IUnknown_Exec(_punkSite, &CGID_Theater, THID_TOOLBARACTIVATED, 0, NULL, NULL); } } if (_fPopupNewMenu) { _nItemCur = _nItemNew; ASSERT(-1 != _nItemCur); ASSERT(_pmtbTracked); _fPopupNewMenu = FALSE; _nItemNew = -1; // Popup a menu hres = _pmtbTracked->PopupOpen(_nItemCur); if (FAILED(hres)) { // Don't fail the activation TraceMsg(TF_ERROR, "%d (pmb=%#08lx): PopupOpen failed", DBG_THIS); MessageBeep(MB_OK); } else if (S_FALSE == hres) { // The submenu was modal and is finished now _ExitMenuMode(); } } } else if (_fMenuMode) { TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): UIActivateIO(%d)", DBG_THIS, fActivate); ASSERT( !_fInSubMenu ); if (!_fTopLevel) UnkOnFocusChangeIS(_punkSite, SAFECAST(this, IInputObject*), FALSE); _ExitMenuMode(); } return S_FALSE; } /*---------------------------------------------------------- Purpose: IDeskBand::GetBandInfo method */ HRESULT CMenuBand::GetBandInfo(DWORD dwBandID, DWORD fViewMode, DESKBANDINFO* pdbi) { HRESULT hres = NOERROR; _dwBandID = dwBandID; // critical for perf! (BandInfoChanged) pdbi->dwMask &= ~DBIM_TITLE; // no title (ever, for now) // We expect that _pmtbBottom should never be the only toolbar // that exists in the menuband. ASSERT(NULL == _pmtbBottom || _pmtbTop); pdbi->dwModeFlags = DBIMF_USECHEVRON; if (_pmtbTop) { // If the buttons need to be updated in the toolbars, the we should // do this before we start asking them about their sizes.... if (_fForceButtonUpdate) { _UpdateButtons(); } if (_fVertical) { pdbi->ptMaxSize.y = 0; pdbi->ptMaxSize.x = 0; SIZE size = {0}; if (_pmtbMenu) { // size param zero here => it's just an out param _pmtbMenu->GetSize(&size); // HACKHACK (lamadio): On downlevel, LARGE metrics mode causes // Start menu to push the programs menu item off screen. if (size.cy > (3 * GetSystemMetrics(SM_CYSCREEN) / 4)) { Exec(&CGID_MenuBand, MBANDCID_SETICONSIZE, ISFBVIEWMODE_SMALLICONS, NULL, NULL); size.cx = 0; size.cy = 0; _pmtbMenu->GetSize(&size); } pdbi->ptMaxSize.y = size.cy; pdbi->ptMaxSize.x = size.cx; } if (_pmtbShellFolder) { // size param should be non-zero here => it's an in/out param _pmtbShellFolder->GetSize(&size); pdbi->ptMaxSize.y += size.cy + ((_pmtbMenu && !_fExpanded)? 1 : 0); // Minor sizing problem pdbi->ptMaxSize.x = max(size.cx, pdbi->ptMaxSize.x); } pdbi->ptMinSize = pdbi->ptMaxSize; } else { HWND hwnd = _pmtbTop->_hwndMB; ShowDW(TRUE); SIZE rgSize; if ( SendMessage( hwnd, TB_GETMAXSIZE, 0, (LPARAM) &rgSize )) { pdbi->ptActual.y = rgSize.cy; SendMessage(hwnd, TB_GETIDEALSIZE, FALSE, (LPARAM)&pdbi->ptActual); } // make our min size identical to the size of the first button // (we're assuming that the toolbar has at least one button) RECT rc; SendMessage(hwnd, TB_GETITEMRECT, 0, (WPARAM)&rc); pdbi->ptMinSize.x = RECTWIDTH(rc); pdbi->ptMinSize.y = RECTHEIGHT(rc); } } return hres; } /*---------------------------------------------------------- Purpose: IOleService::Exec method */ STDMETHODIMP CMenuBand::Exec(const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdExecOpt, VARIANTARG *pvarargIn, VARIANTARG *pvarargOut) { // Don't do anything if we're closing. if (_fClosing) return E_FAIL; if (pguidCmdGroup == NULL) { /*NOTHING*/ } else if (IsEqualGUID(CGID_MENUDESKBAR, *pguidCmdGroup)) { switch (nCmdID) { case MBCID_GETSIDE: if (pvarargOut) { BOOL fOurChoice = FALSE; pvarargOut->vt = VT_I4; if (!_fTopLevel) { // if we are not the top level menu, we // must continue with the direction our parent was in IMenuPopup* pmpParent; IUnknown_QueryService(_punkSite, SID_SMenuPopup, IID_IMenuPopup, (LPVOID*)&pmpParent); if (pmpParent) { if (FAILED(IUnknown_Exec(pmpParent, pguidCmdGroup, nCmdID, nCmdExecOpt, pvarargIn, pvarargOut))) fOurChoice = TRUE; pmpParent->Release(); } } else fOurChoice = TRUE; if (!fOurChoice) { // only use the parent's side hint if it is in the same orientation (ie, horizontal menubar to vertical popup // means we need to make a new choice) BOOL fParentVertical = (pvarargOut->lVal == MENUBAR_RIGHT || pvarargOut->lVal == MENUBAR_LEFT); if (BOOLIFY(_fVertical) != BOOLIFY(fParentVertical)) fOurChoice = TRUE; } if (fOurChoice) { if (_fVertical) { HWND hWndMenuBand; // // The MenuBand is Mirrored , then start the first Menu Window // as Mirrored. [samera] // if ((SUCCEEDED(GetWindow(&hWndMenuBand))) && (IS_WINDOW_RTL_MIRRORED(hWndMenuBand)) ) pvarargOut->lVal = MENUBAR_LEFT; else pvarargOut->lVal = MENUBAR_RIGHT; } else pvarargOut->lVal = MENUBAR_BOTTOM; } } return S_OK; } } else if (IsEqualGUID(CGID_MenuBand, *pguidCmdGroup)) { switch (nCmdID) { case MBANDCID_GETFONTS: // BUGBUG (lamadio): can I remove this? if (pvarargOut) { if (EVAL(_pmbm)) { // BUGBUG (lamadio): this is not marshal-safe. pvarargOut->vt = VT_UNKNOWN; _pmbm->QueryInterface(IID_IUnknown, (void**)&pvarargOut->punkVal); return S_OK; } else return E_FAIL; } else return E_INVALIDARG; break; case MBANDCID_SETFONTS: if (pvarargIn && VT_UNKNOWN == pvarargIn->vt && pvarargIn->punkVal) { // BUGBUG (lamadio): this is not marshal-safe. ATOMICRELEASE(_pmbm); pvarargIn->punkVal->QueryInterface(CLSID_MenuBandMetrics, (void**)&_pmbm); _fForceButtonUpdate = TRUE; // Force Update of Toolbars: if (_pmtbMenu) _pmtbMenu->SetMenuBandMetrics(_pmbm); if (_pmtbShellFolder) _pmtbShellFolder->SetMenuBandMetrics(_pmbm); } else return E_INVALIDARG; break; case MBANDCID_RECAPTURE: g_msgfilter.RetakeCapture(); break; case MBANDCID_NOTAREALSITE: _fParentIsNotASite = BOOLIFY(nCmdExecOpt); break; case MBANDCID_ITEMDROPPED: { _fDragEntered = FALSE; HWND hwndWorker = _pmbState->GetWorkerWindow(NULL); if (hwndWorker && !HasWindowTopmostOwner(hwndWorker)) SetWindowPos(hwndWorker, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE); } break; case MBANDCID_DRAGENTER: _fDragEntered = TRUE; break; case MBANDCID_DRAGLEAVE: _fDragEntered = FALSE; break; case MBANDCID_SELECTITEM: { int iPos = nCmdExecOpt; // If they are passing vararg in, then this is an ID, not a position if (pvarargIn && pvarargIn->vt == VT_I4) { _nItemNew = pvarargIn->lVal; _fPopupNewItemOnShow = TRUE; } // This can be called outside of a created band. if (_pmtbTop) { if (iPos == MBSI_NONE) { SetTracked(NULL); } else { CMenuToolbarBase* pmtb = (iPos == MBSI_LASTITEM) ? _pmtbBottom : _pmtbTop; ASSERT(pmtb); SetTracked(pmtb); _pmtbTracked->SetHotItem(1, iPos, -1, HICF_OTHER); // If the new hot item is in the obscured part of the menu, then the // above call will have reentered & nulled out _pmtbTracked (since we // drop down the chevron menu if the new hot item is obscured). So we // need to revalidate _pmtbTracked. if (!_pmtbTracked) break; NotifyWinEvent(EVENT_OBJECT_FOCUS, _pmtbTracked->_hwndMB, OBJID_CLIENT, GetIndexFromChild(TRUE, iPos)); } } } break; case MBANDCID_KEYBOARD: // If we've been executed because of a keyboard, then set the global // state to reflect that. This is sent by MenuBar when it's ::Popup // member is called with the flag MPPF_KEYBOARD. This is for start menu. if (_pmbState) _pmbState->SetKeyboardCue(TRUE); break; case MBANDCID_POPUPITEM: if (pvarargIn && VT_I4 == pvarargIn->vt) { // we don't want to popup a sub menu if we're tracking a context menu... if ( !((_pmtbBottom && _pmtbBottom->v_TrackingSubContextMenu()) || (_pmtbTop && _pmtbTop->v_TrackingSubContextMenu()))) { // No tracked item? Well default to the top (For the chevron menu) if (!_pmtbTracked) { SetTracked(_pmtbTop); } // We don't want to display the sub menu if we're not shown. // We do this because we could have been dismissed before the message // was routed. if (_fShow && _pmtbTracked) { int iItem; int iPos; if (nCmdExecOpt & MBPUI_ITEMBYPOS) { iPos = pvarargIn->lVal; iItem = GetButtonCmd(_pmtbTracked->_hwndMB, pvarargIn->lVal); } else { iPos = ToolBar_CommandToIndex(_pmtbTracked->_hwndMB, pvarargIn->lVal); iItem = pvarargIn->lVal; } if (nCmdExecOpt & MBPUI_SETITEM) { // Set the hot item explicitly since this can be // invoked by the keyboard and the mouse could be // anywhere. _pmtbTracked->SetHotItem(1, iPos, -1, HICF_OTHER); // If the new hot item is in the obscured part of the menu, then the // above call will have reentered & nulled out _pmtbTracked (since we // drop down the chevron menu if the new hot item is obscured). So we // need to revalidate _pmtbTracked. if (!_pmtbTracked) break; NotifyWinEvent(EVENT_OBJECT_FOCUS, _pmtbTracked->_hwndMB, OBJID_CLIENT, GetIndexFromChild(TRUE, iPos) ); } _pmtbTracked->PopupHelper(iItem, nCmdExecOpt & MBPUI_INITIALSELECT); } } } break; case MBANDCID_ISVERTICAL: if (pvarargOut) { pvarargOut->vt = VT_BOOL; pvarargOut->boolVal = (_fVertical)? VARIANT_TRUE: VARIANT_FALSE; } break; case MBANDCID_SETICONSIZE: ASSERT(nCmdExecOpt == ISFBVIEWMODE_SMALLICONS || nCmdExecOpt == ISFBVIEWMODE_LARGEICONS); _uIconSize = nCmdExecOpt; if (_pmtbTop) _pmtbTop->v_UpdateIconSize(nCmdExecOpt, TRUE); if (_pmtbBottom) _pmtbBottom->v_UpdateIconSize(nCmdExecOpt, TRUE); break; case MBANDCID_SETSTATEOBJECT: if (pvarargIn && VT_INT_PTR == pvarargIn->vt) { _pmbState = (CMenuBandState*)pvarargIn->byref; } break; case MBANDCID_ISINSUBMENU: if (_fInSubMenu || (_pmtbTracked && _pmtbTracked->v_TrackingSubContextMenu())) return S_OK; else return S_FALSE; break; case MBANDCID_ISTRACKING: if (_pmtbTracked && _pmtbTracked->v_TrackingSubContextMenu()) return S_OK; else return S_FALSE; break; case MBANDCID_REPOSITION: // Don't reposition unless we're shown (Avoids artifacts onscreen of a bad positioning) if (_fShow) { // Don't forget to reposition US!!! IMenuPopup* pmdb; DWORD dwFlags = MPPF_REPOSITION | MPPF_NOANIMATE; // If we should force a reposition. This is so that we get // the trickle down reposition so things overlap correctly if (nCmdExecOpt) dwFlags |= MPPF_FORCEZORDER; if (SUCCEEDED(IUnknown_QueryService(_punkSite, SID_SMenuPopup, IID_IMenuPopup, (void**)&pmdb))) { pmdb->Popup(NULL, NULL, dwFlags); pmdb->Release(); } // Reposition the Tracked sub menu based on the current popped up item // since this pane has now moved // If they have a sub menu, tell them to reposition as well. if (_fInSubMenu && _pmtbTracked) { IUnknown_QueryServiceExec(_pmpSubMenu, SID_SMenuBandChild, &CGID_MenuBand, MBANDCID_REPOSITION, nCmdExecOpt, NULL, NULL); } _pmbState->PutTipOnTop(); } break; case MBANDCID_REFRESH: InvalidateItem(NULL, SMINV_REFRESH); break; case MBANDCID_EXPAND: if (_pmtbShellFolder) _pmtbShellFolder->Expand(TRUE); if (_pmtbMenu) _pmtbMenu->Expand(TRUE); break; case MBANDCID_DRAGCANCEL: // If one of the Sub bands in the menu heirarchy has the drag // (Either because of Drag enter or because of the drop) then // we do not want to cancel. if (!_pmbState->HasDrag()) _CancelMode(MPOS_FULLCANCEL); break; case MBANDCID_EXECUTE: ASSERT(pvarargIn != NULL); if (_pmtbTop && _pmtbTop->IsWindowOwner((HWND)pvarargIn->ullVal) == S_OK) _pmtbTop->v_ExecItem((int)nCmdExecOpt); else if (_pmtbBottom && _pmtbBottom->IsWindowOwner((HWND)pvarargIn->ullVal) == S_OK) _pmtbBottom->v_ExecItem((int)nCmdExecOpt); _SiteOnSelect(MPOS_EXECUTE); break; } // Don't bother passing CGID_MenuBand commands to CToolBand return S_OK; } return SUPERCLASS::Exec(pguidCmdGroup, nCmdID, nCmdExecOpt, pvarargIn, pvarargOut); } /*---------------------------------------------------------- Purpose: IDockingWindow::CloseDW method. */ STDMETHODIMP CMenuBand::CloseDW(DWORD dw) { // We don't want to destroy the band if it's cached. // That means it's the caller's respocibility to Unset this bit and call CloseDW explicitly if (_dwFlags & SMINIT_CACHED) return S_OK; // Since we're blowing away all of the menus, // Top and bottom are invalid _pmtbTracked = _pmtbTop = _pmtbBottom = NULL; if (_pmtbMenu) { _pmtbMenu->v_Close(); } if (_pmtbShellFolder) { _pmtbShellFolder->v_Close(); } if (_pmpSubMenu) { _fInSubMenu = FALSE; IUnknown_SetSite(_pmpSubMenu, NULL); ATOMICRELEASE(_pmpSubMenu); } // We don't want our base class to blow this window away. It belongs to someone else. _hwnd = NULL; _fClosing = TRUE; return SUPERCLASS::CloseDW(dw); } /*---------------------------------------------------------- Purpose: IDockingWindow::ShowDW method Notes: for the start menu (non-browser) case, we bracket* the top-level popup operation w/ a LockSetForegroundWindow so that another app can't steal the foreground and collapse our menu. (nt5:172813: don't do it for the browser case since a) we don't want to and b) ShowDW(FALSE) isn't called until exit the browser so we'd be permanently locked!) */ STDMETHODIMP CMenuBand::ShowDW(BOOL fShow) { // Prevent rentrancy when we're already shown. ASSERT((int)_fShow == BOOLIFY(_fShow)); if ((int)_fShow == BOOLIFY(fShow)) return NOERROR; HRESULT hres = SUPERCLASS::ShowDW(fShow); if (!fShow) { _fShow = FALSE; if (_fTopLevel) { if (_fVertical) { // (_fTopLevel && _fVertical) => start menu MyLockSetForegroundWindow(FALSE); } else if (_dwFlags & SMINIT_USEMESSAGEFILTER) { g_msgfilter.SetHook(FALSE, TRUE); g_msgfilter.SetTopMost(this); } } if ((_fTopLevel || _fParentIsHorizontal) && _pmbState) { // Reset to not have the drag when we collapse. _pmbState->HasDrag(FALSE); _pmbState->SetExpand(FALSE); _pmbState->SetUEMState(0); } _CallCB(SMC_EXITMENU); } else { _CallCB(SMC_INITMENU); _fClosing = FALSE; _fShow = TRUE; _GetFontMetrics(); if (_fTopLevel) { // We set the context here so that the ReEngage causes the message filter // to start taking messages on a TopLevel::Show. This prevents a problem // where tracking doesn't work when switching between Favorites and Start Menu _pmbState->SetContext(this); g_msgfilter.SetContext(this, TRUE); g_msgfilter.ReEngage(_pmbState->GetContext()); if (_hwndMenuOwner && _fVertical) SetForegroundWindow(_hwndMenuOwner); if (_fVertical) { // (_fTopLevel && _fVertical) => start menu MyLockSetForegroundWindow(TRUE); } else if (_dwFlags & SMINIT_USEMESSAGEFILTER) { g_msgfilter.SetHook(TRUE, TRUE); g_msgfilter.SetTopMost(this); } _pmbState->CreateFader(_hwndParent); } } if (_pmtbShellFolder) _pmtbShellFolder->v_Show(_fShow, _fForceButtonUpdate); // Menu needs to be last so that it can update the seperator. if (_pmtbMenu) _pmtbMenu->v_Show(_fShow, _fForceButtonUpdate); if (_fPopupNewItemOnShow) { HWND hwnd = _pmbState->GetSubclassedHWND(); PostMessage(hwnd? hwnd : _pmtbMenu->_hwndMB, g_nMBPopupOpen, _nItemNew, MAKELPARAM(TRUE, TRUE)); _fPopupNewItemOnShow = FALSE; } _fForceButtonUpdate = FALSE; return hres; } // BUGBUG (lamadio): move this to shlwapi HRESULT IUnknown_QueryServiceExec(IUnknown* punk, REFGUID guidService, const GUID *guid, DWORD cmdID, DWORD cmdParam, VARIANT* pvarargIn, VARIANT* pvarargOut) { HRESULT hres; IOleCommandTarget* poct; hres = IUnknown_QueryService(punk, guidService, IID_IOleCommandTarget, (void**)&poct); if (SUCCEEDED(hres)) { hres = poct->Exec(guid, cmdID, cmdParam, pvarargIn, pvarargOut); poct->Release(); } return hres; } void CMenuBand::_GetFontMetrics() { if (_pmbm) return; if (_fTopLevel) { ASSERT(_pmtbTop); // We need only 1 HWND _pmbm = new CMenuBandMetrics(_pmtbTop->_hwndMB); } else { AssertMsg(0, TEXT("When this menuband was created, someone forgot to set the metrics")); IOleCommandTarget *poct; HRESULT hres = IUnknown_QueryService(_punkSite, SID_SMenuBandTop, IID_IOleCommandTarget, (LPVOID *)&poct); if (SUCCEEDED(hres)) { VARIANTARG vargOut; // Ask the toplevel menuband for their font info if (SUCCEEDED(poct->Exec(&CGID_MenuBand, MBANDCID_GETFONTS, 0, NULL, &vargOut))) { if (vargOut.vt == VT_UNKNOWN && vargOut.punkVal) { vargOut.punkVal->QueryInterface(CLSID_MenuBandMetrics, (void**)&_pmbm); vargOut.punkVal->Release(); } } poct->Release(); } } } /*---------------------------------------------------------- Purpose: IMenuPopup::OnSelect method This allows the child menubar to tell us when and how to bail out of the menu. */ STDMETHODIMP CMenuBand::OnSelect(DWORD dwType) { int iIndex; switch (dwType) { case MPOS_CHILDTRACKING: // this means that our child did get tracked over it, so we should abort any timeout to destroy it if (_pmtbTracked) { HWND hwnd = _pmtbTracked->_hwndMB; if (_nItemTimer) { _pmtbTracked->KillPopupTimer(); // Use the command id of the SubMenu that we actually have cascaded out. iIndex = ToolBar_CommandToIndex(hwnd, _nItemSubMenu); ToolBar_SetHotItem(hwnd, iIndex); } KillTimer(hwnd, MBTIMER_DRAGOVER); _SiteOnSelect(dwType); } break; case MPOS_SELECTLEFT: if (!_fVertical) _OnSelectArrow(-1); else { // Cancel the child submenu. Hitting left arrow is like // hitting escape. _SubMenuOnSelect(MPOS_CANCELLEVEL); } break; case MPOS_SELECTRIGHT: if (!_fVertical) _OnSelectArrow(1); else { // The right arrow gets propagated up to the top, so // a fully cascaded menu will be cancelled and the // top level menuband will move to the next menu to the // right. _SiteOnSelect(dwType); } break; case MPOS_CANCELLEVEL: // Forward onto submenu _SubMenuOnSelect(dwType); break; case MPOS_FULLCANCEL: case MPOS_EXECUTE: DEBUG_CODE( TraceMsg(TF_MENUBAND, "%d (pmb=%#08lx): CMenuToolbarBase received %s", DBG_THIS, MPOS_FULLCANCEL == dwType ? TEXT("MPOS_FULLCANCEL") : TEXT("MPOS_EXECUTE")); ) _CancelMode(dwType); break; } return S_OK; } void CMenuBand::SetTrackMenuPopup(IUnknown* punk) { ATOMICRELEASE(_pmpTrackPopup); if (punk) { punk->QueryInterface(IID_IMenuPopup, (void**)&_pmpTrackPopup); } } /*---------------------------------------------------------- Purpose: Set the currently tracked toolbar. Only one of the toolbars can have the "activation" at one time. */ BOOL CMenuBand::SetTracked(CMenuToolbarBase* pmtb) { if (pmtb == _pmtbTracked) return FALSE; if (_pmtbTracked) { // Tell the existing toolbar we're leaving him SendMessage(_pmtbTracked->_hwndMB, TB_SETHOTITEM2, -1, HICF_LEAVING); } _pmtbTracked = pmtb; if (_pmtbTracked) { // This is for accessibility. HWND hwnd = _pmtbTracked->_hwndMB; int iHotItem = ToolBar_GetHotItem(hwnd); if (iHotItem >= 0) { // Toolbar Items are 0 based, Accessibility apps require 1 based NotifyWinEvent(EVENT_OBJECT_FOCUS, hwnd, OBJID_CLIENT, GetIndexFromChild(_pmtbTracked->GetFlags() & SMSET_TOP, iHotItem)); } } return TRUE; } void CMenuBand::_OnSelectArrow(int iDir) { _fKeyboardSelected = TRUE; int iIndex; if (!_pmtbTracked) { if (iDir < 0) { SetTracked(_pmtbBottom); iIndex = ToolBar_ButtonCount(_pmtbTracked->_hwndMB) - 1; } else { SetTracked(_pmtbTop); iIndex = 0; } // This can happen when going to the chevron. if (_pmtbTracked) _pmtbTracked->SetHotItem(iDir, iIndex, -1, HICF_ARROWKEYS); } else { HWND hwnd = _pmtbTracked->_hwndMB; iIndex = ToolBar_GetHotItem(hwnd); int iCount = ToolBar_ButtonCount(hwnd); // Set the hot item explicitly since this is invoked by the // keyboard and the mouse could be anywhere. // cycle iIndex by iDir (add extra iCount to avoid negative number problems iIndex = (iIndex + iCount + iDir) % iCount; ToolBar_SetHotItem(hwnd, iIndex); } if (_pmtbTracked) { NotifyWinEvent(EVENT_OBJECT_FOCUS, _pmtbTracked->_hwndMB, OBJID_CLIENT, GetIndexFromChild(_pmtbTracked->GetFlags() & SMSET_TOP, iIndex)); } _fKeyboardSelected = FALSE; } void CMenuBand::_CancelMode(DWORD dwType) { // Tell the hosting site to cancel this level if (_fParentIsNotASite) UIActivateIO(FALSE, NULL); else _SiteOnSelect(dwType); } HRESULT CMenuBand::OnPosRectChangeDB (LPRECT prc) { // We want the HMENU portion to ALWAYS have the maximum allowed. RECT rcMenu = {0}; SIZE sizeMenu = {0}; SIZE sizeSF = {0}; SIZE sizeMax; if (_pmtbMenu) _pmtbMenu->GetSize(&sizeMenu); if (_pmtbShellFolder) _pmtbShellFolder->GetSize(&sizeSF); if (sizeSF.cx > sizeMenu.cx) sizeMax = sizeSF; else sizeMax = sizeMenu; if (_pmtbMenu) { if (_pmtbMenu->GetFlags() & SMSET_TOP) { rcMenu.bottom = sizeMenu.cy; rcMenu.right = prc->right; } else { rcMenu.bottom = prc->bottom; rcMenu.right = prc->right; rcMenu.top = prc->bottom - sizeMenu.cy; rcMenu.left = 0; } _pmtbMenu->SetWindowPos(&sizeMax, &rcMenu, 0); } if (_pmtbShellFolder) { RECT rc = *prc; if (_pmtbShellFolder->GetFlags() & SMSET_TOP) { rc.bottom = prc->bottom - RECTHEIGHT(rcMenu) + 1; } else { rc.top = prc->top + RECTHEIGHT(rcMenu); } _pmtbShellFolder->SetWindowPos(&sizeMax, &rc, 0); } return NOERROR; } HRESULT IUnknown_OnSelect(IUnknown* punk, DWORD dwType, REFGUID guid) { HRESULT hres; IMenuPopup * pmp; hres = IUnknown_QueryService(punk, guid, IID_IMenuPopup, (LPVOID *)&pmp); if (SUCCEEDED(hres)) { pmp->OnSelect(dwType); pmp->Release(); } return hres; } HRESULT CMenuBand::_SiteOnSelect(DWORD dwType) { return IUnknown_OnSelect(_punkSite, dwType, SID_SMenuPopup); } HRESULT CMenuBand::_SubMenuOnSelect(DWORD dwType) { IMenuPopup* pmp = _pmpSubMenu; if (_pmpTrackPopup) pmp = _pmpTrackPopup; return IUnknown_OnSelect(pmp, dwType, SID_SMenuPopup); } HRESULT CMenuBand::GetTop(CMenuToolbarBase** ppmtbTop) { *ppmtbTop = _pmtbTop; if (*ppmtbTop) { (*ppmtbTop)->AddRef(); return NOERROR; } return E_FAIL; } HRESULT CMenuBand::GetBottom(CMenuToolbarBase** ppmtbBottom) { *ppmtbBottom = _pmtbBottom; if (*ppmtbBottom) { (*ppmtbBottom)->AddRef(); return NOERROR; } return E_FAIL; } HRESULT CMenuBand::GetTracked(CMenuToolbarBase** ppmtbTracked) { *ppmtbTracked = _pmtbTracked; if (*ppmtbTracked) { (*ppmtbTracked)->AddRef(); return NOERROR; } return E_FAIL; } HRESULT CMenuBand::GetParentSite(REFIID riid, void** ppvObj) { if (_punkSite) return _punkSite->QueryInterface(riid, ppvObj); return E_FAIL; } HRESULT CMenuBand::GetState(BOOL* pfVertical, BOOL* pfOpen) { *pfVertical = _fVertical; *pfOpen = _fMenuMode; return NOERROR; } HRESULT CMenuBand::DoDefaultAction(VARIANT* pvarChild) { if (pvarChild->lVal != CHILDID_SELF) { CMenuToolbarBase* pmtb = (pvarChild->lVal & TOOLBAR_MASK)? _pmtbTop : _pmtbBottom; int idCmd = GetButtonCmd(pmtb->_hwndMB, (pvarChild->lVal & ~TOOLBAR_MASK) - 1); SendMessage(pmtb->_hwndMB, TB_SETHOTITEM2, idCmd, HICF_OTHER | HICF_TOGGLEDROPDOWN); } else { _CancelMode(MPOS_CANCELLEVEL); } return NOERROR; } HRESULT CMenuBand::GetSubMenu(VARIANT* pvarChild, REFIID riid, void** ppvObj) { HRESULT hres = E_FAIL; CMenuToolbarBase* pmtb = (pvarChild->lVal & TOOLBAR_MASK)? _pmtbTop : _pmtbBottom; int idCmd = GetButtonCmd(pmtb->_hwndMB, (pvarChild->lVal & ~TOOLBAR_MASK) - 1); *ppvObj = NULL; if (idCmd != -1 && pmtb) { hres = pmtb->v_GetSubMenu(idCmd, &SID_SMenuBandChild, riid, ppvObj); } return hres; } HRESULT CMenuBand::IsEmpty() { BOOL fReturn = TRUE; if (_pmtbShellFolder) fReturn = _pmtbShellFolder->IsEmpty(); if (fReturn && _pmtbMenu) fReturn = _pmtbMenu->IsEmpty(); return fReturn? S_OK : S_FALSE; } //---------------------------------------------------------------------------- // CMenuBandMetrics // //---------------------------------------------------------------------------- COLORREF GetDemotedColor() { WORD iHue; WORD iLum; WORD iSat; COLORREF clr = (COLORREF)GetSysColor(COLOR_MENU); HDC hdc = GetDC(NULL); // Office CommandBars use this same algorithm for their "intellimenus" // colors. We prefer to call them "expando menus"... if (hdc) { int cColors = GetDeviceCaps(hdc, BITSPIXEL); ReleaseDC(NULL, hdc); switch (cColors) { case 4: // 16 Colors case 8: // 256 Colors // Default to using Button Face break; default: // 256+ colors ColorRGBToHLS(clr, &iHue, &iLum, &iSat); if (iLum > 220) iLum -= 20; else if (iLum <= 20) iLum += 40; else iLum += 20; clr = ColorHLSToRGB(iHue, iLum, iSat); break; } } return clr; } ULONG CMenuBandMetrics::AddRef() { return ++_cRef; } ULONG CMenuBandMetrics::Release() { ASSERT(_cRef > 0); if (--_cRef > 0) return _cRef; delete this; return 0; } HRESULT CMenuBandMetrics::QueryInterface(REFIID riid, LPVOID * ppvObj) { if (IsEqualIID(riid, IID_IUnknown)) { *ppvObj = SAFECAST(this, IUnknown*); } else if (IsEqualIID(riid, CLSID_MenuBandMetrics)) { *ppvObj = this; } else { *ppvObj = NULL; return E_FAIL; } AddRef(); return S_OK; } CMenuBandMetrics::CMenuBandMetrics(HWND hwnd) : _cRef(1) { _SetMenuFont(); _SetArrowFont(hwnd); _SetChevronFont(hwnd); #ifndef DRAWEDGE _SetPaintMetrics(hwnd); #endif _SetTextBrush(hwnd); _SetColors(); HIGHCONTRAST hc = {sizeof(HIGHCONTRAST)}; if (SystemParametersInfoA(SPI_GETHIGHCONTRAST, sizeof(hc), &hc, 0)) { _fHighContrastMode = (HCF_HIGHCONTRASTON & hc.dwFlags); } } CMenuBandMetrics::~CMenuBandMetrics() { if (_hFontMenu) DeleteObject(_hFontMenu); if (_hFontArrow) DeleteObject(_hFontArrow); if (_hFontChevron) DeleteObject(_hFontChevron); if (_hbrText) DeleteObject(_hbrText); #ifndef DRAWEDGE if (_hPenHighlight) DeleteObject(_hPenHighlight); if (_hPenShadow) DeleteObject(_hPenShadow); #endif } HFONT CMenuBandMetrics::_CalcFont(HWND hwnd, LPCTSTR pszFont, DWORD dwCharSet, TCHAR ch, int* pcx, int* pcy, int* pcxMargin, int iOrientation, int iWeight) { ASSERT(hwnd); HFONT hFontOld, hFontRet; TEXTMETRIC tm; RECT rect={0}; int cx, cy, cxM; HDC hdc = GetDC(hwnd); hFontOld = (HFONT)SelectObject(hdc, _hFontMenu); GetTextMetrics(hdc, &tm); // Set the font height (based on original USER code) cy = ((tm.tmHeight + tm.tmExternalLeading + GetSystemMetrics(SM_CYBORDER)) & 0xFFFE) - 1; // Use the menu font's avg character width as the margin. cxM = tm.tmAveCharWidth; // Not exactly how USER does it, but close // Shlwapi wraps the ansi/unicode behavior. hFontRet = CreateFontWrap(cy, 0, iOrientation, 0, iWeight, 0, 0, 0, dwCharSet, 0, 0, 0, 0, pszFont); if (EVAL(hFontRet)) { // Calc width of arrow using this new font SelectObject(hdc, hFontRet); if (EVAL(DrawText(hdc, &ch, 1, &rect, DT_CALCRECT | DT_SINGLELINE | DT_LEFT | DT_VCENTER))) cx = rect.right; else cx = tm.tmMaxCharWidth; } else { cx = tm.tmMaxCharWidth; } SelectObject(hdc, hFontOld); ReleaseDC(hwnd, hdc); *pcx = cx; *pcy = cy; *pcxMargin = cxM; return hFontRet; } /* Call after _SetMenuFont() */ void CMenuBandMetrics::_SetChevronFont(HWND hwnd) { ASSERT(!_hFontChevron); TCHAR szPath[MAX_PATH]; NONCLIENTMETRICSA ncm; ncm.cbSize = sizeof(ncm); // Should only fail with bad parameters... EVAL(SystemParametersInfoA(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)); // Obtain the font's metrics SHAnsiToTChar(ncm.lfMenuFont.lfFaceName, szPath, ARRAYSIZE(szPath)); _hFontChevron = _CalcFont(hwnd, szPath, DEFAULT_CHARSET, CH_MENUARROW, &_cxChevron, &_cyChevron, &_cxChevron, -900, FW_NORMAL); } /* Call after _SetMenuFont() */ void CMenuBandMetrics::_SetArrowFont(HWND hwnd) { ASSERT(!_hFontArrow); ASSERT(_hFontMenu); // Obtain the font's metrics if (_hFontMenu) { _hFontArrow = _CalcFont(hwnd, szfnMarlett, SYMBOL_CHARSET, CH_MENUARROW, &_cxArrow, &_cyArrow, &_cxMargin, 0, FW_NORMAL); } else { _cxArrow = _cyArrow = _cxMargin = 0; } } void CMenuBandMetrics::_SetMenuFont() { NONCLIENTMETRICSA ncm; ncm.cbSize = sizeof(ncm); // Should only fail with bad parameters... EVAL(SystemParametersInfoA(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)); // Should only fail under low mem conditions... EVAL(_hFontMenu = CreateFontIndirectA(&ncm.lfMenuFont)); } void CMenuBandMetrics::_SetColors() { _clrBackground = GetSysColor(COLOR_MENU); _clrMenuText = GetSysColor(COLOR_MENUTEXT); _clrDemoted = GetDemotedColor(); } #ifndef DRAWEDGE // Office "IntelliMenu" style void CMenuBandMetrics::_SetPaintMetrics(HWND hwnd) { DWORD dwSysHighlight = GetSysColor(COLOR_3DHIGHLIGHT); DWORD dwSysShadow = GetSysColor(COLOR_3DSHADOW); _hPenHighlight = CreatePen(PS_SOLID, 1, dwSysHighlight); _hPenShadow = CreatePen(PS_SOLID, 1, dwSysShadow); } #endif void CMenuBandMetrics::_SetTextBrush(HWND hwnd) { _hbrText = CreateSolidBrush(GetSysColor(COLOR_MENUTEXT)); } CMenuBandState::CMenuBandState() { // We will default to NOT show the keyboard cues. This // is overridden based on the User Settings. _fKeyboardCue = FALSE; } CMenuBandState::~CMenuBandState() { ATOMICRELEASE(_ptFader); ATOMICRELEASE(_pScheduler); if (_hwndToolTip) DestroyWindow(_hwndToolTip); if (_hwndWorker) DestroyWindow(_hwndWorker); } int CMenuBandState::GetKeyboardCue() { return _fKeyboardCue; } void CMenuBandState::SetKeyboardCue(BOOL fKC) { _fKeyboardCue = fKC; } IShellTaskScheduler* CMenuBandState::GetScheduler() { if (!_pScheduler) { CoCreateInstance(CLSID_ShellTaskScheduler, NULL, CLSCTX_INPROC, IID_IShellTaskScheduler, (void **) &_pScheduler); } if (_pScheduler) _pScheduler->AddRef(); return _pScheduler; } BOOL CMenuBandState::FadeRect(PRECT prc, PFNFADESCREENRECT pfn, LPVOID pvParam) { BOOL fFade = FALSE; SystemParametersInfo(SPI_GETSELECTIONFADE, 0, &fFade, 0); if (g_bRunOnNT5 && _ptFader && fFade) { // Set the callback into the fader window. Do this each time, as the pane // may have changed between fades if (_ptFader->FadeRect(prc, pfn, pvParam)) { IShellTaskScheduler* pScheduler = GetScheduler(); if (pScheduler) { fFade = pScheduler->AddTask(_ptFader, TASKID_Fader, ITSAT_DEFAULT_LPARAM, ITSAT_DEFAULT_PRIORITY) == S_OK; } } } return fFade; } void CMenuBandState::CreateFader(HWND hwnd) { // We do this on first show, because in the Constuctor of CMenuBandState, // the Window classes might not be registered yet (As is the case with start menu). if (g_bRunOnNT5 && !_ptFader) { _ptFader = new CFadeTask(); } } void CMenuBandState::CenterOnButton(HWND hwndTB, BOOL fBalloon, int idCmd, LPTSTR pszTitle, LPTSTR pszTip) { // Balloon style holds presidence over info tips if (_fTipShown && _fBalloonStyle) return; if (!_hwndToolTip) { _hwndToolTip = CreateWindow(TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP | TTS_BALLOON, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, g_hinst, NULL); if (_hwndToolTip) { // set the version so we can have non buggy mouse event forwarding SendMessage(_hwndToolTip, CCM_SETVERSION, COMCTL32_VERSION, 0); SendMessage(_hwndToolTip, TTM_SETMAXTIPWIDTH, 0, (LPARAM)300); } } if (_hwndToolTip) { // Collapse the previous tip because we're going to be doing some stuff to it before displaying again. SendMessage(_hwndToolTip, TTM_TRACKACTIVATE, (WPARAM)FALSE, (LPARAM)0); // Balloon tips don't have a border, but regular tips do. Swap now... SHSetWindowBits(_hwndToolTip, GWL_STYLE, TTS_BALLOON | WS_BORDER, (fBalloon) ? TTS_BALLOON : WS_BORDER); if (pszTip && pszTip[0]) { RECT rc; TOOLINFO ti = {0}; ti.cbSize = SIZEOF(ti); // This was pretty bad: I kept adding tools, but never deleteing them. Now we get rid of the current // one then add the new one. if (SendMessage(_hwndToolTip, TTM_ENUMTOOLS, 0, (LPARAM)&ti)) { SendMessage(_hwndToolTip, TTM_DELTOOL, 0, (LPARAM)&ti); // Delete the current tool. } ti.cbSize = SIZEOF(ti); ti.uFlags = TTF_IDISHWND | TTF_TRANSPARENT | (fBalloon? TTF_TRACK : 0); ti.hwnd = hwndTB; ti.uId = (UINT_PTR)hwndTB; SendMessage(_hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)(LPTOOLINFO)&ti); ti.lpszText = pszTip; SendMessage(_hwndToolTip, TTM_UPDATETIPTEXT, 0, (LPARAM)&ti); SendMessage(_hwndToolTip, TTM_SETTITLE, TTI_INFO, (LPARAM)pszTitle); SendMessage(hwndTB, TB_GETRECT, idCmd, (LPARAM)&rc); MapWindowPoints(hwndTB, HWND_DESKTOP, (POINT*)&rc, 2); // Notice the correction for the bottom: gsierra wanted it up a couple of pixels. SendMessage(_hwndToolTip, TTM_TRACKPOSITION, 0, MAKELONG((rc.left + rc.right)/2, rc.bottom - 3)); SetWindowPos(_hwndToolTip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); SendMessage(_hwndToolTip, TTM_TRACKACTIVATE, (WPARAM)TRUE, (LPARAM)&ti); _fTipShown = TRUE; _fBalloonStyle = fBalloon; } } } void CMenuBandState::HideTooltip(BOOL fAllowBalloonCollapse) { if (_hwndToolTip && _fTipShown) { // Now we're going to latch the Balloon style. The rest of menuband blindly // collapses the tooltip when selection changes. Here's where we say "Don't collapse // the chevron balloon tip because of a selection change." if ((_fBalloonStyle && fAllowBalloonCollapse) || !_fBalloonStyle) { SendMessage(_hwndToolTip, TTM_TRACKACTIVATE, (WPARAM)FALSE, (LPARAM)0); _fTipShown = FALSE; } } } void CMenuBandState::PutTipOnTop() { // Force the tooltip to the topmost. if (_hwndToolTip) { SetWindowPos(_hwndToolTip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } } HWND CMenuBandState::GetWorkerWindow(HWND hwndParent) { if (!_hwndSubclassed) return NULL; if (!_hwndWorker) { // We need a worker window, so that dialogs show up on top of our menus. // HiddenWndProc is included from sftbar.h _hwndWorker = SHCreateWorkerWindow(HiddenWndProc, _hwndSubclassed, WS_EX_TOOLWINDOW, WS_POPUP, 0, (void*)_hwndSubclassed); } //hwndParent is unused at this time. I plan on using it to prevent the parenting to the subclassed window. return _hwndWorker; }
142,674
46,023
// AvioMatrix a fast matrix computation library. // // Copyright (C) 2011 The University of Tokyo Avionics Research Group // // This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. #include "AvioMatrix.h" #include "math.h" #define null (0) #define likely(x) __builtin_expect(!!(x),1) #define unlikely(x) __builtin_expect(!!(x),0) #define EXPORT __attribute__((visibility("default"))) #ifdef __cplusplus extern "C" { #endif EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv* env = NULL; jint result = -1; if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) return result; /* Please insert here JNI registration method. */ return JNI_VERSION_1_6; } static jstring AvioMatrix_Hello(JNIEnv *env, jclass cls) { return env->NewStringUTF("Hello JNI world."); } static jint NativeArray_Alloc(JNIEnv *env, jclass cls, jint capacityInBytes) { env->ThrowNew(env->FindClass("java/lang/Exception"), "Alloc : Not implemented yet."); return -1; } static void NativeArray_Free(JNIEnv *env, jclass cls, jint capacityInBytes) { env->ThrowNew(env->FindClass("java/lang/Exception"), "Free : Not implemented yet."); } static jint NativeArray_GetNativePointer(JNIEnv *env, jclass cls, jobject buf) { return (int)env->GetDirectBufferAddress(buf); } inline static jfloat InnerProduct_a(__restrict jfloat* u, __restrict jfloat* v, int n) { jfloat res(0.0f); for (int i = 0; i < n; ++i) res += u[i] * v[i]; return res; } inline static jfloat InnerProduct_b(jfloat* u, int n) { jfloat res(0.0f); for (int i = 0; i < n; ++i) res += u[i] * u[i]; return res; } static jfloat AvioMatrix_InnerProduct(JNIEnv *env, jclass cls, jobject u, jobject v) { jsize lenu = env->GetDirectBufferCapacity(u), lenv = env->GetDirectBufferCapacity(v); if (lenu != lenv) { env->ThrowNew(env->FindClass("java/lang/Exception"), "Array lengths mismatch."); return 0.0f; } else { jfloat *_u = (jfloat*)env->GetDirectBufferAddress(u), *_v = (jfloat*)env->GetDirectBufferAddress(v); if (_u == _v) return InnerProduct_b(_u, lenu); else return InnerProduct_a(_u, _v, lenu); } } inline static void Add_a(__restrict jfloat* a, __restrict jfloat* b, int n) { for (int i = 0; i < n & ~3; ++i) *a++ += *b++; for (int i = 0; i < n | 3; ++i) *a++ += *b++; } inline static void Add_b(jfloat* a, int n) { for (int i = 0; i < n & ~3; ++i) *a++ *= 2.0f; for (int i = 0; i < n | 3; ++i) *a++ += 2.0f; } static void AvioMatrix_Add(JNIEnv *env, jclass cls, jobject A, jobject B) { jsize lena = env->GetDirectBufferCapacity(A); jsize lenb = env->GetDirectBufferCapacity(B); if (lena != lenb) { env->ThrowNew(env->FindClass("java/lang/Exception"), "Array lengths mismatch."); } else { int n = lena; jfloat *a = (float*)env->GetDirectBufferAddress(A), *b = (float*)env->GetDirectBufferAddress(B); if (a == b) Add_b(a, n); else Add_a(a, b, n); } } inline static void Sub_a(__restrict jfloat* a, __restrict jfloat* b, int n) { for (int i = 0; i < n & ~3; ++i) *a++ -= *b++; for (int i = 0; i < n | 3; ++i) *a++ -= *b++; } inline static void ZeroClear(jfloat* a, int n) { for (int i = 0; i < n; ++i) *a++ = 0; } static void AvioMatrix_Subtract(JNIEnv *env, jclass cls, jobject A, jobject B) { jsize lena = env->GetDirectBufferCapacity(A); jsize lenb = env->GetDirectBufferCapacity(B); if (lena != lenb) { env->ThrowNew(env->FindClass("java/lang/Exception"), "Array lengths mismatch."); } else { int n = lena; jfloat *a = (float*)env->GetDirectBufferAddress(A), *b = (float*)env->GetDirectBufferAddress(B); if (a == b) { ZeroClear(a, n); } else { Sub_a(a, b, n); } } } static void AvioMatrix_Mul_scalar(JNIEnv *env, jclass cls, jobject A, jfloat b) { jsize lenA = env->GetDirectBufferCapacity(A); jfloat *a = (float*)env->GetDirectBufferAddress(A); for (int i = 0; i < lenA; ++i) a[i] *= b; for (int i = 0; i < lenA & ~3; ++i) *a++ *= b; for (int i = 0; i < lenA | 3; ++i) *a++ *= b; } static void AvioMatrix_Mul(JNIEnv *env, jclass cls, jobject A, jobject B, jobject C, jint Arow, jint Acol, jint Bcol) { jsize lenA = env->GetDirectBufferCapacity(A); jsize lenB = env->GetDirectBufferCapacity(B); jsize lenC = env->GetDirectBufferCapacity(C); if (lenA != Arow * Acol || lenB != Arow * Bcol || lenC != Bcol * Acol) { env->ThrowNew(env->FindClass("java/lang/Exception"), "Array lengths mismatch."); return; } jfloat *a = (jfloat*)env->GetDirectBufferAddress(A); jfloat *b = (jfloat*)env->GetDirectBufferAddress(B); jfloat *c = (jfloat*)env->GetDirectBufferAddress(C); for (unsigned int i = 0; i < Arow; ++i) for (unsigned int j = 0; j < Acol; ++j) for (unsigned int k = 0; k < Bcol; ++k) a[i * Acol + j] += b[i * Bcol + k] * c[k * Acol + j]; } static void AvioMatrix_MulAdd(JNIEnv *env, jclass cls, jobject A, jfloat b, jobject C) { jsize lenA = env->GetDirectBufferCapacity(A); jsize lenC = env->GetDirectBufferCapacity(C); if (lenA != lenC) { env->ThrowNew(env->FindClass("java/lang/Exception"), "Array lengths mismatch."); } else { int n = lenA; jfloat *a = (jfloat*)env->GetDirectBufferAddress(A), *c = (jfloat*)env->GetDirectBufferAddress(C); for (int i = 0; i < n; ++i) a[i] += b * c[i]; } } #ifdef __cplusplus } #endif
5,834
2,390
// Copyright 2016 the V8 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. #include "src/builtins/builtins-utils-gen.h" #include "src/builtins/builtins.h" #include "src/codegen/code-factory.h" #include "src/codegen/code-stub-assembler.h" #include "src/execution/isolate.h" #include "src/objects/js-generator.h" #include "src/objects/objects-inl.h" namespace v8 { namespace internal { class GeneratorBuiltinsAssembler : public CodeStubAssembler { public: explicit GeneratorBuiltinsAssembler(compiler::CodeAssemblerState* state) : CodeStubAssembler(state) {} protected: // Currently, AsyncModules in V8 are built on top of JSAsyncFunctionObjects // with an initial yield. Thus, we need some way to 'resume' the // underlying JSAsyncFunctionObject owned by an AsyncModule. To support this // the body of resume is factored out below, and shared by JSGeneratorObject // prototype methods as well as AsyncModuleEvaluate. The only difference // between AsyncModuleEvaluate and JSGeneratorObject::PrototypeNext is // the expected receiver. void InnerResume(CodeStubArguments* args, TNode<JSGeneratorObject> receiver, TNode<Object> value, TNode<Context> context, JSGeneratorObject::ResumeMode resume_mode, char const* const method_name); void GeneratorPrototypeResume(CodeStubArguments* args, TNode<Object> receiver, TNode<Object> value, TNode<Context> context, JSGeneratorObject::ResumeMode resume_mode, char const* const method_name); }; void GeneratorBuiltinsAssembler::InnerResume( CodeStubArguments* args, TNode<JSGeneratorObject> receiver, TNode<Object> value, TNode<Context> context, JSGeneratorObject::ResumeMode resume_mode, char const* const method_name) { // Check if the {receiver} is running or already closed. TNode<Smi> receiver_continuation = LoadObjectField<Smi>(receiver, JSGeneratorObject::kContinuationOffset); Label if_receiverisclosed(this, Label::kDeferred), if_receiverisrunning(this, Label::kDeferred); TNode<Smi> closed = SmiConstant(JSGeneratorObject::kGeneratorClosed); GotoIf(SmiEqual(receiver_continuation, closed), &if_receiverisclosed); DCHECK_LT(JSGeneratorObject::kGeneratorExecuting, JSGeneratorObject::kGeneratorClosed); GotoIf(SmiLessThan(receiver_continuation, closed), &if_receiverisrunning); // Remember the {resume_mode} for the {receiver}. StoreObjectFieldNoWriteBarrier(receiver, JSGeneratorObject::kResumeModeOffset, SmiConstant(resume_mode)); // Resume the {receiver} using our trampoline. // Close the generator if there was an exception. TVARIABLE(Object, var_exception); Label if_exception(this, Label::kDeferred), if_final_return(this); TNode<Object> result; { compiler::ScopedExceptionHandler handler(this, &if_exception, &var_exception); result = CallStub(CodeFactory::ResumeGenerator(isolate()), context, value, receiver); } // If the generator is not suspended (i.e., its state is 'executing'), // close it and wrap the return value in IteratorResult. TNode<Smi> result_continuation = LoadObjectField<Smi>(receiver, JSGeneratorObject::kContinuationOffset); // The generator function should not close the generator by itself, let's // check it is indeed not closed yet. CSA_DCHECK(this, SmiNotEqual(result_continuation, closed)); TNode<Smi> executing = SmiConstant(JSGeneratorObject::kGeneratorExecuting); GotoIf(SmiEqual(result_continuation, executing), &if_final_return); args->PopAndReturn(result); BIND(&if_final_return); { // Close the generator. StoreObjectFieldNoWriteBarrier( receiver, JSGeneratorObject::kContinuationOffset, closed); // Return the wrapped result. args->PopAndReturn(CallBuiltin(Builtin::kCreateIterResultObject, context, result, TrueConstant())); } BIND(&if_receiverisclosed); { // The {receiver} is closed already. TNode<Object> builtin_result; switch (resume_mode) { case JSGeneratorObject::kNext: builtin_result = CallBuiltin(Builtin::kCreateIterResultObject, context, UndefinedConstant(), TrueConstant()); break; case JSGeneratorObject::kReturn: builtin_result = CallBuiltin(Builtin::kCreateIterResultObject, context, value, TrueConstant()); break; case JSGeneratorObject::kThrow: builtin_result = CallRuntime(Runtime::kThrow, context, value); break; } args->PopAndReturn(builtin_result); } BIND(&if_receiverisrunning); { ThrowTypeError(context, MessageTemplate::kGeneratorRunning); } BIND(&if_exception); { StoreObjectFieldNoWriteBarrier( receiver, JSGeneratorObject::kContinuationOffset, closed); CallRuntime(Runtime::kReThrow, context, var_exception.value()); Unreachable(); } } void GeneratorBuiltinsAssembler::GeneratorPrototypeResume( CodeStubArguments* args, TNode<Object> receiver, TNode<Object> value, TNode<Context> context, JSGeneratorObject::ResumeMode resume_mode, char const* const method_name) { // Check if the {receiver} is actually a JSGeneratorObject. ThrowIfNotInstanceType(context, receiver, JS_GENERATOR_OBJECT_TYPE, method_name); TNode<JSGeneratorObject> generator = CAST(receiver); InnerResume(args, generator, value, context, resume_mode, method_name); } TF_BUILTIN(AsyncModuleEvaluate, GeneratorBuiltinsAssembler) { const int kValueArg = 0; auto argc = UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount); CodeStubArguments args(this, argc); TNode<Object> receiver = args.GetReceiver(); TNode<Object> value = args.GetOptionalArgumentValue(kValueArg); auto context = Parameter<Context>(Descriptor::kContext); // AsyncModules act like JSAsyncFunctions. Thus we check here // that the {receiver} is a JSAsyncFunction. char const* const method_name = "[AsyncModule].evaluate"; ThrowIfNotInstanceType(context, receiver, JS_ASYNC_FUNCTION_OBJECT_TYPE, method_name); TNode<JSAsyncFunctionObject> async_function = CAST(receiver); InnerResume(&args, async_function, value, context, JSGeneratorObject::kNext, method_name); } // ES6 #sec-generator.prototype.next TF_BUILTIN(GeneratorPrototypeNext, GeneratorBuiltinsAssembler) { const int kValueArg = 0; auto argc = UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount); CodeStubArguments args(this, argc); TNode<Object> receiver = args.GetReceiver(); TNode<Object> value = args.GetOptionalArgumentValue(kValueArg); auto context = Parameter<Context>(Descriptor::kContext); GeneratorPrototypeResume(&args, receiver, value, context, JSGeneratorObject::kNext, "[Generator].prototype.next"); } // ES6 #sec-generator.prototype.return TF_BUILTIN(GeneratorPrototypeReturn, GeneratorBuiltinsAssembler) { const int kValueArg = 0; auto argc = UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount); CodeStubArguments args(this, argc); TNode<Object> receiver = args.GetReceiver(); TNode<Object> value = args.GetOptionalArgumentValue(kValueArg); auto context = Parameter<Context>(Descriptor::kContext); GeneratorPrototypeResume(&args, receiver, value, context, JSGeneratorObject::kReturn, "[Generator].prototype.return"); } // ES6 #sec-generator.prototype.throw TF_BUILTIN(GeneratorPrototypeThrow, GeneratorBuiltinsAssembler) { const int kExceptionArg = 0; auto argc = UncheckedParameter<Int32T>(Descriptor::kJSActualArgumentsCount); CodeStubArguments args(this, argc); TNode<Object> receiver = args.GetReceiver(); TNode<Object> exception = args.GetOptionalArgumentValue(kExceptionArg); auto context = Parameter<Context>(Descriptor::kContext); GeneratorPrototypeResume(&args, receiver, exception, context, JSGeneratorObject::kThrow, "[Generator].prototype.throw"); } // TODO(cbruni): Merge with corresponding bytecode handler. TF_BUILTIN(SuspendGeneratorBaseline, GeneratorBuiltinsAssembler) { auto generator = Parameter<JSGeneratorObject>(Descriptor::kGeneratorObject); auto context = LoadContextFromBaseline(); StoreJSGeneratorObjectContext(generator, context); auto suspend_id = SmiTag(UncheckedParameter<IntPtrT>(Descriptor::kSuspendId)); StoreJSGeneratorObjectContinuation(generator, suspend_id); // Store the bytecode offset in the [input_or_debug_pos] field, to be used by // the inspector. auto bytecode_offset = SmiTag(UncheckedParameter<IntPtrT>(Descriptor::kBytecodeOffset)); // Avoid the write barrier by using the generic helper. StoreObjectFieldNoWriteBarrier( generator, JSGeneratorObject::kInputOrDebugPosOffset, bytecode_offset); TNode<JSFunction> closure = LoadJSGeneratorObjectFunction(generator); auto sfi = LoadJSFunctionSharedFunctionInfo(closure); CSA_DCHECK(this, Word32BinaryNot(IsSharedFunctionInfoDontAdaptArguments(sfi))); TNode<IntPtrT> formal_parameter_count = Signed(ChangeUint32ToWord( LoadSharedFunctionInfoFormalParameterCountWithoutReceiver(sfi))); TNode<FixedArray> parameters_and_registers = LoadJSGeneratorObjectParametersAndRegisters(generator); auto parameters_and_registers_length = SmiUntag(LoadFixedArrayBaseLength(parameters_and_registers)); // Copy over the function parameters auto parameter_base_index = IntPtrConstant( interpreter::Register::FromParameterIndex(0, 1).ToOperand() + 1); CSA_CHECK(this, UintPtrLessThan(formal_parameter_count, parameters_and_registers_length)); auto parent_frame_pointer = LoadParentFramePointer(); BuildFastLoop<IntPtrT>( IntPtrConstant(0), formal_parameter_count, [=](TNode<IntPtrT> index) { auto reg_index = IntPtrAdd(parameter_base_index, index); TNode<Object> value = LoadFullTagged(parent_frame_pointer, TimesSystemPointerSize(reg_index)); UnsafeStoreFixedArrayElement(parameters_and_registers, index, value); }, 1, IndexAdvanceMode::kPost); // Iterate over register file and write values into array. // The mapping of register to array index must match that used in // BytecodeGraphBuilder::VisitResumeGenerator. auto register_base_index = IntPtrAdd(formal_parameter_count, IntPtrConstant(interpreter::Register(0).ToOperand())); auto register_count = UncheckedParameter<IntPtrT>(Descriptor::kRegisterCount); auto end_index = IntPtrAdd(formal_parameter_count, register_count); CSA_CHECK(this, UintPtrLessThan(end_index, parameters_and_registers_length)); BuildFastLoop<IntPtrT>( formal_parameter_count, end_index, [=](TNode<IntPtrT> index) { auto reg_index = IntPtrSub(register_base_index, index); TNode<Object> value = LoadFullTagged(parent_frame_pointer, TimesSystemPointerSize(reg_index)); UnsafeStoreFixedArrayElement(parameters_and_registers, index, value); }, 1, IndexAdvanceMode::kPost); // The return value is unused, defaulting to undefined. Return(UndefinedConstant()); } // TODO(cbruni): Merge with corresponding bytecode handler. TF_BUILTIN(ResumeGeneratorBaseline, GeneratorBuiltinsAssembler) { auto generator = Parameter<JSGeneratorObject>(Descriptor::kGeneratorObject); TNode<JSFunction> closure = LoadJSGeneratorObjectFunction(generator); auto sfi = LoadJSFunctionSharedFunctionInfo(closure); CSA_DCHECK(this, Word32BinaryNot(IsSharedFunctionInfoDontAdaptArguments(sfi))); TNode<IntPtrT> formal_parameter_count = Signed(ChangeUint32ToWord( LoadSharedFunctionInfoFormalParameterCountWithoutReceiver(sfi))); TNode<FixedArray> parameters_and_registers = LoadJSGeneratorObjectParametersAndRegisters(generator); // Iterate over array and write values into register file. Also erase the // array contents to not keep them alive artificially. auto register_base_index = IntPtrAdd(formal_parameter_count, IntPtrConstant(interpreter::Register(0).ToOperand())); auto register_count = UncheckedParameter<IntPtrT>(Descriptor::kRegisterCount); auto end_index = IntPtrAdd(formal_parameter_count, register_count); auto parameters_and_registers_length = SmiUntag(LoadFixedArrayBaseLength(parameters_and_registers)); CSA_CHECK(this, UintPtrLessThan(end_index, parameters_and_registers_length)); auto parent_frame_pointer = LoadParentFramePointer(); BuildFastLoop<IntPtrT>( formal_parameter_count, end_index, [=](TNode<IntPtrT> index) { TNode<Object> value = UnsafeLoadFixedArrayElement(parameters_and_registers, index); auto reg_index = IntPtrSub(register_base_index, index); StoreFullTaggedNoWriteBarrier(parent_frame_pointer, TimesSystemPointerSize(reg_index), value); UnsafeStoreFixedArrayElement(parameters_and_registers, index, StaleRegisterConstant(), SKIP_WRITE_BARRIER); }, 1, IndexAdvanceMode::kPost); Return(LoadJSGeneratorObjectInputOrDebugPos(generator)); } } // namespace internal } // namespace v8
13,763
4,006
#include <fstream> #include <ros/ros.h> #include <ros/package.h> int main(int argc, char **argv) { // Get path and file name std::string package_path = ros::package::getPath("crowdbot_active_slam"); std::string directory_path = package_path + "/" + argv[1]; std::string general_results_path = directory_path + "/general_results.txt"; std::string test_results_path = directory_path + "/occupancy_grid_map.txt"; std::string ground_truth_map_path = package_path + "/worlds/occupancy_maps/occupancy_grid_map_" + argv[2] + "_2000x2000.txt"; std::ifstream test_map_file(test_results_path.c_str()); std::ifstream ground_truth_map_file(ground_truth_map_path.c_str()); std::string line; int i = 0; int j = 0; int k = 0; double map_score = 0; double over_ref_score = 0; if (ground_truth_map_file.is_open()){ if (test_map_file.is_open()){ while (std::getline(test_map_file, line)){ std::stringstream ss_test; ss_test << line; double p_test; ss_test >> p_test; std::getline(ground_truth_map_file, line); std::stringstream ss_ref; ss_ref << line; double p_ref; ss_ref >> p_ref; // Map Scoring if (p_test == -1){ p_test = 0.5; if (p_ref == -1){ p_ref = 0.5; } else { k += 1; p_ref /= 100; } } else { p_test /= 100; i += 1; if (p_ref == -1){ p_ref = 0.5; j += 1; over_ref_score += std::pow(p_ref - p_test, 2); } else { p_ref /= 100; } } map_score += std::pow(p_ref - p_test, 2); } } else { ROS_INFO("Failed to open test_map_file!"); } } else { ROS_INFO("Failed to open ground_truth_map_file!"); } std::ofstream result_file(general_results_path.c_str(), std::ofstream::app); if (result_file.is_open()){ // Add information to file result_file << std::endl; result_file << "Map:" << std::endl; result_file << "map_score: " << map_score << std::endl; result_file << "Number of known cells: " << i << std::endl; result_file << "Number of known test cells, while unknown in ref map: " << j << std::endl; result_file << "score for known test cells, while unkown in ref map: " << over_ref_score << std::endl; result_file << "Number of known ref cells, while unknown in test map: " << k << std::endl; // Close file result_file.close(); } else{ ROS_INFO("Could not open general_results.txt!"); } std::cout << "map_score: " << map_score << std::endl; std::cout << "Number of known cells: " << i << std::endl; std::cout << "Number of known test cells, while unknown in ref map: " << j << std::endl; std::cout << "score for known test cells, while unkown in ref map: " << over_ref_score << std::endl; std::cout << "Number of known ref cells, while unknown in test map: " << k << std::endl; return 0; }
3,045
1,087
#include "CRenderable2D.h" #include "core/utils/string.h" #include "core-ext/system/io/Resources.h" #include "core-ext/system/io/assets/TextureIO.h" #include "gpuw/Device.h" #include "renderer/texture/RrTexture.h" #include "renderer/material/RrShaderProgram.h" #include "renderer/material/RrPass.h" #include "renderer/material/Material.h" #include "render2d/preprocess/PaletteToLUT.h" #include "render2d/preprocess/NormalMapGeneration.h" #include "render2d/preprocess/Conversion.h" #include "render2d/state/WorldPalette.h" CRenderable2D::CRenderable2D ( void ) : CRenderableObject() { // Set up default parameters m_spriteGenerationInfo = rrSpriteGenParams(); m_spriteGenerationInfo.normal_default = Vector3f(0, 0, 1.0F); // Use a default 2D material RrPass spritePass; spritePass.utilSetupAsDefault(); spritePass.m_type = kPassTypeForward; spritePass.m_alphaMode = renderer::kAlphaModeAlphatest; spritePass.m_cullMode = gpu::kCullModeNone; spritePass.m_surface.diffuseColor = Color(1.0F, 1.0F, 1.0F, 1.0F); spritePass.setTexture( TEX_DIFFUSE, RrTexture::Load(renderer::kTextureWhite) ); spritePass.setTexture( TEX_NORMALS, RrTexture::Load(renderer::kTextureNormalN0) ); spritePass.setTexture( TEX_SURFACE, RrTexture::Load(renderer::kTextureBlack) ); spritePass.setTexture( TEX_OVERLAY, RrTexture::Load(renderer::kTextureGrayA0) ); spritePass.setProgram( RrShaderProgram::Load(rrShaderProgramVsPs{"shaders/sys/fullbright_vv.spv", "shaders/sys/fullbright_p.spv"}) ); renderer::shader::Location t_vspec[] = {renderer::shader::Location::kPosition, renderer::shader::Location::kUV0, renderer::shader::Location::kColor}; spritePass.setVertexSpecificationByCommonList(t_vspec, 3); spritePass.m_primitiveType = gpu::kPrimitiveTopologyTriangleStrip; PassInitWithInput(0, &spritePass); // Start off with empty model data memset(&m_modeldata, 0, sizeof(m_modeldata)); m_modeldata.indexNum = 0; m_modeldata.vertexNum = 0; } CRenderable2D::~CRenderable2D () { m_meshBuffer.FreeMeshBuffers(); // Material reference released automatically } // SetSpriteFile ( c-string sprite filename ) // Sets the sprite filename to load or convert. Uses resource manager to cache data. void CRenderable2D::SetSpriteFile ( const char* n_sprite_resname, rrSpriteSetResult* o_set_result ) { SetSpriteFileAnimated( n_sprite_resname, NULL, o_set_result ); } // SetSpriteFileAnimated ( c-string sprite filename ) // Sets the sprite filename to load and possibly convert, but provides returns for additional information. void CRenderable2D::SetSpriteFileAnimated ( const char* n_sprite_resname, core::gfx::tex::arSpriteInfo* o_sprite_info, rrSpriteSetResult* o_set_result ) { //// Create the filename for the files. //std::string filename_palette = core::utils::string::GetFileStemLeaf(n_sprite_filename) + "_pal"; //std::string filename_sprite = core::utils::string::GetFileStemLeaf(n_sprite_filename); //std::string filename_normals = core::utils::string::GetFileStemLeaf(n_sprite_filename) + "_normal"; //std::string filename_surface = core::utils::string::GetFileStemLeaf(n_sprite_filename) + "_surface"; //if (n_palette_filename != NULL) //{ // filename_palette = core::utils::string::GetFileStemLeaf(n_palette_filename); //} //std::string resource_palette; //std::string resource_sprite; //std::string resource_normals; //std::string resource_surface; arstring256 resource_sprite (n_sprite_resname); arstring256 resource_palette = resource_sprite + "_palette"; arstring256 resource_normals = resource_sprite + "_normals"; arstring256 resource_surface = resource_sprite + "_surface"; arstring256 resource_illumin = resource_sprite + "_illumin"; render2d::preprocess::rrConvertSpriteResults convert_results = {}; bool conversionResult = render2d::preprocess::ConvertSprite(n_sprite_resname, &convert_results); ARCORE_ASSERT(conversionResult == true); //#if 1 // DEVELOPER_MODE // // Check for a JPG: // { // // Convert the resource files to engine's format (if the JPGs exist) // if ( core::Resources::MakePathTo(filename_sprite + ".jpg", resource_sprite) ) // { // Textures::ConvertFile(resource_sprite, core::utils::string::GetFileStemLeaf(resource_sprite) + ".bpd"); // } // } // // Check for the PNGs: // { // // Convert the resource files to engine's format (if the PNGs exist) // if ( core::Resources::MakePathTo(filename_sprite + ".png", resource_sprite) ) // { // Textures::ConvertFile(resource_sprite, core::utils::string::GetFileStemLeaf(resource_sprite) + ".bpd"); // } // if ( core::Resources::MakePathTo(filename_palette + ".png", resource_palette) ) // { // Textures::ConvertFile(resource_palette, core::utils::string::GetFileStemLeaf(resource_palette) + ".bpd"); // } // if ( core::Resources::MakePathTo(filename_normals + ".png", resource_normals) ) // { // Textures::ConvertFile(resource_normals, core::utils::string::GetFileStemLeaf(resource_normals) + ".bpd"); // } // if ( core::Resources::MakePathTo(filename_surface + ".png", resource_surface) ) // { // Textures::ConvertFile(resource_surface, core::utils::string::GetFileStemLeaf(resource_surface) + ".bpd"); // } // } // // Check for the GALs: // { // // Convert the resource files to engine's format (if the GALs exist) // if ( core::Resources::MakePathTo(filename_sprite + ".gal", resource_sprite) ) // { // Textures::timgInfo image_info; // pixel_t* image; // if (o_img_info != NULL && o_img_frametimes != NULL) // image = Textures::loadGAL_Animation(resource_sprite, image_info, NULL); // else // image = Textures::loadGAL(resource_sprite, image_info); // Textures::ConvertData(image, &image_info, core::utils::string::GetFileStemLeaf(resource_sprite) + ".bpd"); // delete [] image; // // image = Textures::loadGAL_Layer(resource_sprite, "normals", image_info); // if (image != NULL) // { // Textures::ConvertData(image, &image_info, core::utils::string::GetFileStemLeaf(resource_sprite) + "_normal.bpd"); // delete [] image; // } // // image = Textures::loadGAL_Layer(resource_sprite, "surface", image_info); // if (image != NULL) // { // Textures::ConvertData(image, &image_info, core::utils::string::GetFileStemLeaf(resource_sprite) + "_surface.bpd"); // delete [] image; // } // } // if ( core::Resources::MakePathTo(filename_palette + ".gal", resource_palette) ) // { // Textures::timgInfo image_info; // pixel_t* image = Textures::loadGAL(resource_palette, image_info); // Textures::ConvertData(image, &image_info, core::utils::string::GetFileStemLeaf(resource_palette) + ".bpd"); // delete [] image; // } // } //#endif// DEVELOPER_MODE //arstring256 name_sprite = resource_sprite; //core::utils::string::ToResourceName(name_sprite.data, 256); ////name_sprite = arstring256("rr2d_") + name_sprite; ////arstring256 name_palette = name_sprite + "_palette"; ////arstring256 name_normals = name_sprite + "_normals"; ////arstring256 name_surface = name_sprite + "_surface"; ////arstring256 name_illumin = name_sprite + "_illumin"; //// Load the sprite procedurally for the albedo/palette: //m_textureAlbedo = RrTexture::Find(name_sprite); //if (m_textureAlbedo == NULL) //{ // m_textureAlbedo = RrTexture::CreateUnitialized(name_sprite); // // load the bpd now // // // pull the info? // m_textureAlbedo->Upload(false, // NULL, // 1, 1, // core::gfx::tex::kColorFormatRGBA8, // core::gfx::tex::kWrappingRepeat, core::gfx::tex::kWrappingRepeat, // core::gfx::tex::kMipmapGenerationNone, // core::gfx::tex::kSamplingPoint); //} //else //{ // //o_sprite_info-> //} //// Load up the paletted texture //if (m_texturePalette == NULL) //{ // m_texturePalette = RrTexture::Find(name_palette); // // Load a new palette and add it to the world. // if (m_texturePalette == NULL) // { // m_texturePalette = RrTexture::Load(resource_palette); // // Some things need a palette, some things dont. // // Push the palette to the world (possibly?? improve this???) // /*if (m_texturePalette != NULL) // { // // Load the raw data from the palette first // Textures::timgInfo imginfo_palette; // pixel_t* raw_palette = Textures::LoadRawImageData(resource_palette, imginfo_palette); // if ( raw_palette == NULL ) throw core::MissingDataException(); // // Set all data in the palette to have 255 alpha (opaque) // for (int i = 0; i < imginfo_palette.width * imginfo_palette.height; ++i) // raw_palette[i].a = 255; // // Add the palette to the world's palette // render2d::WorldPalette::Active()->AddPalette( raw_palette, imginfo_palette.height, imginfo_palette.width ); // // Save dummy value // renderer::Resources::AddTexture(filename_palette); // }*/ // } //} // Load the palette: if (core::Resources::Exists(resource_palette)) { m_texturePalette = RrTexture::Load(resource_palette); m_textureAlbedo = RrTexture::Load(resource_sprite); } else { // The palette may be part of the bitmap: m_textureAlbedo = RrTexture::Load(resource_sprite); if (m_textureAlbedo) { //m_texturePalette = m_textureAlbedo->GetPalette(); //TODO } } // Load the other textures using the normal sequence m_textureNormals = RrTexture::Load(resource_normals); m_textureSurface = RrTexture::Load(resource_surface); m_textureIllumin = RrTexture::Load(resource_illumin); // Output the sprite info if (o_sprite_info != NULL) { if (m_textureAlbedo->GetExtraInfo().spriteInfo != NULL) { *o_sprite_info = *m_textureAlbedo->GetExtraInfo().spriteInfo; } } // Set the palette texture as the sprite if (m_textureAlbedo) PassAccess(0).setTexture(TEX_DIFFUSE, m_textureAlbedo); if (m_textureNormals) PassAccess(0).setTexture(TEX_NORMALS, m_textureNormals); if (m_textureSurface) PassAccess(0).setTexture(TEX_SURFACE, m_textureSurface); if (m_textureIllumin) PassAccess(0).setTexture(TEX_OVERLAY, m_textureIllumin); // Set output result if (o_set_result != NULL) { o_set_result->textureAlbedo = m_textureAlbedo; o_set_result->textureNormals = m_textureNormals; o_set_result->textureSurface = m_textureSurface; o_set_result->textureIllumin = m_textureIllumin; o_set_result->texturePalette = m_texturePalette; } /*m_material->setTexture(TEX_DIFFUSE, new_texture); // Set the normal map up as well if (loaded_normals) m_material->setTexture(TEX_NORMALS, loaded_normals); // Set the surface map up as well if (loaded_surface) m_material->setTexture(TEX_SURFACE, loaded_surface);*/ // Now create BPD paths: // Require the sprite //if ( !core::Resources::MakePathTo(filename_sprite + ".bpd", resource_sprite) ) //{ // throw core::MissingFileException(); //} //// If no palette, then load the object in forward mode. //if ( !core::Resources::MakePathTo(filename_palette + ".bpd", resource_palette) ) //{ // // Remove deferred pass from the shader so it only renders in forward mode // m_material->deferredinfo.clear(); // // Load up the texture // RrTexture* new_texture = RESOURCE_GET_TEXTURE( // n_sprite_filename, // new RrTexture ( // n_sprite_filename, // Texture2D, RGBA8, // 1024,1024, Clamp,Clamp, // MipmapNone,SamplingPoint // ) // ); // // Set output texture info // if (o_img_info) *o_img_info = new_texture->GetIOImgInfo(); // // Set sprite info // m_spriteInfo.fullsize.x = new_texture->GetWidth(); // m_spriteInfo.fullsize.y = new_texture->GetHeight(); // m_spriteInfo.framesize.x = new_texture->GetWidth(); // m_spriteInfo.framesize.y = new_texture->GetHeight(); // // Set the material based on the input file. // m_material->setTexture(TEX_DIFFUSE, new_texture); // // No longer need the texture in this object // new_texture->RemoveReference(); // // Not a palette'd sprite. // return; //} //// Check for paletted textures: //RrTexture* loaded_palette = NULL;//renderer::Resources::GetTexture(filename_palette); //RrTexture* loaded_sprite = RrTexture::Load(resource_sprite.c_str()); //RrTexture* loaded_normals = RrTexture::Load(resource_normals.c_str()); //RrTexture* loaded_surface = RrTexture::Load(resource_surface.c_str()); ////RrTexture* loaded_sprite = renderer::Resources::GetTexture(filename_sprite); ////RrTexture* loaded_normals = renderer::Resources::GetTexture(filename_normals); ////RrTexture* loaded_surface = renderer::Resources::GetTexture(filename_surface); //if ( loaded_palette == NULL ) //{ // // Load the raw data from the palette first // Textures::timgInfo imginfo_palette; // pixel_t* raw_palette = Textures::LoadRawImageData(resource_palette, imginfo_palette); // if ( raw_palette == NULL ) throw core::MissingDataException(); // // Set all data in the palette to have 255 alpha (opaque) // for (int i = 0; i < imginfo_palette.width * imginfo_palette.height; ++i) // raw_palette[i].a = 255; // // Add the palette to the world's palette // Render2D::WorldPalette::Active()->AddPalette( raw_palette, imginfo_palette.height, imginfo_palette.width ); // // // No longer need local palette // delete [] raw_palette; // // Save dummy value // renderer::Resources::AddTexture(filename_palette); //} ////if ( loaded_sprite == NULL ) ////{ //// // Load the raw data from the sprite //// Textures::timgInfo imginfo_sprite; //// pixel_t* raw_sprite = Textures::LoadRawImageData(resource_sprite, imginfo_sprite); //// if ( raw_sprite == NULL ) throw core::MissingDataException(); //// // Set output texture info //// if (o_img_info) *o_img_info = imginfo_sprite; //// // Convert the colors to the internal world's palette //// render2d::preprocess::DataToLUT( //// raw_sprite, imginfo_sprite.width * imginfo_sprite.height, //// Render2D::WorldPalette::Active()->palette_data, Render2D::WorldPalette::MAX_HEIGHT, Render2D::WorldPalette::Active()->palette_width); //// // Create empty texture to upload data into //// RrTexture* new_texture = new RrTexture(""); //// // Upload the data //// new_texture->Upload( //// raw_sprite, //// imginfo_sprite.width, imginfo_sprite.height, //// Clamp, Clamp, //// MipmapNone, SamplingPoint //// ); //// // Set sprite info //// m_spriteInfo.fullsize.x = new_texture->GetWidth(); //// m_spriteInfo.fullsize.y = new_texture->GetHeight(); //// m_spriteInfo.framesize.x = new_texture->GetWidth(); //// m_spriteInfo.framesize.y = new_texture->GetHeight(); //// // Set the palette texture as the sprite //// m_material->setTexture(TEX_DIFFUSE, new_texture); //// // No longer need the texture in this object //// new_texture->RemoveReference(); //// // Add it to manager //// renderer::Resources::AddTexture(filename_sprite, new_texture); //// // Create normal map texture //// if ( core::Resources::MakePathTo(filename_normals + ".bpd", resource_normals) ) //// { //// RrTexture* new_texture = new RrTexture ( //// resource_normals, //// Texture2D, RGBA8, //// 1024,1024, Clamp,Clamp, //// MipmapNone,SamplingPoint //// ); //// m_material->setTexture(TEX_NORMALS, new_texture); //// // No longer need the texture in this object //// new_texture->RemoveReference(); //// // Add it to manager //// renderer::Resources::AddTexture(filename_normals, new_texture); //// } //// else //// { //// RrTexture* new_texture = new RrTexture(""); //// // Generate a normal map based on input parameters //// pixel_t* raw_normalmap = new pixel_t [imginfo_sprite.width * imginfo_sprite.height]; //// render2d::preprocess::GenerateNormalMap( raw_sprite, raw_normalmap, imginfo_sprite.width, imginfo_sprite.height, m_spriteGenerationInfo.normal_default ); //// // Upload the data //// new_texture->Upload( //// raw_normalmap, //// imginfo_sprite.width, imginfo_sprite.height, //// Clamp, Clamp, //// MipmapNone, SamplingPoint //// ); //// // Set this new normal map //// m_material->setTexture(TEX_NORMALS, new_texture); //// // Clear off the data now that it's on the GPU //// delete [] raw_normalmap; //// // No longer need the texture in this object //// new_texture->RemoveReference(); //// // Add it to manager //// renderer::Resources::AddTexture(filename_normals, new_texture); //// } //// // Clear off the data now that it's on the GPU and we're done using it for generation //// delete [] raw_sprite; //// // Create surface map texture //// if ( core::Resources::MakePathTo(filename_surface + ".bpd", resource_surface) ) //// { //// RrTexture* new_texture = new RrTexture ( //// resource_surface, //// Texture2D, RGBA8, //// 1024,1024, Clamp,Clamp, //// MipmapNone,SamplingPoint //// ); //// // Set this new surface map //// m_material->setTexture(TEX_SURFACE, new_texture); //// // No longer need the texture in this object //// new_texture->RemoveReference(); //// // Add it to manager //// renderer::Resources::AddTexture(filename_surface, new_texture); //// } ////} ////else //{ // RrTexture* new_texture = loaded_sprite; // // Set sprite info // m_spriteInfo.fullsize.x = new_texture->GetWidth(); // m_spriteInfo.fullsize.y = new_texture->GetHeight(); // m_spriteInfo.framesize.x = new_texture->GetWidth(); // m_spriteInfo.framesize.y = new_texture->GetHeight(); // // Set the palette texture as the sprite // m_material->setTexture(TEX_DIFFUSE, new_texture); // // Set the normal map up as well // if (loaded_normals) m_material->setTexture(TEX_NORMALS, loaded_normals); // // Set the surface map up as well // if (loaded_surface) m_material->setTexture(TEX_SURFACE, loaded_surface); //} //// Remove forward pass to save memory //m_material->passinfo.clear(); } // GetSpriteInfo () // Returns read-only reference to the current sprite information structure. const render2d::rrSpriteInfo& CRenderable2D::GetSpriteInfo ( void ) { return m_spriteInfo; } // SpriteGenParams () // Returns read-write reference to the sprite generation parameters rrSpriteGenParams& CRenderable2D::SpriteGenParams ( void ) { return m_spriteGenerationInfo; } // PushModelData() // Takes the information inside of m_modeldata and pushes it to the GPU so that it may be rendered. void CRenderable2D::PushModeldata ( void ) { m_meshBuffer.InitMeshBuffers(&m_modeldata); } // PreRender() // Push the uniform properties bool CRenderable2D::PreRender ( rrCameraPass* cameraPass ) { PushCbufferPerObject(transform.world, cameraPass); return true; } // Render() // Render the model using the 2D engine's style bool CRenderable2D::Render ( const rrRenderParams* params ) { //// Do not render if no buffer to render with //if ( m_buffer_verts == 0 || m_buffer_tris == 0 ) //{ // return true; //} //// For now, we will render the same way as the 3d meshes render ////GL.Transform( &(transform.world) ); //m_material->m_bufferSkeletonSize = 0; //m_material->m_bufferMatricesSkinning = 0; //m_material->bindPass(pass); ////parent->SendShaderUniforms(this); //BindVAO( pass, m_buffer_verts, m_buffer_tris ); //GL.DrawElements( GL_TRIANGLES, m_modeldata.triangleNum*3, GL_UNSIGNED_INT, 0 ); ////GL.endOrtho(); //// Success! // otherwise we will render the same way 3d meshes render { if ( !m_meshBuffer.m_mesh_uploaded ) return true; // Only render when have a valid mesh and rendering enabled gpu::GraphicsContext* gfx = gpu::getDevice()->getContext(); gpu::Pipeline* pipeline = GetPipeline( params->pass ); gfx->setPipeline(pipeline); // Set up the material helper... renderer::Material(this, gfx, params->pass, pipeline) // set the depth & blend state registers .setDepthStencilState() .setRasterizerState() // bind the samplers & textures .setBlendState() .setTextures(); // bind the vertex buffers for (int i = 0; i < renderer::shader::kVBufferSlotMaxCount; ++i) if (m_meshBuffer.m_bufferEnabled[i]) gfx->setVertexBuffer(i, &m_meshBuffer.m_buffer[i], 0); // bind the index buffer gfx->setIndexBuffer(&m_meshBuffer.m_indexBuffer, gpu::kIndexFormatUnsigned16); // bind the cbuffers gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_OBJECT_MATRICES, &m_cbufPerObjectMatrices); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_OBJECT_EXTENDED, &m_cbufPerObjectSurfaces[params->pass]); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_CAMERA_INFORMATION, params->cbuf_perCamera); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_PASS_INFORMATION, params->cbuf_perPass); gfx->setShaderCBuffer(gpu::kShaderStageVs, renderer::CBUFFER_PER_FRAME_INFORMATION, params->cbuf_perFrame); // draw now gfx->drawIndexed(m_modeldata.indexNum, 0, 0); } return true; }
20,665
7,992