commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
e38f84e86b9227f0276bef499b0b65bb9c43505e
src/uoj8583.cpp
src/uoj8583.cpp
#include<malloc.h> #include<stdio.h> #define OK 1 #define ERROR 0 #define STACK_INIT_SIZE 100 // 存储空间初始分配量 #define STACKINCREMENT 10 // 存储空间分配增量 typedef int SElemType; // 定义栈元素类型 typedef int Status; // Status是函数的类型,其值是函数结果状态代码,如OK等 struct SqStack { SElemType *base; // 在栈构造之前和销毁之后,base的值为NULL SElemType *top; // 栈顶指针 int stacksize; // 当前已分配的存储空间,以元素为单位 Status InitStack() { // 构造一个空栈S,该栈预定义大小为STACK_INIT_SIZE // 请补全代码 base=(SElemType*) malloc(STACK_INIT_SIZE*(sizeof(SElemType))); if(base=NULL)return ERROR; top=base+1; stacksize=STACK_INIT_SIZE; return OK; } Status Push(SElemType e) { // 在栈S中插入元素e为新的栈顶元素 // 请补全代码 if(top-base>=stacksize){ base=(SElemType *) realloc(base,(stacksize+STACKINCREMENT)*sizeof(SElemType)); if(base==NULL){ return ERROR; } }else{ *top=e; top++; } return OK; } Status Pop(SElemType &e) { // 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR // 请补全代码 if( top-base<=1){ return ERROR; } e=*(--top); return OK; } Status GetTop(SElemType &e) { // 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR // 请补全代码 if( top-base<=1){ return ERROR; } e=*(top-1); return OK; } int StackLength() { // 返回栈S的元素个数 // 请补全代码 return top-base-1; } Status StackTraverse() { // 从栈顶到栈底依次输出栈中的每个元素 SElemType *p = (SElemType *)malloc(sizeof(SElemType)); p = top; //请填空 if(StackLength() ==0 )printf("The Stack is Empty!"); //请填空 else { printf("The Stack is: "); p--; while(p-base>1) //请填空 { printf("%d ", *p); p--; //请填空 } } printf("\n"); return OK; } }; // 顺序栈 int main() { int a; SqStack S; SElemType x, e; if(S.InitStack()) // 判断顺序表是否创建成功,请填空 { printf("A Stack Has Created.\n"); } while(1) { printf("1:Push \n2:Pop \n3:Get the Top \n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n"); scanf("%d",&a); switch(a) { case 1: scanf("%d", &x); if(S.Push(x)) printf("Push Error!\n"); // 判断Push是否合法,请填空 else printf("The Element %d is Successfully Pushed!\n", x); break; case 2: if(S.Pop(e)) printf("Pop Error!\n"); // 判断Pop是否合法,请填空 else printf("The Element %d is Successfully Poped!\n", e); break; case 3: if(S.GetTop(e))printf("Get Top Error!\n"); // 判断Get Top是否合法,请填空 else printf("The Top Element is %d!\n", e); break; case 4: printf("The Length of the Stack is %d!\n",S.StackLength()); //请填空 break; case 5: S.StackTraverse(); //请填空 break; case 0: return 1; } } }
#include<malloc.h> #include<stdio.h> #define OK 0 #define ERROR 1 #define STACK_INIT_SIZE 100 // 存储空间初始分配量 #define STACKINCREMENT 10 // 存储空间分配增量 typedef int SElemType; // 定义栈元素类型 typedef int Status; // Status是函数的类型,其值是函数结果状态代码,如OK等 struct SqStack { SElemType *base; // 在栈构造之前和销毁之后,base的值为NULL SElemType *top; // 栈顶指针 int stacksize; // 当前已分配的存储空间,以元素为单位 Status InitStack() { // 构造一个空栈S,该栈预定义大小为STACK_INIT_SIZE // 请补全代码 base=(SElemType*) malloc(STACK_INIT_SIZE*(sizeof(SElemType))); if(base==NULL)return ERROR; top=base+1; stacksize=STACK_INIT_SIZE; return OK; } Status Push(SElemType e) { // 在栈S中插入元素e为新的栈顶元素 // 请补全代码 if(top-base>=stacksize*4){ base=(SElemType *) realloc(base,(stacksize+STACKINCREMENT)*sizeof(SElemType)); if(base==NULL){ return ERROR; } }else{ *top=e; top++; } return OK; } Status Pop(SElemType &e) { // 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR // 请补全代码 if( top-base<=1){ return ERROR; } e=*(--top); return OK; } Status GetTop(SElemType &e) { // 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR // 请补全代码 if( top-base<=1){ return ERROR; } e=*(top-1); return OK; } int StackLength() { // 返回栈S的元素个数 // 请补全代码 return top-base-1; } Status StackTraverse() { // 从栈顶到栈底依次输出栈中的每个元素 SElemType *p = (SElemType *)malloc(sizeof(SElemType)); p = top; //请填空 if(StackLength() ==0 )printf("The Stack is Empty!"); //请填空 else { printf("The Stack is: "); p--; while(p-base>=1) //请填空 { printf("%d ", *p); p--; //请填空 } } printf("\n"); return OK; } }; // 顺序栈 int main() { int a; SqStack S; SElemType x, e; if(S.InitStack()==OK) // 判断顺序表是否创建成功,请填空 { printf("A Stack Has Created.\n"); } while(1) { printf("1:Push \n2:Pop \n3:Get the Top \n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n"); scanf("%d",&a); switch(a) { case 1: scanf("%d", &x); if(S.Push(x)) printf("Push Error!\n"); // 判断Push是否合法,请填空 else printf("The Element %d is Successfully Pushed!\n", x); break; case 2: if(S.Pop(e)) printf("Pop Error!\n"); // 判断Pop是否合法,请填空 else printf("The Element %d is Successfully Poped!\n", e); break; case 3: if(S.GetTop(e))printf("Get Top Error!\n"); // 判断Get Top是否合法,请填空 else printf("The Top Element is %d!\n", e); break; case 4: printf("The Length of the Stack is %d!\n",S.StackLength()); //请填空 break; case 5: S.StackTraverse(); //请填空 break; case 0: return 1; } } }
update uoj8583
update uoj8583
C++
mit
czfshine/my_oj,czfshine/my_oj,czfshine/my_oj,czfshine/my_oj
17238968e883ee002dfb6469aa1e67be14debdb4
src/map/src/nearby.cpp
src/map/src/nearby.cpp
#include "nearby.h" #include "components/position.h" #include "entity_system.h" #include <algorithm> namespace { constexpr std::tuple<uint16_t, uint16_t> get_grid_position(float x, float y) { uint16_t gx = x / 1000.f; uint16_t gy = y / 1000.f; return {gx, gy}; } std::tuple<uint16_t, uint16_t> get_grid_position(const EntitySystem& entitySystem, Entity e) { const auto* pos = entitySystem.try_get_component<Component::Position>(); if (!pos) return {0, 0}; return get_grid_position(pos->x, pos->y); } } Nearby::Nearby(const EntitySystem& entitySystem) : entitySystem(entitySystem) {} void Nearby::add_entity(RoseCommon::Entity entity) { if (entity == entt::null) return; grid[get_grid_position(entitySystem, entity)].push_back(entity); } void remove_entity(RoseCommon::Entity entity) { if (entity == entt::unll) return; auto& list = grid[get_grid_position(entitySystem, entity)]; std::remove(list.begin(), list.end(), entity); } bool is_nearby(RoseCommon::Entity first, RoseCommon::Entity second) const { if (first == entt::null || second == entt::null) return false; auto pos_first = get_grid_position(entitySystem, first); auto pos_second = get_grid_position(entitySystem, second); if (std::abs(std::get<0>(pos_first) - std::get<0>(pos_second)) <= 10 && std::abs(std::get<1>(pos_first) - std::get<1>(pos_second)) <= 10) return true; return false; } std::vector<RoseCommon::Entity> get_nearby(RoseCommon::Entity entity) const { std::vector<RoseCommon::Entity> res; // TODO: populate res return res; } void update_position(RoseCommon::Entity entity, float old_x, float old_y) { if (old_x && old_y) { auto &list = grid[get_grid_position(old_x, old_y)]; std::remove(list.begin(), list.end(), entity); } grid[get_grid_position(entitySystem, entity)].push_back(entity); }
#include "nearby.h" #include "components/position.h" #include "entity_system.h" #include <algorithm> namespace { constexpr std::tuple<uint16_t, uint16_t> get_grid_position(float x, float y) { uint16_t gx = x / 1000.f; uint16_t gy = y / 1000.f; return {gx, gy}; } std::tuple<uint16_t, uint16_t> get_grid_position(const Registry& registry, Entity e) { const auto* pos = registry.try_get_component<Component::Position>(); if (!pos) return {0, 0}; return get_grid_position(pos->x, pos->y); } } void Nearby::add_entity(RoseCommon::Registry& registry, RoseCommon::Entity entity) { if (entity == entt::null) return; grid[get_grid_position(registry, entity)].push_back(entity); } void remove_entity(RoseCommon::Registry& registry, RoseCommon::Entity entity) { if (entity == entt::unll) return; auto& list = grid[get_grid_position(registry, entity)]; std::remove(list.begin(), list.end(), entity); } bool is_nearby(RoseCommon::Entity first, RoseCommon::Entity second) const { if (first == entt::null || second == entt::null) return false; auto pos_first = get_grid_position(entitySystem, first); auto pos_second = get_grid_position(entitySystem, second); if (std::abs(std::get<0>(pos_first) - std::get<0>(pos_second)) <= 10 && std::abs(std::get<1>(pos_first) - std::get<1>(pos_second)) <= 10) return true; return false; } std::vector<RoseCommon::Entity> get_nearby(RoseCommon::Entity entity) const { std::vector<RoseCommon::Entity> res; // TODO: populate res return res; } void update_position(RoseCommon::Entity entity, float old_x, float old_y, float x, float y) { if (old_x && old_y) { auto &list = grid[get_grid_position(old_x, old_y)]; std::remove(list.begin(), list.end(), entity); } grid[get_grid_position(x, y)].push_back(entity); }
Update nearby.cpp
Update nearby.cpp
C++
apache-2.0
RavenX8/osIROSE-new,RavenX8/osIROSE-new,dev-osrose/osIROSE-new,RavenX8/osIROSE-new,dev-osrose/osIROSE-new,dev-osrose/osIROSE-new
b490f9798778aef50c34c1fc0dc0d9d177c05fe5
include/LIEF/BinaryStream/BinaryStream.hpp
include/LIEF/BinaryStream/BinaryStream.hpp
/* Copyright 2017 - 2022 R. Thomas * Copyright 2017 - 2022 Quarkslab * * 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 LIEF_BINARY_STREAM_H_ #define LIEF_BINARY_STREAM_H_ #include <cstdint> #include <climits> #include <vector> #include <istream> #include <utility> #include <memory> #include <algorithm> #include "LIEF/BinaryStream/Convert.hpp" #include "LIEF/errors.hpp" struct mbedtls_x509_crt; struct mbedtls_x509_time; namespace LIEF { //! Class that is used to a read stream of data from different sources class BinaryStream { public: enum class STREAM_TYPE { UNKNOWN = 0, VECTOR, MEMORY, SPAN, FILE, ELF_DATA_HANDLER, }; BinaryStream(); virtual ~BinaryStream(); virtual uint64_t size() const = 0; inline STREAM_TYPE type() const { return stype_; } result<uint64_t> read_uleb128() const; result<uint64_t> read_sleb128() const; result<int64_t> read_dwarf_encoded(uint8_t encoding) const; result<std::string> read_string(size_t maxsize = ~static_cast<size_t>(0)) const; result<std::string> peek_string(size_t maxsize = ~static_cast<size_t>(0)) const; result<std::string> peek_string_at(size_t offset, size_t maxsize = ~static_cast<size_t>(0)) const; result<std::u16string> read_u16string() const; result<std::u16string> peek_u16string() const; result<std::string> read_mutf8(size_t maxsize = ~static_cast<size_t>(0)) const; result<std::u16string> read_u16string(size_t length) const; result<std::u16string> peek_u16string(size_t length) const; result<std::u16string> peek_u16string_at(size_t offset, size_t length) const; virtual inline ok_error_t peek_data(std::vector<uint8_t>& container, uint64_t offset, uint64_t size) { if (size == 0) { return ok(); } // Even though offset + size < ... => offset < ... // the addition could overflow so it's worth checking both const bool read_ok = offset <= this->size() && (offset + size) <= this->size(); if (!read_ok) { return make_error_code(lief_errors::read_error); } container.resize(size); if (peek_in(container.data(), offset, size)) { return ok(); } return make_error_code(lief_errors::read_error); } virtual inline ok_error_t read_data(std::vector<uint8_t>& container, uint64_t size) { if (!peek_data(container, pos(), size)) { return make_error_code(lief_errors::read_error); } increment_pos(size); return ok(); } void setpos(size_t pos) const; void increment_pos(size_t value) const; void decrement_pos(size_t value) const; size_t pos() const; operator bool() const; template<class T> const T* read_array(size_t size) const; template<class T> result<T> peek() const; template<class T> result<T> peek(size_t offset) const; template<class T> const T* peek_array(size_t size) const; template<class T> const T* peek_array(size_t offset, size_t size) const; template<class T> result<T> read() const; template<typename T> bool can_read() const; template<typename T> bool can_read(size_t offset) const; size_t align(size_t align_on) const; /* Functions that are endianness aware */ template<class T> typename std::enable_if<std::is_integral<T>::value, result<T>>::type peek_conv() const; template<class T> typename std::enable_if<!std::is_integral<T>::value, result<T>>::type peek_conv() const; template<class T> result<T> peek_conv(size_t offset) const; template<class T> result<T> read_conv() const; /* Read an array of values and adjust endianness as needed */ template<typename T> std::unique_ptr<T[]> read_conv_array(size_t size) const; template<typename T> std::unique_ptr<T[]> peek_conv_array(size_t offset, size_t size) const; template<typename T> static T swap_endian(T u); void set_endian_swap(bool swap); /* ASN.1 & X509 parsing functions */ virtual result<size_t> asn1_read_tag(int tag); virtual result<size_t> asn1_read_len(); virtual result<std::string> asn1_read_alg(); virtual result<std::string> asn1_read_oid(); virtual result<int32_t> asn1_read_int(); virtual result<std::vector<uint8_t>> asn1_read_bitstring(); virtual result<std::vector<uint8_t>> asn1_read_octet_string(); virtual result<std::unique_ptr<mbedtls_x509_crt>> asn1_read_cert(); virtual result<std::string> x509_read_names(); virtual result<std::vector<uint8_t>> x509_read_serial(); virtual result<std::unique_ptr<mbedtls_x509_time>> x509_read_time(); template<class T> static bool is_all_zero(const T& buffer) { const auto* ptr = reinterpret_cast<const uint8_t *const>(&buffer); return std::all_of(ptr, ptr + sizeof(T), [] (uint8_t x) { return x == 0; }); } inline bool should_swap() const { return endian_swap_; } protected: virtual result<const void*> read_at(uint64_t offset, uint64_t size) const = 0; inline virtual ok_error_t peek_in(void* dst, uint64_t offset, uint64_t size) const { if (auto raw = read_at(offset, size)) { if (dst == nullptr) { return make_error_code(lief_errors::read_error); } const void* ptr = *raw; memcpy(dst, ptr, size); return ok(); } return make_error_code(lief_errors::read_error); } mutable size_t pos_ = 0; bool endian_swap_ = false; STREAM_TYPE stype_ = STREAM_TYPE::UNKNOWN; }; class ScopedStream { public: ScopedStream(const ScopedStream&) = delete; ScopedStream& operator=(const ScopedStream&) = delete; ScopedStream(ScopedStream&&) = delete; ScopedStream& operator=(ScopedStream&&) = delete; explicit ScopedStream(BinaryStream& stream, uint64_t pos) : pos_{stream.pos()}, stream_{stream} { stream_.setpos(pos); } explicit ScopedStream(BinaryStream& stream) : pos_{stream.pos()}, stream_{stream} {} inline ~ScopedStream() { stream_.setpos(pos_); } private: uint64_t pos_ = 0; BinaryStream& stream_; }; template<class T> result<T> BinaryStream::read() const { result<T> tmp = this->peek<T>(); if (!tmp) { return tmp.error(); } this->increment_pos(sizeof(T)); return tmp; } template<class T> result<T> BinaryStream::peek() const { const auto current_p = pos(); T ret{}; if (auto res = peek_in(&ret, pos(), sizeof(T))) { setpos(current_p); return ret; } setpos(current_p); return make_error_code(lief_errors::read_error); } template<class T> result<T> BinaryStream::peek(size_t offset) const { size_t saved_offset = this->pos(); this->setpos(offset); result<T> r = this->peek<T>(); this->setpos(saved_offset); return r; } template<class T> const T* BinaryStream::peek_array(size_t size) const { result<const void*> raw = this->read_at(this->pos(), sizeof(T) * size); if (!raw) { return nullptr; } return reinterpret_cast<const T*>(raw.value()); } template<class T> const T* BinaryStream::peek_array(size_t offset, size_t size) const { size_t saved_offset = this->pos(); this->setpos(offset); const T* r = this->peek_array<T>(size); this->setpos(saved_offset); return r; } template<typename T> bool BinaryStream::can_read() const { // Even though pos_ + sizeof(T) < ... => pos_ < ... // the addition could overflow so it's worth checking both return pos_ < size() && (pos_ + sizeof(T)) < size(); } template<typename T> bool BinaryStream::can_read(size_t offset) const { // Even though offset + sizeof(T) < ... => offset < ... // the addition could overflow so it's worth checking both return offset < size() && (offset + sizeof(T)) < size(); } template<class T> const T* BinaryStream::read_array(size_t size) const { const T* tmp = this->peek_array<T>(size); this->increment_pos(sizeof(T) * size); return tmp; } template<class T> result<T> BinaryStream::read_conv() const { result<T> tmp = this->peek_conv<T>(); if (!tmp) { return tmp.error(); } this->increment_pos(sizeof(T)); return tmp; } template<class T> typename std::enable_if<std::is_integral<T>::value, result<T>>::type BinaryStream::peek_conv() const { T ret; if (auto res = peek_in(&ret, pos(), sizeof(T))) { if (endian_swap_) { return swap_endian<T>(ret); } return ret; } return make_error_code(lief_errors::read_error); } template<class T> typename std::enable_if<!std::is_integral<T>::value, result<T>>::type BinaryStream::peek_conv() const { T ret; if (auto res = peek_in(&ret, pos(), sizeof(T))) { if (endian_swap_) { LIEF::Convert::swap_endian<T>(&ret); } return ret; } return make_error_code(lief_errors::read_error); } template<class T> result<T> BinaryStream::peek_conv(size_t offset) const { size_t saved_offset = this->pos(); this->setpos(offset); result<T> r = this->peek_conv<T>(); this->setpos(saved_offset); return r; } template<typename T> std::unique_ptr<T[]> BinaryStream::read_conv_array(size_t size) const { const T *t = this->read_array<T>(size); if (t == nullptr) { return nullptr; } std::unique_ptr<T[]> uptr(new T[size]); for (size_t i = 0; i < size; i++) { uptr[i] = t[i]; if (this->endian_swap_) { LIEF::Convert::swap_endian<T>(& uptr[i]); } /* else no conversion, just provide the copied data */ } return uptr; } template<typename T> std::unique_ptr<T[]> BinaryStream::peek_conv_array(size_t offset, size_t size) const { const T *t = this->peek_array<T>(offset, size); if (t == nullptr) { return nullptr; } std::unique_ptr<T[]> uptr(new T[size]); for (size_t i = 0; i < size; i++) { uptr[i] = t[i]; if (this->endian_swap_) { LIEF::Convert::swap_endian<T>(& uptr[i]); } /* else no conversion, just provide the copied data */ } return uptr; } } #endif
/* Copyright 2017 - 2022 R. Thomas * Copyright 2017 - 2022 Quarkslab * * 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 LIEF_BINARY_STREAM_H_ #define LIEF_BINARY_STREAM_H_ #include <cstdint> #include <climits> #include <vector> #include <istream> #include <utility> #include <memory> #include <algorithm> #include "LIEF/BinaryStream/Convert.hpp" #include "LIEF/errors.hpp" struct mbedtls_x509_crt; struct mbedtls_x509_time; namespace LIEF { //! Class that is used to a read stream of data from different sources class BinaryStream { public: enum class STREAM_TYPE { UNKNOWN = 0, VECTOR, MEMORY, SPAN, FILE, ELF_DATA_HANDLER, }; BinaryStream(); virtual ~BinaryStream(); virtual uint64_t size() const = 0; inline STREAM_TYPE type() const { return stype_; } result<uint64_t> read_uleb128() const; result<uint64_t> read_sleb128() const; result<int64_t> read_dwarf_encoded(uint8_t encoding) const; result<std::string> read_string(size_t maxsize = ~static_cast<size_t>(0)) const; result<std::string> peek_string(size_t maxsize = ~static_cast<size_t>(0)) const; result<std::string> peek_string_at(size_t offset, size_t maxsize = ~static_cast<size_t>(0)) const; result<std::u16string> read_u16string() const; result<std::u16string> peek_u16string() const; result<std::string> read_mutf8(size_t maxsize = ~static_cast<size_t>(0)) const; result<std::u16string> read_u16string(size_t length) const; result<std::u16string> peek_u16string(size_t length) const; result<std::u16string> peek_u16string_at(size_t offset, size_t length) const; virtual inline ok_error_t peek_data(std::vector<uint8_t>& container, uint64_t offset, uint64_t size) { if (size == 0) { return ok(); } // Even though offset + size < ... => offset < ... // the addition could overflow so it's worth checking both const bool read_ok = offset <= this->size() && (offset + size) <= this->size(); if (!read_ok) { return make_error_code(lief_errors::read_error); } container.resize(size); if (peek_in(container.data(), offset, size)) { return ok(); } return make_error_code(lief_errors::read_error); } virtual inline ok_error_t read_data(std::vector<uint8_t>& container, uint64_t size) { if (!peek_data(container, pos(), size)) { return make_error_code(lief_errors::read_error); } increment_pos(size); return ok(); } void setpos(size_t pos) const; void increment_pos(size_t value) const; void decrement_pos(size_t value) const; size_t pos() const; operator bool() const; template<class T> const T* read_array(size_t size) const; template<class T> result<T> peek() const; template<class T> result<T> peek(size_t offset) const; template<class T> const T* peek_array(size_t size) const; template<class T> const T* peek_array(size_t offset, size_t size) const; template<class T> result<T> read() const; template<typename T> bool can_read() const; template<typename T> bool can_read(size_t offset) const; size_t align(size_t align_on) const; /* Functions that are endianness aware */ template<class T> typename std::enable_if<std::is_integral<T>::value, result<T>>::type peek_conv() const; template<class T> typename std::enable_if<!std::is_integral<T>::value, result<T>>::type peek_conv() const; template<class T> result<T> peek_conv(size_t offset) const; template<class T> result<T> read_conv() const; /* Read an array of values and adjust endianness as needed */ template<typename T> std::unique_ptr<T[]> read_conv_array(size_t size) const; template<typename T> std::unique_ptr<T[]> peek_conv_array(size_t offset, size_t size) const; template<typename T> static T swap_endian(T u); void set_endian_swap(bool swap); /* ASN.1 & X509 parsing functions */ virtual result<size_t> asn1_read_tag(int tag); virtual result<size_t> asn1_read_len(); virtual result<std::string> asn1_read_alg(); virtual result<std::string> asn1_read_oid(); virtual result<int32_t> asn1_read_int(); virtual result<std::vector<uint8_t>> asn1_read_bitstring(); virtual result<std::vector<uint8_t>> asn1_read_octet_string(); virtual result<std::unique_ptr<mbedtls_x509_crt>> asn1_read_cert(); virtual result<std::string> x509_read_names(); virtual result<std::vector<uint8_t>> x509_read_serial(); virtual result<std::unique_ptr<mbedtls_x509_time>> x509_read_time(); template<class T> static bool is_all_zero(const T& buffer) { const auto* ptr = reinterpret_cast<const uint8_t *const>(&buffer); return std::all_of(ptr, ptr + sizeof(T), [] (uint8_t x) { return x == 0; }); } inline bool should_swap() const { return endian_swap_; } protected: virtual result<const void*> read_at(uint64_t offset, uint64_t size) const = 0; inline virtual ok_error_t peek_in(void* dst, uint64_t offset, uint64_t size) const { if (auto raw = read_at(offset, size)) { if (dst == nullptr) { return make_error_code(lief_errors::read_error); } const void* ptr = *raw; if (ptr == nullptr) { return make_error_code(lief_errors::read_error); } memcpy(dst, ptr, size); return ok(); } return make_error_code(lief_errors::read_error); } mutable size_t pos_ = 0; bool endian_swap_ = false; STREAM_TYPE stype_ = STREAM_TYPE::UNKNOWN; }; class ScopedStream { public: ScopedStream(const ScopedStream&) = delete; ScopedStream& operator=(const ScopedStream&) = delete; ScopedStream(ScopedStream&&) = delete; ScopedStream& operator=(ScopedStream&&) = delete; explicit ScopedStream(BinaryStream& stream, uint64_t pos) : pos_{stream.pos()}, stream_{stream} { stream_.setpos(pos); } explicit ScopedStream(BinaryStream& stream) : pos_{stream.pos()}, stream_{stream} {} inline ~ScopedStream() { stream_.setpos(pos_); } private: uint64_t pos_ = 0; BinaryStream& stream_; }; template<class T> result<T> BinaryStream::read() const { result<T> tmp = this->peek<T>(); if (!tmp) { return tmp.error(); } this->increment_pos(sizeof(T)); return tmp; } template<class T> result<T> BinaryStream::peek() const { const auto current_p = pos(); T ret{}; if (auto res = peek_in(&ret, pos(), sizeof(T))) { setpos(current_p); return ret; } setpos(current_p); return make_error_code(lief_errors::read_error); } template<class T> result<T> BinaryStream::peek(size_t offset) const { size_t saved_offset = this->pos(); this->setpos(offset); result<T> r = this->peek<T>(); this->setpos(saved_offset); return r; } template<class T> const T* BinaryStream::peek_array(size_t size) const { result<const void*> raw = this->read_at(this->pos(), sizeof(T) * size); if (!raw) { return nullptr; } return reinterpret_cast<const T*>(raw.value()); } template<class T> const T* BinaryStream::peek_array(size_t offset, size_t size) const { size_t saved_offset = this->pos(); this->setpos(offset); const T* r = this->peek_array<T>(size); this->setpos(saved_offset); return r; } template<typename T> bool BinaryStream::can_read() const { // Even though pos_ + sizeof(T) < ... => pos_ < ... // the addition could overflow so it's worth checking both return pos_ < size() && (pos_ + sizeof(T)) < size(); } template<typename T> bool BinaryStream::can_read(size_t offset) const { // Even though offset + sizeof(T) < ... => offset < ... // the addition could overflow so it's worth checking both return offset < size() && (offset + sizeof(T)) < size(); } template<class T> const T* BinaryStream::read_array(size_t size) const { const T* tmp = this->peek_array<T>(size); this->increment_pos(sizeof(T) * size); return tmp; } template<class T> result<T> BinaryStream::read_conv() const { result<T> tmp = this->peek_conv<T>(); if (!tmp) { return tmp.error(); } this->increment_pos(sizeof(T)); return tmp; } template<class T> typename std::enable_if<std::is_integral<T>::value, result<T>>::type BinaryStream::peek_conv() const { T ret; if (auto res = peek_in(&ret, pos(), sizeof(T))) { if (endian_swap_) { return swap_endian<T>(ret); } return ret; } return make_error_code(lief_errors::read_error); } template<class T> typename std::enable_if<!std::is_integral<T>::value, result<T>>::type BinaryStream::peek_conv() const { T ret; if (auto res = peek_in(&ret, pos(), sizeof(T))) { if (endian_swap_) { LIEF::Convert::swap_endian<T>(&ret); } return ret; } return make_error_code(lief_errors::read_error); } template<class T> result<T> BinaryStream::peek_conv(size_t offset) const { size_t saved_offset = this->pos(); this->setpos(offset); result<T> r = this->peek_conv<T>(); this->setpos(saved_offset); return r; } template<typename T> std::unique_ptr<T[]> BinaryStream::read_conv_array(size_t size) const { const T *t = this->read_array<T>(size); if (t == nullptr) { return nullptr; } std::unique_ptr<T[]> uptr(new T[size]); for (size_t i = 0; i < size; i++) { uptr[i] = t[i]; if (this->endian_swap_) { LIEF::Convert::swap_endian<T>(& uptr[i]); } /* else no conversion, just provide the copied data */ } return uptr; } template<typename T> std::unique_ptr<T[]> BinaryStream::peek_conv_array(size_t offset, size_t size) const { const T *t = this->peek_array<T>(offset, size); if (t == nullptr) { return nullptr; } std::unique_ptr<T[]> uptr(new T[size]); for (size_t i = 0; i < size; i++) { uptr[i] = t[i]; if (this->endian_swap_) { LIEF::Convert::swap_endian<T>(& uptr[i]); } /* else no conversion, just provide the copied data */ } return uptr; } } #endif
Check that the ptr is not null
Check that the ptr is not null
C++
apache-2.0
lief-project/LIEF,lief-project/LIEF,lief-project/LIEF,lief-project/LIEF
02b2574e7d1ac49b793a0d828dea967eca87fdc9
include/internal/iutest_option_message.hpp
include/internal/iutest_option_message.hpp
//====================================================================== //----------------------------------------------------------------------- /** * @file iutest_option_message.hpp * @brief iris unit test コマンドラインメッセージ ファイル * * @author t.shirayanagi * @par copyright * Copyright (C) 2011-2016, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== #ifndef INCG_IRIS_IUTEST_OPTION_MESSAGE_HPP_00EB9B17_0615_4678_9AD0_1F5B295B404F_ #define INCG_IRIS_IUTEST_OPTION_MESSAGE_HPP_00EB9B17_0615_4678_9AD0_1F5B295B404F_ //====================================================================== // include #include "iutest_console.hpp" namespace iutest { namespace detail { //====================================================================== // class class iuOptionMessage { public: /** * @brief ヘルプの出力 */ static void ShowHelp(); /** * @brief バージョン出力 */ static void ShowVersion(); /** * @brief 機能出力 */ static void ShowFeature(); /** * @brief コンパイラスペック出力 */ static void ShowSpec(); }; inline void iuOptionMessage::ShowHelp() { const char* readme = "--------------------------------------------------\n" "Name\n" " iutest - iris unit test framework\n" "--------------------------------------------------\n" "Command Line Options\n" "\n" " --help, -h : Generate help message.\n" " --iutest_output=xml[:path] : Path of xml report.\n" " --iutest_list_tests : List up tests.\n" " --iutest_list_tests_with_where : List up tests with where.\n" " --iutest_color=<yes|no|auto|ansi>: Console color enable.\n" " --iutest_flagfile=<file> : Set the flag from the file.\n" " --iutest_filter=<filter> : Select the test run.\n" " --iutest_shuffle : Do shuffle test.\n" " --iutest_random_seed=<seed> : Set random seed.\n" " --iutest_also_run_disabled_tests : Run disabled tests.\n" " --iutest_break_on_failure[=0|1] : When that failed to break.\n" " --iutest_throw_on_failure[=0|1] : When that failed to throw.\n" " --iutest_catch_exceptions=<0|1> : Catch exceptions enable.\n" " --iutest_print_time=<0|1> : Setting the display of elapsed time.\n" " --iutest_repeat=<count> : Set the number of repetitions\n" " of the test.\n" #if IUTEST_HAS_STREAM_RESULT " --iutest_stream_result_to=<host:port>\n" " : Set stream test results server.\n" #endif " --iutest_file_location=<auto|vs|gcc>\n" " : Format file location messages.\n" " --verbose : Verbose option.\n" " --feature : Show iutest feature.\n" " --version, -v : Show iutest version.\n" "\n" "--------------------------------------------------\n" "License\n" "\n" " Copyright (c) 2011-2015, Takazumi-Shirayanagi\n" "\n" " This software is released under the new BSD License, see LICENSE\n" "\n"; detail::iuConsole::color_output(detail::iuConsole::cyan, readme); } inline void iuOptionMessage::ShowVersion() { detail::iuConsole::output("iutest version %x.%x.%x.%x\n" , IUTEST_MAJORVER, IUTEST_MINORVER, IUTEST_BUILD, IUTEST_REVISION); } /** @private */ #define IIUT_SHOW_MACRO(macro) detail::iuConsole::output("#define %s %s\n", #macro, IUTEST_PP_TOSTRING(macro)) inline void iuOptionMessage::ShowFeature() { IIUT_SHOW_MACRO(IUTEST_HAS_ANY_PARAM_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_ASSERTION_NOEQUALTO_OBJECT); IIUT_SHOW_MACRO(IUTEST_HAS_ASSERTION_RETURN); IIUT_SHOW_MACRO(IUTEST_HAS_AUTOFIXTURE_PARAM_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_COMBINE); IIUT_SHOW_MACRO(IUTEST_HAS_CONCAT); IIUT_SHOW_MACRO(IUTEST_HAS_CSVPARAMS); IIUT_SHOW_MACRO(IUTEST_HAS_EXCEPTIONS); IIUT_SHOW_MACRO(IUTEST_HAS_GENRAND); IIUT_SHOW_MACRO(IUTEST_HAS_IGNORE_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_LIB); IIUT_SHOW_MACRO(IUTEST_HAS_MATCHERS); IIUT_SHOW_MACRO(IUTEST_HAS_MATCHER_ALLOF_AND_ANYOF); IIUT_SHOW_MACRO(IUTEST_HAS_MATCHER_ELEMENTSARE); IIUT_SHOW_MACRO(IUTEST_HAS_MATCHER_REGEX); IIUT_SHOW_MACRO(IUTEST_HAS_MINIDUMP); IIUT_SHOW_MACRO(IUTEST_HAS_PACKAGE); IIUT_SHOW_MACRO(IUTEST_HAS_PAIRWISE); IIUT_SHOW_MACRO(IUTEST_HAS_PARAM_METHOD_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_PARAM_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_PARAM_TEST_PARAM_NAME_GENERATOR); IIUT_SHOW_MACRO(IUTEST_HAS_PEEP); IIUT_SHOW_MACRO(IUTEST_HAS_PEEP_CLASS); IIUT_SHOW_MACRO(IUTEST_HAS_PEEP_FUNC); IIUT_SHOW_MACRO(IUTEST_HAS_PEEP_STATIC_FUNC); IIUT_SHOW_MACRO(IUTEST_HAS_PRINT_TO); IIUT_SHOW_MACRO(IUTEST_HAS_RANDOMVALUES); IIUT_SHOW_MACRO(IUTEST_HAS_REGEX); IIUT_SHOW_MACRO(IUTEST_HAS_REPORT_SKIPPED); IIUT_SHOW_MACRO(IUTEST_HAS_SOCKET); IIUT_SHOW_MACRO(IUTEST_HAS_SPI_LAMBDA_SUPPORT); IIUT_SHOW_MACRO(IUTEST_HAS_STATIC_ASSERT); IIUT_SHOW_MACRO(IUTEST_HAS_STATIC_ASSERT_TYPEEQ); IIUT_SHOW_MACRO(IUTEST_HAS_STREAM_BUFFER); IIUT_SHOW_MACRO(IUTEST_HAS_STREAM_RESULT); IIUT_SHOW_MACRO(IUTEST_HAS_TESTFIXTURE_ALIAS_BY_TUPLE); IIUT_SHOW_MACRO(IUTEST_HAS_TESTNAME_ALIAS); IIUT_SHOW_MACRO(IUTEST_HAS_TESTNAME_ALIAS_JP); IIUT_SHOW_MACRO(IUTEST_HAS_TYPED_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_TYPED_TEST_APPEND_TYPENAME); IIUT_SHOW_MACRO(IUTEST_HAS_TYPED_TEST_P); IIUT_SHOW_MACRO(IUTEST_HAS_VALUESGEN); IIUT_SHOW_MACRO(IUTEST_HAS_VARIADIC_COMBINE); IIUT_SHOW_MACRO(IUTEST_HAS_VARIADIC_PAIRWISE); IIUT_SHOW_MACRO(IUTEST_HAS_VARIADIC_VALUES); IIUT_SHOW_MACRO(IUTEST_CHECK_STRICT); IIUT_SHOW_MACRO(IUTEST_PLATFORM); IIUT_SHOW_MACRO(IUTEST_USE_THROW_ON_ASSERTION_FAILURE); } inline void iuOptionMessage::ShowSpec() { IIUT_SHOW_MACRO(IUTEST_HAS_ANALYSIS_ASSUME); IIUT_SHOW_MACRO(IUTEST_HAS_ATTRIBUTE); IIUT_SHOW_MACRO(IUTEST_HAS_AUTO); IIUT_SHOW_MACRO(IUTEST_HAS_CHAR16_T); IIUT_SHOW_MACRO(IUTEST_HAS_CHAR32_T); IIUT_SHOW_MACRO(IUTEST_HAS_CLOCK); IIUT_SHOW_MACRO(IUTEST_HAS_CONSTEXPR); IIUT_SHOW_MACRO(IUTEST_HAS_COUNTER_MACRO); IIUT_SHOW_MACRO(IUTEST_HAS_CTIME); IIUT_SHOW_MACRO(IUTEST_HAS_CXX_HDR_CHRONO); IIUT_SHOW_MACRO(IUTEST_HAS_CXX_HDR_CODECVT); IIUT_SHOW_MACRO(IUTEST_HAS_CXX_HDR_RANDOM); IIUT_SHOW_MACRO(IUTEST_HAS_CXX_HDR_REGEX); IIUT_SHOW_MACRO(IUTEST_HAS_CXX11); IIUT_SHOW_MACRO(IUTEST_HAS_DECLTYPE); IIUT_SHOW_MACRO(IUTEST_HAS_DELETED_FUNCTIONS); IIUT_SHOW_MACRO(IUTEST_HAS_EXCEPTIONS); IIUT_SHOW_MACRO(IUTEST_HAS_EXPLICIT_CONVERSION); IIUT_SHOW_MACRO(IUTEST_HAS_EXTERN_TEMPLATE); IIUT_SHOW_MACRO(IUTEST_HAS_GETTIMEOFDAY); IIUT_SHOW_MACRO(IUTEST_HAS_HDR_CXXABI); IIUT_SHOW_MACRO(IUTEST_HAS_HDR_SYSTIME); IIUT_SHOW_MACRO(IUTEST_HAS_HDR_UCHAR); IIUT_SHOW_MACRO(IUTEST_HAS_IF_EXISTS); IIUT_SHOW_MACRO(IUTEST_HAS_INITIALIZER_LIST); IIUT_SHOW_MACRO(IUTEST_HAS_LAMBDA); IIUT_SHOW_MACRO(IUTEST_HAS_LAMBDA_STATEMENTS); IIUT_SHOW_MACRO(IUTEST_HAS_NOEXCEPT); IIUT_SHOW_MACRO(IUTEST_HAS_NULLPTR); IIUT_SHOW_MACRO(IUTEST_HAS_OVERRIDE_AND_FINAL); IIUT_SHOW_MACRO(IUTEST_HAS_RTTI); IIUT_SHOW_MACRO(IUTEST_HAS_RVALUE_REFS); IIUT_SHOW_MACRO(IUTEST_HAS_SEH); IIUT_SHOW_MACRO(IUTEST_HAS_STD_BEGIN_END); IIUT_SHOW_MACRO(IUTEST_HAS_STD_DECLVAL); IIUT_SHOW_MACRO(IUTEST_HAS_STD_EMPLACE); IIUT_SHOW_MACRO(IUTEST_HAS_STRINGSTREAM); IIUT_SHOW_MACRO(IUTEST_HAS_STRONG_ENUMS); IIUT_SHOW_MACRO(IUTEST_HAS_STRSTREAM); IIUT_SHOW_MACRO(IUTEST_HAS_TUPLE); IIUT_SHOW_MACRO(IUTEST_HAS_VARIADIC_TEMPLATES); IIUT_SHOW_MACRO(IUTEST_HAS_VARIADIC_TEMPLATE_TEMPLATES); #ifdef _MSC_FULL_VER IIUT_SHOW_MACRO(_MSC_FULL_VER); #endif #ifdef _LIBCPP_VERSION IIUT_SHOW_MACRO(_LIBCPP_VERSION); #endif #ifdef __GLIBCXX__ IIUT_SHOW_MACRO(__GLIBCXX__); #endif #ifdef __GLIBCPP__ IIUT_SHOW_MACRO(__GLIBCPP__); #endif #ifdef _LIBCPP_VERSION IIUT_SHOW_MACRO(_LIBCPP_VERSION); #endif #undef IIUT_SHOW_MACRO } } // end of namespace detail } // end of namespace iutest #endif // INCG_IRIS_IUTEST_OPTION_MESSAGE_HPP_00EB9B17_0615_4678_9AD0_1F5B295B404F_
//====================================================================== //----------------------------------------------------------------------- /** * @file iutest_option_message.hpp * @brief iris unit test コマンドラインメッセージ ファイル * * @author t.shirayanagi * @par copyright * Copyright (C) 2011-2016, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== #ifndef INCG_IRIS_IUTEST_OPTION_MESSAGE_HPP_00EB9B17_0615_4678_9AD0_1F5B295B404F_ #define INCG_IRIS_IUTEST_OPTION_MESSAGE_HPP_00EB9B17_0615_4678_9AD0_1F5B295B404F_ //====================================================================== // include #include "iutest_console.hpp" namespace iutest { namespace detail { //====================================================================== // class class iuOptionMessage { public: /** * @brief ヘルプの出力 */ static void ShowHelp(); /** * @brief バージョン出力 */ static void ShowVersion(); /** * @brief 機能出力 */ static void ShowFeature(); /** * @brief コンパイラスペック出力 */ static void ShowSpec(); }; inline void iuOptionMessage::ShowHelp() { const char* readme = "--------------------------------------------------\n" "Name\n" " iutest - iris unit test framework\n" "--------------------------------------------------\n" "Command Line Options\n" "\n" " --help, -h : Generate help message.\n" " --iutest_output=xml[:path] : Path of xml report.\n" " --iutest_list_tests : List up tests.\n" " --iutest_list_tests_with_where : List up tests with where.\n" " --iutest_color=<yes|no|auto|ansi>: Console color enable.\n" " --iutest_flagfile=<file> : Set the flag from the file.\n" " --iutest_filter=<filter> : Select the test run.\n" " --iutest_shuffle : Do shuffle test.\n" " --iutest_random_seed=<seed> : Set random seed.\n" " --iutest_also_run_disabled_tests : Run disabled tests.\n" " --iutest_break_on_failure[=0|1] : When that failed to break.\n" " --iutest_throw_on_failure[=0|1] : When that failed to throw.\n" " --iutest_catch_exceptions=<0|1> : Catch exceptions enable.\n" " --iutest_print_time=<0|1> : Setting the display of elapsed time.\n" " --iutest_repeat=<count> : Set the number of repetitions\n" " of the test.\n" #if IUTEST_HAS_STREAM_RESULT " --iutest_stream_result_to=<host:port>\n" " : Set stream test results server.\n" #endif " --iutest_file_location=<auto|vs|gcc>\n" " : Format file location messages.\n" " --verbose : Verbose option.\n" " --feature : Show iutest feature.\n" " --version, -v : Show iutest version.\n" "\n" "--------------------------------------------------\n" "License\n" "\n" " Copyright (c) 2011-2015, Takazumi-Shirayanagi\n" "\n" " This software is released under the new BSD License, see LICENSE\n" "\n"; detail::iuConsole::color_output(detail::iuConsole::cyan, readme); } inline void iuOptionMessage::ShowVersion() { detail::iuConsole::output("iutest version %x.%x.%x.%x\n" , IUTEST_MAJORVER, IUTEST_MINORVER, IUTEST_BUILD, IUTEST_REVISION); } /** @private */ #define IIUT_SHOW_MACRO(macro) detail::iuConsole::output("#define %s %s\n", #macro, IUTEST_PP_TOSTRING(macro)) inline void iuOptionMessage::ShowFeature() { IIUT_SHOW_MACRO(IUTEST_HAS_ANY_PARAM_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_ASSERTION_NOEQUALTO_OBJECT); IIUT_SHOW_MACRO(IUTEST_HAS_ASSERTION_RETURN); IIUT_SHOW_MACRO(IUTEST_HAS_AUTOFIXTURE_PARAM_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_COMBINE); IIUT_SHOW_MACRO(IUTEST_HAS_CONCAT); IIUT_SHOW_MACRO(IUTEST_HAS_CSVPARAMS); IIUT_SHOW_MACRO(IUTEST_HAS_EXCEPTIONS); IIUT_SHOW_MACRO(IUTEST_HAS_GENRAND); IIUT_SHOW_MACRO(IUTEST_HAS_IGNORE_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_LIB); IIUT_SHOW_MACRO(IUTEST_HAS_MATCHERS); IIUT_SHOW_MACRO(IUTEST_HAS_MATCHER_ALLOF_AND_ANYOF); IIUT_SHOW_MACRO(IUTEST_HAS_MATCHER_ELEMENTSARE); IIUT_SHOW_MACRO(IUTEST_HAS_MATCHER_REGEX); IIUT_SHOW_MACRO(IUTEST_HAS_MINIDUMP); IIUT_SHOW_MACRO(IUTEST_HAS_PACKAGE); IIUT_SHOW_MACRO(IUTEST_HAS_PAIRWISE); IIUT_SHOW_MACRO(IUTEST_HAS_PARAM_METHOD_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_PARAM_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_PARAM_TEST_PARAM_NAME_GENERATOR); IIUT_SHOW_MACRO(IUTEST_HAS_PEEP); IIUT_SHOW_MACRO(IUTEST_HAS_PEEP_CLASS); IIUT_SHOW_MACRO(IUTEST_HAS_PEEP_FUNC); IIUT_SHOW_MACRO(IUTEST_HAS_PEEP_STATIC_FUNC); IIUT_SHOW_MACRO(IUTEST_HAS_PRINT_TO); IIUT_SHOW_MACRO(IUTEST_HAS_RANDOMVALUES); IIUT_SHOW_MACRO(IUTEST_HAS_REGEX); IIUT_SHOW_MACRO(IUTEST_HAS_REPORT_SKIPPED); IIUT_SHOW_MACRO(IUTEST_HAS_SOCKET); IIUT_SHOW_MACRO(IUTEST_HAS_SPI_LAMBDA_SUPPORT); IIUT_SHOW_MACRO(IUTEST_HAS_STATIC_ASSERT); IIUT_SHOW_MACRO(IUTEST_HAS_STATIC_ASSERT_TYPEEQ); IIUT_SHOW_MACRO(IUTEST_HAS_STREAM_BUFFER); IIUT_SHOW_MACRO(IUTEST_HAS_STREAM_RESULT); IIUT_SHOW_MACRO(IUTEST_HAS_TESTFIXTURE_ALIAS_BY_TUPLE); IIUT_SHOW_MACRO(IUTEST_HAS_TESTNAME_ALIAS); IIUT_SHOW_MACRO(IUTEST_HAS_TESTNAME_ALIAS_JP); IIUT_SHOW_MACRO(IUTEST_HAS_TYPED_TEST); IIUT_SHOW_MACRO(IUTEST_HAS_TYPED_TEST_APPEND_TYPENAME); IIUT_SHOW_MACRO(IUTEST_HAS_TYPED_TEST_P); IIUT_SHOW_MACRO(IUTEST_HAS_VALUESGEN); IIUT_SHOW_MACRO(IUTEST_HAS_VARIADIC_COMBINE); IIUT_SHOW_MACRO(IUTEST_HAS_VARIADIC_PAIRWISE); IIUT_SHOW_MACRO(IUTEST_HAS_VARIADIC_VALUES); IIUT_SHOW_MACRO(IUTEST_CHECK_STRICT); IIUT_SHOW_MACRO(IUTEST_PLATFORM); IIUT_SHOW_MACRO(IUTEST_USE_THROW_ON_ASSERTION_FAILURE); } inline void iuOptionMessage::ShowSpec() { IIUT_SHOW_MACRO(IUTEST_HAS_ANALYSIS_ASSUME); IIUT_SHOW_MACRO(IUTEST_HAS_ATTRIBUTE); IIUT_SHOW_MACRO(IUTEST_HAS_AUTO); IIUT_SHOW_MACRO(IUTEST_HAS_CHAR16_T); IIUT_SHOW_MACRO(IUTEST_HAS_CHAR32_T); IIUT_SHOW_MACRO(IUTEST_HAS_CLOCK); IIUT_SHOW_MACRO(IUTEST_HAS_CONSTEXPR); IIUT_SHOW_MACRO(IUTEST_HAS_COUNTER_MACRO); IIUT_SHOW_MACRO(IUTEST_HAS_CTIME); IIUT_SHOW_MACRO(IUTEST_HAS_CXX_HDR_CHRONO); IIUT_SHOW_MACRO(IUTEST_HAS_CXX_HDR_CODECVT); IIUT_SHOW_MACRO(IUTEST_HAS_CXX_HDR_RANDOM); IIUT_SHOW_MACRO(IUTEST_HAS_CXX_HDR_REGEX); IIUT_SHOW_MACRO(IUTEST_HAS_CXX11); IIUT_SHOW_MACRO(IUTEST_HAS_DECLTYPE); IIUT_SHOW_MACRO(IUTEST_HAS_DELETED_FUNCTIONS); IIUT_SHOW_MACRO(IUTEST_HAS_EXCEPTIONS); IIUT_SHOW_MACRO(IUTEST_HAS_EXPLICIT_CONVERSION); IIUT_SHOW_MACRO(IUTEST_HAS_EXTERN_TEMPLATE); IIUT_SHOW_MACRO(IUTEST_HAS_GETTIMEOFDAY); IIUT_SHOW_MACRO(IUTEST_HAS_HDR_CXXABI); IIUT_SHOW_MACRO(IUTEST_HAS_HDR_SYSTIME); IIUT_SHOW_MACRO(IUTEST_HAS_HDR_UCHAR); IIUT_SHOW_MACRO(IUTEST_HAS_IF_EXISTS); IIUT_SHOW_MACRO(IUTEST_HAS_INITIALIZER_LIST); IIUT_SHOW_MACRO(IUTEST_HAS_LAMBDA); IIUT_SHOW_MACRO(IUTEST_HAS_LAMBDA_STATEMENTS); IIUT_SHOW_MACRO(IUTEST_HAS_NOEXCEPT); IIUT_SHOW_MACRO(IUTEST_HAS_NULLPTR); IIUT_SHOW_MACRO(IUTEST_HAS_OVERRIDE_AND_FINAL); IIUT_SHOW_MACRO(IUTEST_HAS_RTTI); IIUT_SHOW_MACRO(IUTEST_HAS_RVALUE_REFS); IIUT_SHOW_MACRO(IUTEST_HAS_SEH); IIUT_SHOW_MACRO(IUTEST_HAS_STD_BEGIN_END); IIUT_SHOW_MACRO(IUTEST_HAS_STD_DECLVAL); IIUT_SHOW_MACRO(IUTEST_HAS_STD_EMPLACE); IIUT_SHOW_MACRO(IUTEST_HAS_STRINGSTREAM); IIUT_SHOW_MACRO(IUTEST_HAS_STRONG_ENUMS); IIUT_SHOW_MACRO(IUTEST_HAS_STRSTREAM); IIUT_SHOW_MACRO(IUTEST_HAS_TUPLE); IIUT_SHOW_MACRO(IUTEST_HAS_VARIADIC_TEMPLATES); IIUT_SHOW_MACRO(IUTEST_HAS_VARIADIC_TEMPLATE_TEMPLATES); #ifdef _MSC_FULL_VER IIUT_SHOW_MACRO(_MSC_FULL_VER); #endif #ifdef __GLIBC__ IIUT_SHOW_MACRO(__GLIBC__); #endif #ifdef __GLIBCXX__ IIUT_SHOW_MACRO(__GLIBCXX__); #endif #ifdef __GLIBCPP__ IIUT_SHOW_MACRO(__GLIBCPP__); #endif #ifdef _LIBCPP_VERSION IIUT_SHOW_MACRO(_LIBCPP_VERSION); #endif #undef IIUT_SHOW_MACRO } } // end of namespace detail } // end of namespace iutest #endif // INCG_IRIS_IUTEST_OPTION_MESSAGE_HPP_00EB9B17_0615_4678_9AD0_1F5B295B404F_
update r1086 update spec message
update r1086 update spec message
C++
bsd-3-clause
srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest
dd079183c532b7edfaf02ce6b6a263d8277bcad9
include/mapnik/geometry/boost_adapters.hpp
include/mapnik/geometry/boost_adapters.hpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP #define MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP #include <mapnik/config.hpp> // undef B0 to workaround https://svn.boost.org/trac/boost/ticket/10467 #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #undef B0 #include <boost/geometry/geometry.hpp> #include <boost/geometry/geometries/register/point.hpp> #include <boost/geometry/geometries/register/ring.hpp> #include <boost/geometry/geometries/register/linestring.hpp> #pragma GCC diagnostic pop // mapnik #include <mapnik/geometry.hpp> #include <mapnik/coord.hpp> #include <mapnik/geometry/box2d.hpp> BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::geometry::point<double>, double, boost::geometry::cs::cartesian, x, y) BOOST_GEOMETRY_REGISTER_LINESTRING_TEMPLATED(mapnik::geometry::line_string) BOOST_GEOMETRY_REGISTER_RING_TEMPLATED(mapnik::geometry::linear_ring) // needed by box2d<T> BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, boost::geometry::cs::cartesian, x, y) namespace mapnik { template <typename CoordinateType> struct interior_rings { using polygon_type = mapnik::geometry::polygon<CoordinateType>; using iterator = typename polygon_type::iterator; using const_iterator = typename polygon_type::const_iterator; using value_type = typename polygon_type::value_type; interior_rings(polygon_type & poly) : poly_(poly) {} iterator begin() { auto itr = poly_.begin(); std::advance(itr, 1); return itr; } iterator end() { return poly_.end();} const_iterator begin() const { auto itr = poly_.begin(); std::advance(itr, 1); return itr; } const_iterator end() const { return poly_.end();} void clear() { poly_.resize(1); } void resize(std::size_t size) { poly_.resize(size + 1); } std::size_t size() const { return poly_.empty() ? 0 : poly_.size() - 1; } void push_back(value_type const& val) { poly_.push_back(val); } value_type& back() { return poly_.back(); } value_type const& back() const { return poly_.back(); } polygon_type & poly_; }; } // ns mapnik namespace boost { namespace geometry { namespace traits { template<> struct tag<mapnik::box2d<double> > { using type = box_tag; }; template<> struct point_type<mapnik::box2d<double> > { using type = mapnik::coord2d; }; template <> struct indexed_access<mapnik::box2d<double>, min_corner, 0> { using ct = coordinate_type<mapnik::coord2d>::type; static inline ct get(mapnik::box2d<double> const& b) { return b.minx();} static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); } }; template <> struct indexed_access<mapnik::box2d<double>, min_corner, 1> { using ct = coordinate_type<mapnik::coord2d>::type; static inline ct get(mapnik::box2d<double> const& b) { return b.miny();} static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); } }; template <> struct indexed_access<mapnik::box2d<double>, max_corner, 0> { using ct = coordinate_type<mapnik::coord2d>::type; static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();} static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); } }; template <> struct indexed_access<mapnik::box2d<double>, max_corner, 1> { using ct = coordinate_type<mapnik::coord2d>::type; static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();} static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); } }; template<typename CoordinateType> struct tag<mapnik::geometry::polygon<CoordinateType> > { using type = polygon_tag; }; template <typename CoordinateType> struct point_order<mapnik::geometry::linear_ring<CoordinateType> > { static const order_selector value = counterclockwise; }; template<typename CoordinateType> struct tag<mapnik::geometry::multi_point<CoordinateType> > { using type = multi_point_tag; }; template<typename CoordinateType> struct tag<mapnik::geometry::multi_line_string<CoordinateType> > { using type = multi_linestring_tag; }; template<typename CoordinateType> struct tag<mapnik::geometry::multi_polygon<CoordinateType> > { using type = multi_polygon_tag; }; // ring template <typename CoordinateType> struct ring_const_type<mapnik::geometry::polygon<CoordinateType> > { using type = typename mapnik::geometry::linear_ring<CoordinateType> const&; }; template <typename CoordinateType> struct ring_mutable_type<mapnik::geometry::polygon<CoordinateType> > { using type = typename mapnik::geometry::linear_ring<CoordinateType>&; }; // interior template <typename CoordinateType> struct interior_const_type<mapnik::geometry::polygon<CoordinateType> > { using type = typename mapnik::interior_rings<CoordinateType> const; }; template <typename CoordinateType> struct interior_mutable_type<mapnik::geometry::polygon<CoordinateType> > { using type = typename mapnik::interior_rings<CoordinateType> ; }; template <typename CoordinateType> struct exterior_ring<mapnik::geometry::polygon<CoordinateType> > { using ring_const_type = typename ring_const_type<mapnik::geometry::polygon<CoordinateType> >::type; using ring_mutable_type = typename ring_mutable_type<mapnik::geometry::polygon<CoordinateType> >::type; static ring_mutable_type get(mapnik::geometry::polygon<CoordinateType> & p) { if (p.empty()) p.resize(1); return p[0]; } static ring_const_type get(mapnik::geometry::polygon<CoordinateType> const& p) { if (p.empty()) throw std::runtime_error("Exterior ring must be initialized!"); return p[0]; } }; template <typename CoordinateType> struct interior_rings<mapnik::geometry::polygon<CoordinateType> > { using interior_const_type = typename interior_const_type<mapnik::geometry::polygon<CoordinateType> >::type; using interior_mutable_type = typename interior_mutable_type<mapnik::geometry::polygon<CoordinateType> >::type; static interior_const_type get(mapnik::geometry::polygon<CoordinateType> const& p) { return mapnik::interior_rings<CoordinateType>(const_cast<mapnik::geometry::polygon<CoordinateType>&>(p)); } static interior_mutable_type get(mapnik::geometry::polygon<CoordinateType>& p) { return mapnik::interior_rings<CoordinateType>(p); } }; }}} #endif //MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP #define MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP #include <mapnik/config.hpp> // undef B0 to workaround https://svn.boost.org/trac/boost/ticket/10467 #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #undef B0 #include <boost/geometry/geometry.hpp> #include <boost/geometry/geometries/register/point.hpp> #include <boost/geometry/geometries/register/ring.hpp> #include <boost/geometry/geometries/register/linestring.hpp> #pragma GCC diagnostic pop // mapnik #include <mapnik/geometry.hpp> #include <mapnik/coord.hpp> #include <mapnik/geometry/box2d.hpp> BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::geometry::point<double>, double, boost::geometry::cs::cartesian, x, y) BOOST_GEOMETRY_REGISTER_POINT_2D (mapnik::geometry::point<std::int64_t>, std::int64_t, boost::geometry::cs::cartesian, x, y) BOOST_GEOMETRY_REGISTER_LINESTRING_TEMPLATED(mapnik::geometry::line_string) BOOST_GEOMETRY_REGISTER_RING_TEMPLATED(mapnik::geometry::linear_ring) // needed by box2d<T> BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, boost::geometry::cs::cartesian, x, y) namespace mapnik { template <typename CoordinateType> struct interior_rings { using polygon_type = mapnik::geometry::polygon<CoordinateType>; using iterator = typename polygon_type::iterator; using const_iterator = typename polygon_type::const_iterator; using value_type = typename polygon_type::value_type; interior_rings(polygon_type & poly) : poly_(poly) {} iterator begin() { auto itr = poly_.begin(); std::advance(itr, 1); return itr; } iterator end() { return poly_.end();} const_iterator begin() const { auto itr = poly_.begin(); std::advance(itr, 1); return itr; } const_iterator end() const { return poly_.end();} void clear() { poly_.resize(1); } void resize(std::size_t size) { poly_.resize(size + 1); } std::size_t size() const { return poly_.empty() ? 0 : poly_.size() - 1; } void push_back(value_type const& val) { poly_.push_back(val); } value_type& back() { return poly_.back(); } value_type const& back() const { return poly_.back(); } polygon_type & poly_; }; } // ns mapnik namespace boost { namespace geometry { namespace traits { template<> struct tag<mapnik::box2d<double> > { using type = box_tag; }; template<> struct point_type<mapnik::box2d<double> > { using type = mapnik::coord2d; }; template <> struct indexed_access<mapnik::box2d<double>, min_corner, 0> { using ct = coordinate_type<mapnik::coord2d>::type; static inline ct get(mapnik::box2d<double> const& b) { return b.minx();} static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); } }; template <> struct indexed_access<mapnik::box2d<double>, min_corner, 1> { using ct = coordinate_type<mapnik::coord2d>::type; static inline ct get(mapnik::box2d<double> const& b) { return b.miny();} static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); } }; template <> struct indexed_access<mapnik::box2d<double>, max_corner, 0> { using ct = coordinate_type<mapnik::coord2d>::type; static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();} static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); } }; template <> struct indexed_access<mapnik::box2d<double>, max_corner, 1> { using ct = coordinate_type<mapnik::coord2d>::type; static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();} static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); } }; template<typename CoordinateType> struct tag<mapnik::geometry::polygon<CoordinateType> > { using type = polygon_tag; }; template <typename CoordinateType> struct point_order<mapnik::geometry::linear_ring<CoordinateType> > { static const order_selector value = counterclockwise; }; template<typename CoordinateType> struct tag<mapnik::geometry::multi_point<CoordinateType> > { using type = multi_point_tag; }; template<typename CoordinateType> struct tag<mapnik::geometry::multi_line_string<CoordinateType> > { using type = multi_linestring_tag; }; template<typename CoordinateType> struct tag<mapnik::geometry::multi_polygon<CoordinateType> > { using type = multi_polygon_tag; }; // ring template <typename CoordinateType> struct ring_const_type<mapnik::geometry::polygon<CoordinateType> > { using type = typename mapnik::geometry::linear_ring<CoordinateType> const&; }; template <typename CoordinateType> struct ring_mutable_type<mapnik::geometry::polygon<CoordinateType> > { using type = typename mapnik::geometry::linear_ring<CoordinateType>&; }; // interior template <typename CoordinateType> struct interior_const_type<mapnik::geometry::polygon<CoordinateType> > { using type = typename mapnik::interior_rings<CoordinateType> const; }; template <typename CoordinateType> struct interior_mutable_type<mapnik::geometry::polygon<CoordinateType> > { using type = typename mapnik::interior_rings<CoordinateType> ; }; template <typename CoordinateType> struct exterior_ring<mapnik::geometry::polygon<CoordinateType> > { using ring_const_type = typename ring_const_type<mapnik::geometry::polygon<CoordinateType> >::type; using ring_mutable_type = typename ring_mutable_type<mapnik::geometry::polygon<CoordinateType> >::type; static ring_mutable_type get(mapnik::geometry::polygon<CoordinateType> & p) { if (p.empty()) p.resize(1); return p[0]; } static ring_const_type get(mapnik::geometry::polygon<CoordinateType> const& p) { if (p.empty()) throw std::runtime_error("Exterior ring must be initialized!"); return p[0]; } }; template <typename CoordinateType> struct interior_rings<mapnik::geometry::polygon<CoordinateType> > { using interior_const_type = typename interior_const_type<mapnik::geometry::polygon<CoordinateType> >::type; using interior_mutable_type = typename interior_mutable_type<mapnik::geometry::polygon<CoordinateType> >::type; static interior_const_type get(mapnik::geometry::polygon<CoordinateType> const& p) { return mapnik::interior_rings<CoordinateType>(const_cast<mapnik::geometry::polygon<CoordinateType>&>(p)); } static interior_mutable_type get(mapnik::geometry::polygon<CoordinateType>& p) { return mapnik::interior_rings<CoordinateType>(p); } }; template <typename CoordinateType> struct resize<mapnik::interior_rings<CoordinateType>> { static inline void apply(mapnik::interior_rings<CoordinateType> interiors, std::size_t new_size) { interiors.resize(new_size); } }; template <typename CoordinateType> struct clear<mapnik::interior_rings<CoordinateType>> { static inline void apply(mapnik::interior_rings<CoordinateType> interiors) { interiors.clear(); } }; }}} #endif //MAPNIK_BOOST_GEOMETRY_ADAPTERS_HPP
add `boost::geometry::resize` and `boost::geometry::clear` traits specialisations for `mapnik::interior_rings<CoordinateType>`
add `boost::geometry::resize` and `boost::geometry::clear` traits specialisations for `mapnik::interior_rings<CoordinateType>`
C++
lgpl-2.1
lightmare/mapnik,tomhughes/mapnik,tomhughes/mapnik,lightmare/mapnik,mapnik/mapnik,mapnik/mapnik,lightmare/mapnik,lightmare/mapnik,mapnik/mapnik,mapnik/mapnik,naturalatlas/mapnik,tomhughes/mapnik,naturalatlas/mapnik,naturalatlas/mapnik,tomhughes/mapnik,naturalatlas/mapnik
3fca996c0f676ca3cb6f3512497210d81deb5133
src/version.cpp
src/version.cpp
// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number // Refer to version.h for current version number #define CLIENT_VERSION_SUFFIX "-cgb" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "df9d55a" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE);
// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("AndroidsTokens"); // Client version number // Refer to version.h for current version number #define CLIENT_VERSION_SUFFIX "-ADTv2" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "df9d55a" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE);
Update version.cpp
Update version.cpp
C++
mit
Crypto2/AndroidsTokens_v2,CryptoRepairCrew/Android-Token-V2,CryptoRepairCrew/Android-Token-V2,CryptoRepairCrew/Android-Token-V2,Crypto2/AndroidsTokens_v2,Crypto2/AndroidsTokens_v2,Crypto2/AndroidsTokens_v2,CryptoRepairCrew/Android-Token-V2,CryptoRepairCrew/Android-Token-V2
8c34e7c3f12af273f3f0941ddcd6d31dc7593279
src/cpp/server/server_builder.cc
src/cpp/server/server_builder.cc
/* * * Copyright 2015-2016, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <grpc++/server_builder.h> #include <grpc++/impl/service_type.h> #include <grpc++/server.h> #include <grpc/support/cpu.h> #include <grpc/support/log.h> #include "src/cpp/server/thread_pool_interface.h" namespace grpc { static std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>* g_plugin_factory_list; static gpr_once once_init_plugin_list = GPR_ONCE_INIT; static void do_plugin_list_init(void) { g_plugin_factory_list = new std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>(); } ServerBuilder::ServerBuilder() : max_message_size_(-1), generic_service_(nullptr) { grpc_compression_options_init(&compression_options_); gpr_once_init(&once_init_plugin_list, do_plugin_list_init); for (auto factory : (*g_plugin_factory_list)) { std::unique_ptr<ServerBuilderPlugin> plugin = factory(); plugins_[plugin->name()] = std::move(plugin); } } std::unique_ptr<ServerCompletionQueue> ServerBuilder::AddCompletionQueue( bool is_frequently_polled) { ServerCompletionQueue* cq = new ServerCompletionQueue(is_frequently_polled); cqs_.push_back(cq); return std::unique_ptr<ServerCompletionQueue>(cq); } void ServerBuilder::RegisterService(Service* service) { services_.emplace_back(new NamedService(service)); } void ServerBuilder::RegisterService(const grpc::string& addr, Service* service) { services_.emplace_back(new NamedService(addr, service)); } void ServerBuilder::RegisterAsyncGenericService(AsyncGenericService* service) { if (generic_service_) { gpr_log(GPR_ERROR, "Adding multiple AsyncGenericService is unsupported for now. " "Dropping the service %p", service); return; } generic_service_ = service; } void ServerBuilder::SetOption(std::unique_ptr<ServerBuilderOption> option) { options_.push_back(std::move(option)); } void ServerBuilder::AddListeningPort(const grpc::string& addr, std::shared_ptr<ServerCredentials> creds, int* selected_port) { Port port = {addr, creds, selected_port}; ports_.push_back(port); } std::unique_ptr<Server> ServerBuilder::BuildAndStart() { std::unique_ptr<ThreadPoolInterface> thread_pool; for (auto it = services_.begin(); it != services_.end(); ++it) { if ((*it)->service->has_synchronous_methods()) { if (thread_pool == nullptr) { thread_pool.reset(CreateDefaultThreadPool()); break; } } } ChannelArguments args; for (auto option = options_.begin(); option != options_.end(); ++option) { (*option)->UpdateArguments(&args); (*option)->UpdatePlugins(&plugins_); } if (thread_pool == nullptr) { for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { if ((*plugin).second->has_sync_methods()) { thread_pool.reset(CreateDefaultThreadPool()); break; } } } if (max_message_size_ > 0) { args.SetInt(GRPC_ARG_MAX_MESSAGE_LENGTH, max_message_size_); } args.SetInt(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET, compression_options_.enabled_algorithms_bitset); std::unique_ptr<Server> server( new Server(thread_pool.release(), true, max_message_size_, &args)); ServerInitializer* initializer = server->initializer(); int num_non_listening_cqs = 0; for (auto cq = cqs_.begin(); cq != cqs_.end(); ++cq) { // A completion queue that is not polled frequently (by calling Next() or // AsyncNext()) is not safe to use for listening to incoming channels. // Register all such completion queues as non-listening completion queues // with the GRPC core library. if ((*cq)->IsFrequentlyPolled()) { grpc_server_register_completion_queue(server->server_, (*cq)->cq(), nullptr); } else { grpc_server_register_non_listening_completion_queue(server->server_, (*cq)->cq(), nullptr); num_non_listening_cqs++; } } // TODO: (sreek) - Find a good way to determine whether the server is a Sync // server or an Async server. In case of Async server, return an error if all // the completion queues are non-listening if (num_non_listening_cqs >= 0) { gpr_log(GPR_INFO, "Number of non listening completion queues: %d out of %d", num_non_listening_cqs, cqs_.size()); } for (auto service = services_.begin(); service != services_.end(); service++) { if (!server->RegisterService((*service)->host.get(), (*service)->service)) { return nullptr; } } for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin).second->InitServer(initializer); } if (generic_service_) { server->RegisterAsyncGenericService(generic_service_); } else { for (auto it = services_.begin(); it != services_.end(); ++it) { if ((*it)->service->has_generic_methods()) { gpr_log(GPR_ERROR, "Some methods were marked generic but there is no " "generic service registered."); return nullptr; } } } for (auto port = ports_.begin(); port != ports_.end(); port++) { int r = server->AddListeningPort(port->addr, port->creds.get()); if (!r) return nullptr; if (port->selected_port != nullptr) { *port->selected_port = r; } } auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0]; if (!server->Start(cqs_data, cqs_.size())) { return nullptr; } for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin).second->Finish(initializer); } return server; } void ServerBuilder::InternalAddPluginFactory( std::unique_ptr<ServerBuilderPlugin> (*CreatePlugin)()) { gpr_once_init(&once_init_plugin_list, do_plugin_list_init); (*g_plugin_factory_list).push_back(CreatePlugin); } } // namespace grpc
/* * * Copyright 2015-2016, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <grpc++/server_builder.h> #include <grpc++/impl/service_type.h> #include <grpc++/server.h> #include <grpc/support/cpu.h> #include <grpc/support/log.h> #include "src/cpp/server/thread_pool_interface.h" namespace grpc { static std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>* g_plugin_factory_list; static gpr_once once_init_plugin_list = GPR_ONCE_INIT; static void do_plugin_list_init(void) { g_plugin_factory_list = new std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>(); } ServerBuilder::ServerBuilder() : max_message_size_(-1), generic_service_(nullptr) { grpc_compression_options_init(&compression_options_); gpr_once_init(&once_init_plugin_list, do_plugin_list_init); for (auto factory : (*g_plugin_factory_list)) { std::unique_ptr<ServerBuilderPlugin> plugin = factory(); plugins_[plugin->name()] = std::move(plugin); } } std::unique_ptr<ServerCompletionQueue> ServerBuilder::AddCompletionQueue( bool is_frequently_polled) { ServerCompletionQueue* cq = new ServerCompletionQueue(is_frequently_polled); cqs_.push_back(cq); return std::unique_ptr<ServerCompletionQueue>(cq); } void ServerBuilder::RegisterService(Service* service) { services_.emplace_back(new NamedService(service)); } void ServerBuilder::RegisterService(const grpc::string& addr, Service* service) { services_.emplace_back(new NamedService(addr, service)); } void ServerBuilder::RegisterAsyncGenericService(AsyncGenericService* service) { if (generic_service_) { gpr_log(GPR_ERROR, "Adding multiple AsyncGenericService is unsupported for now. " "Dropping the service %p", service); return; } generic_service_ = service; } void ServerBuilder::SetOption(std::unique_ptr<ServerBuilderOption> option) { options_.push_back(std::move(option)); } void ServerBuilder::AddListeningPort(const grpc::string& addr, std::shared_ptr<ServerCredentials> creds, int* selected_port) { Port port = {addr, creds, selected_port}; ports_.push_back(port); } std::unique_ptr<Server> ServerBuilder::BuildAndStart() { std::unique_ptr<ThreadPoolInterface> thread_pool; for (auto it = services_.begin(); it != services_.end(); ++it) { if ((*it)->service->has_synchronous_methods()) { if (thread_pool == nullptr) { thread_pool.reset(CreateDefaultThreadPool()); break; } } } ChannelArguments args; for (auto option = options_.begin(); option != options_.end(); ++option) { (*option)->UpdateArguments(&args); (*option)->UpdatePlugins(&plugins_); } if (thread_pool == nullptr) { for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { if ((*plugin).second->has_sync_methods()) { thread_pool.reset(CreateDefaultThreadPool()); break; } } } if (max_message_size_ > 0) { args.SetInt(GRPC_ARG_MAX_MESSAGE_LENGTH, max_message_size_); } args.SetInt(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET, compression_options_.enabled_algorithms_bitset); std::unique_ptr<Server> server( new Server(thread_pool.release(), true, max_message_size_, &args)); ServerInitializer* initializer = server->initializer(); int num_non_listening_cqs = 0; for (auto cq = cqs_.begin(); cq != cqs_.end(); ++cq) { // A completion queue that is not polled frequently (by calling Next() or // AsyncNext()) is not safe to use for listening to incoming channels. // Register all such completion queues as non-listening completion queues // with the GRPC core library. if ((*cq)->IsFrequentlyPolled()) { grpc_server_register_completion_queue(server->server_, (*cq)->cq(), nullptr); } else { grpc_server_register_non_listening_completion_queue(server->server_, (*cq)->cq(), nullptr); num_non_listening_cqs++; } } // TODO: (sreek) - Find a good way to determine whether the server is a Sync // server or an Async server. In case of Async server, return an error if all // the completion queues are non-listening if (num_non_listening_cqs > 0) { gpr_log(GPR_INFO, "Number of non listening completion queues: %d out of %d", num_non_listening_cqs, cqs_.size()); } for (auto service = services_.begin(); service != services_.end(); service++) { if (!server->RegisterService((*service)->host.get(), (*service)->service)) { return nullptr; } } for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin).second->InitServer(initializer); } if (generic_service_) { server->RegisterAsyncGenericService(generic_service_); } else { for (auto it = services_.begin(); it != services_.end(); ++it) { if ((*it)->service->has_generic_methods()) { gpr_log(GPR_ERROR, "Some methods were marked generic but there is no " "generic service registered."); return nullptr; } } } for (auto port = ports_.begin(); port != ports_.end(); port++) { int r = server->AddListeningPort(port->addr, port->creds.get()); if (!r) return nullptr; if (port->selected_port != nullptr) { *port->selected_port = r; } } auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0]; if (!server->Start(cqs_data, cqs_.size())) { return nullptr; } for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin).second->Finish(initializer); } return server; } void ServerBuilder::InternalAddPluginFactory( std::unique_ptr<ServerBuilderPlugin> (*CreatePlugin)()) { gpr_once_init(&once_init_plugin_list, do_plugin_list_init); (*g_plugin_factory_list).push_back(CreatePlugin); } } // namespace grpc
Fix a typo
Fix a typo
C++
bsd-3-clause
LuminateWireless/grpc,LuminateWireless/grpc,a11r/grpc,ejona86/grpc,geffzhang/grpc,matt-kwong/grpc,mehrdada/grpc,firebase/grpc,pmarks-net/grpc,grpc/grpc,jtattermusch/grpc,y-zeng/grpc,dgquintas/grpc,ppietrasa/grpc,jtattermusch/grpc,Vizerai/grpc,stanley-cheung/grpc,geffzhang/grpc,adelez/grpc,pmarks-net/grpc,yongni/grpc,grani/grpc,hstefan/grpc,zhimingxie/grpc,podsvirov/grpc,matt-kwong/grpc,baylabs/grpc,wcevans/grpc,andrewpollock/grpc,kriswuollett/grpc,greasypizza/grpc,daniel-j-born/grpc,jboeuf/grpc,quizlet/grpc,malexzx/grpc,vjpai/grpc,murgatroid99/grpc,kpayson64/grpc,grpc/grpc,Crevil/grpc,thunderboltsid/grpc,hstefan/grpc,greasypizza/grpc,adelez/grpc,philcleveland/grpc,dklempner/grpc,MakMukhi/grpc,quizlet/grpc,ppietrasa/grpc,mehrdada/grpc,soltanmm-google/grpc,soltanmm-google/grpc,yongni/grpc,hstefan/grpc,makdharma/grpc,carl-mastrangelo/grpc,philcleveland/grpc,malexzx/grpc,y-zeng/grpc,soltanmm/grpc,a11r/grpc,thinkerou/grpc,LuminateWireless/grpc,rjshade/grpc,greasypizza/grpc,yugui/grpc,wcevans/grpc,jtattermusch/grpc,thinkerou/grpc,kriswuollett/grpc,firebase/grpc,yongni/grpc,stanley-cheung/grpc,dgquintas/grpc,grani/grpc,kpayson64/grpc,kskalski/grpc,pmarks-net/grpc,royalharsh/grpc,PeterFaiman/ruby-grpc-minimal,murgatroid99/grpc,msmania/grpc,ctiller/grpc,tengyifei/grpc,firebase/grpc,perumaalgoog/grpc,7anner/grpc,mehrdada/grpc,jtattermusch/grpc,firebase/grpc,malexzx/grpc,vjpai/grpc,fuchsia-mirror/third_party-grpc,Vizerai/grpc,wcevans/grpc,hstefan/grpc,chrisdunelm/grpc,ctiller/grpc,grpc/grpc,LuminateWireless/grpc,adelez/grpc,firebase/grpc,soltanmm-google/grpc,ncteisen/grpc,adelez/grpc,jcanizales/grpc,mehrdada/grpc,zhimingxie/grpc,thinkerou/grpc,chrisdunelm/grpc,infinit/grpc,sreecha/grpc,jboeuf/grpc,greasypizza/grpc,adelez/grpc,ncteisen/grpc,thunderboltsid/grpc,makdharma/grpc,sreecha/grpc,stanley-cheung/grpc,murgatroid99/grpc,perumaalgoog/grpc,soltanmm/grpc,carl-mastrangelo/grpc,vsco/grpc,jboeuf/grpc,simonkuang/grpc,deepaklukose/grpc,geffzhang/grpc,dklempner/grpc,mehrdada/grpc,ncteisen/grpc,donnadionne/grpc,Crevil/grpc,baylabs/grpc,rjshade/grpc,yongni/grpc,matt-kwong/grpc,royalharsh/grpc,tengyifei/grpc,donnadionne/grpc,kriswuollett/grpc,daniel-j-born/grpc,kskalski/grpc,donnadionne/grpc,MakMukhi/grpc,ctiller/grpc,grani/grpc,ejona86/grpc,muxi/grpc,msmania/grpc,MakMukhi/grpc,carl-mastrangelo/grpc,daniel-j-born/grpc,kskalski/grpc,podsvirov/grpc,Vizerai/grpc,PeterFaiman/ruby-grpc-minimal,podsvirov/grpc,baylabs/grpc,ipylypiv/grpc,yongni/grpc,bogdandrutu/grpc,nicolasnoble/grpc,dklempner/grpc,grpc/grpc,stanley-cheung/grpc,ncteisen/grpc,nicolasnoble/grpc,deepaklukose/grpc,adelez/grpc,ncteisen/grpc,deepaklukose/grpc,geffzhang/grpc,quizlet/grpc,perumaalgoog/grpc,muxi/grpc,nicolasnoble/grpc,baylabs/grpc,Crevil/grpc,chrisdunelm/grpc,simonkuang/grpc,fuchsia-mirror/third_party-grpc,deepaklukose/grpc,quizlet/grpc,grpc/grpc,nicolasnoble/grpc,Vizerai/grpc,leifurhauks/grpc,dgquintas/grpc,murgatroid99/grpc,grpc/grpc,Vizerai/grpc,ctiller/grpc,royalharsh/grpc,makdharma/grpc,chrisdunelm/grpc,jtattermusch/grpc,soltanmm/grpc,matt-kwong/grpc,firebase/grpc,malexzx/grpc,Crevil/grpc,soltanmm-google/grpc,rjshade/grpc,yugui/grpc,sreecha/grpc,greasypizza/grpc,wcevans/grpc,dklempner/grpc,daniel-j-born/grpc,stanley-cheung/grpc,yang-g/grpc,daniel-j-born/grpc,philcleveland/grpc,kskalski/grpc,7anner/grpc,pmarks-net/grpc,kskalski/grpc,pmarks-net/grpc,vjpai/grpc,muxi/grpc,bogdandrutu/grpc,sreecha/grpc,pmarks-net/grpc,mehrdada/grpc,jtattermusch/grpc,LuminateWireless/grpc,jboeuf/grpc,firebase/grpc,MakMukhi/grpc,podsvirov/grpc,soltanmm/grpc,apolcyn/grpc,a11r/grpc,simonkuang/grpc,zhimingxie/grpc,Vizerai/grpc,nicolasnoble/grpc,simonkuang/grpc,bogdandrutu/grpc,ncteisen/grpc,baylabs/grpc,malexzx/grpc,stanley-cheung/grpc,grani/grpc,grpc/grpc,donnadionne/grpc,yugui/grpc,apolcyn/grpc,thinkerou/grpc,dgquintas/grpc,philcleveland/grpc,msmania/grpc,wcevans/grpc,7anner/grpc,leifurhauks/grpc,jboeuf/grpc,matt-kwong/grpc,vsco/grpc,geffzhang/grpc,vjpai/grpc,chrisdunelm/grpc,wcevans/grpc,msmania/grpc,firebase/grpc,tengyifei/grpc,leifurhauks/grpc,bogdandrutu/grpc,carl-mastrangelo/grpc,MakMukhi/grpc,jboeuf/grpc,andrewpollock/grpc,zhimingxie/grpc,apolcyn/grpc,adelez/grpc,Crevil/grpc,makdharma/grpc,vjpai/grpc,ipylypiv/grpc,fuchsia-mirror/third_party-grpc,thinkerou/grpc,a-veitch/grpc,grpc/grpc,leifurhauks/grpc,jtattermusch/grpc,podsvirov/grpc,LuminateWireless/grpc,LuminateWireless/grpc,nicolasnoble/grpc,msmania/grpc,jcanizales/grpc,ipylypiv/grpc,mehrdada/grpc,andrewpollock/grpc,jcanizales/grpc,yang-g/grpc,hstefan/grpc,jtattermusch/grpc,murgatroid99/grpc,tengyifei/grpc,stanley-cheung/grpc,jtattermusch/grpc,ipylypiv/grpc,grani/grpc,simonkuang/grpc,LuminateWireless/grpc,PeterFaiman/ruby-grpc-minimal,thunderboltsid/grpc,y-zeng/grpc,jtattermusch/grpc,vsco/grpc,nicolasnoble/grpc,muxi/grpc,dgquintas/grpc,mehrdada/grpc,deepaklukose/grpc,PeterFaiman/ruby-grpc-minimal,quizlet/grpc,kumaralokgithub/grpc,sreecha/grpc,ejona86/grpc,soltanmm-google/grpc,thinkerou/grpc,carl-mastrangelo/grpc,kskalski/grpc,vjpai/grpc,apolcyn/grpc,y-zeng/grpc,infinit/grpc,jcanizales/grpc,geffzhang/grpc,y-zeng/grpc,infinit/grpc,muxi/grpc,fuchsia-mirror/third_party-grpc,fuchsia-mirror/third_party-grpc,yugui/grpc,quizlet/grpc,perumaalgoog/grpc,zhimingxie/grpc,nicolasnoble/grpc,ipylypiv/grpc,podsvirov/grpc,Crevil/grpc,ppietrasa/grpc,msmania/grpc,muxi/grpc,yugui/grpc,thinkerou/grpc,makdharma/grpc,a-veitch/grpc,apolcyn/grpc,jcanizales/grpc,rjshade/grpc,ejona86/grpc,pszemus/grpc,bogdandrutu/grpc,jcanizales/grpc,arkmaxim/grpc,royalharsh/grpc,andrewpollock/grpc,dgquintas/grpc,ctiller/grpc,philcleveland/grpc,firebase/grpc,pmarks-net/grpc,murgatroid99/grpc,perumaalgoog/grpc,fuchsia-mirror/third_party-grpc,deepaklukose/grpc,pszemus/grpc,makdharma/grpc,ppietrasa/grpc,a-veitch/grpc,firebase/grpc,carl-mastrangelo/grpc,ejona86/grpc,murgatroid99/grpc,ppietrasa/grpc,msmania/grpc,ppietrasa/grpc,leifurhauks/grpc,7anner/grpc,pszemus/grpc,malexzx/grpc,thunderboltsid/grpc,kpayson64/grpc,thunderboltsid/grpc,infinit/grpc,arkmaxim/grpc,jboeuf/grpc,rjshade/grpc,leifurhauks/grpc,infinit/grpc,baylabs/grpc,thunderboltsid/grpc,tengyifei/grpc,muxi/grpc,quizlet/grpc,greasypizza/grpc,kriswuollett/grpc,infinit/grpc,hstefan/grpc,kumaralokgithub/grpc,deepaklukose/grpc,vsco/grpc,arkmaxim/grpc,vjpai/grpc,jtattermusch/grpc,wcevans/grpc,sreecha/grpc,leifurhauks/grpc,yongni/grpc,kpayson64/grpc,PeterFaiman/ruby-grpc-minimal,chrisdunelm/grpc,soltanmm-google/grpc,apolcyn/grpc,geffzhang/grpc,soltanmm/grpc,yongni/grpc,thunderboltsid/grpc,PeterFaiman/ruby-grpc-minimal,pszemus/grpc,a11r/grpc,matt-kwong/grpc,baylabs/grpc,ncteisen/grpc,msmania/grpc,baylabs/grpc,hstefan/grpc,thunderboltsid/grpc,nicolasnoble/grpc,stanley-cheung/grpc,a-veitch/grpc,muxi/grpc,sreecha/grpc,malexzx/grpc,donnadionne/grpc,kriswuollett/grpc,greasypizza/grpc,apolcyn/grpc,kumaralokgithub/grpc,geffzhang/grpc,makdharma/grpc,ejona86/grpc,ppietrasa/grpc,PeterFaiman/ruby-grpc-minimal,sreecha/grpc,sreecha/grpc,simonkuang/grpc,royalharsh/grpc,a-veitch/grpc,thinkerou/grpc,podsvirov/grpc,adelez/grpc,matt-kwong/grpc,hstefan/grpc,kskalski/grpc,rjshade/grpc,ipylypiv/grpc,simonkuang/grpc,yang-g/grpc,chrisdunelm/grpc,yang-g/grpc,rjshade/grpc,yang-g/grpc,carl-mastrangelo/grpc,geffzhang/grpc,carl-mastrangelo/grpc,kskalski/grpc,7anner/grpc,arkmaxim/grpc,arkmaxim/grpc,ejona86/grpc,pszemus/grpc,kpayson64/grpc,donnadionne/grpc,daniel-j-born/grpc,perumaalgoog/grpc,murgatroid99/grpc,vjpai/grpc,mehrdada/grpc,zhimingxie/grpc,greasypizza/grpc,podsvirov/grpc,7anner/grpc,jboeuf/grpc,ejona86/grpc,wcevans/grpc,muxi/grpc,ncteisen/grpc,7anner/grpc,arkmaxim/grpc,grpc/grpc,yang-g/grpc,quizlet/grpc,yongni/grpc,perumaalgoog/grpc,7anner/grpc,jboeuf/grpc,bogdandrutu/grpc,a11r/grpc,PeterFaiman/ruby-grpc-minimal,kriswuollett/grpc,donnadionne/grpc,hstefan/grpc,kumaralokgithub/grpc,sreecha/grpc,MakMukhi/grpc,pszemus/grpc,ncteisen/grpc,yugui/grpc,grani/grpc,y-zeng/grpc,murgatroid99/grpc,deepaklukose/grpc,philcleveland/grpc,chrisdunelm/grpc,jboeuf/grpc,MakMukhi/grpc,Crevil/grpc,yang-g/grpc,tengyifei/grpc,vsco/grpc,sreecha/grpc,sreecha/grpc,dklempner/grpc,matt-kwong/grpc,dklempner/grpc,a11r/grpc,soltanmm/grpc,ctiller/grpc,leifurhauks/grpc,arkmaxim/grpc,ctiller/grpc,zhimingxie/grpc,grpc/grpc,dgquintas/grpc,a-veitch/grpc,vjpai/grpc,dgquintas/grpc,dklempner/grpc,donnadionne/grpc,kpayson64/grpc,ipylypiv/grpc,dklempner/grpc,thinkerou/grpc,MakMukhi/grpc,fuchsia-mirror/third_party-grpc,muxi/grpc,chrisdunelm/grpc,yang-g/grpc,philcleveland/grpc,matt-kwong/grpc,wcevans/grpc,chrisdunelm/grpc,baylabs/grpc,daniel-j-born/grpc,ctiller/grpc,pszemus/grpc,ipylypiv/grpc,ctiller/grpc,a-veitch/grpc,ejona86/grpc,greasypizza/grpc,royalharsh/grpc,yongni/grpc,pszemus/grpc,dgquintas/grpc,bogdandrutu/grpc,Crevil/grpc,royalharsh/grpc,perumaalgoog/grpc,quizlet/grpc,andrewpollock/grpc,bogdandrutu/grpc,malexzx/grpc,msmania/grpc,dgquintas/grpc,fuchsia-mirror/third_party-grpc,a11r/grpc,ppietrasa/grpc,a-veitch/grpc,philcleveland/grpc,grpc/grpc,Crevil/grpc,Vizerai/grpc,royalharsh/grpc,stanley-cheung/grpc,tengyifei/grpc,muxi/grpc,kpayson64/grpc,royalharsh/grpc,vjpai/grpc,apolcyn/grpc,simonkuang/grpc,a-veitch/grpc,ctiller/grpc,murgatroid99/grpc,tengyifei/grpc,nicolasnoble/grpc,andrewpollock/grpc,nicolasnoble/grpc,yugui/grpc,kpayson64/grpc,y-zeng/grpc,soltanmm-google/grpc,Vizerai/grpc,ejona86/grpc,zhimingxie/grpc,daniel-j-born/grpc,pszemus/grpc,kriswuollett/grpc,ncteisen/grpc,soltanmm/grpc,rjshade/grpc,pszemus/grpc,infinit/grpc,carl-mastrangelo/grpc,carl-mastrangelo/grpc,arkmaxim/grpc,kumaralokgithub/grpc,stanley-cheung/grpc,ppietrasa/grpc,firebase/grpc,ejona86/grpc,jcanizales/grpc,ncteisen/grpc,makdharma/grpc,donnadionne/grpc,pszemus/grpc,donnadionne/grpc,pszemus/grpc,kpayson64/grpc,vjpai/grpc,y-zeng/grpc,fuchsia-mirror/third_party-grpc,thunderboltsid/grpc,thinkerou/grpc,jboeuf/grpc,jcanizales/grpc,donnadionne/grpc,vjpai/grpc,bogdandrutu/grpc,mehrdada/grpc,thinkerou/grpc,podsvirov/grpc,deepaklukose/grpc,kumaralokgithub/grpc,simonkuang/grpc,jcanizales/grpc,soltanmm-google/grpc,kumaralokgithub/grpc,mehrdada/grpc,andrewpollock/grpc,adelez/grpc,7anner/grpc,yugui/grpc,dklempner/grpc,LuminateWireless/grpc,rjshade/grpc,kskalski/grpc,firebase/grpc,PeterFaiman/ruby-grpc-minimal,dgquintas/grpc,leifurhauks/grpc,vsco/grpc,apolcyn/grpc,makdharma/grpc,jboeuf/grpc,grani/grpc,tengyifei/grpc,zhimingxie/grpc,thinkerou/grpc,ipylypiv/grpc,pmarks-net/grpc,vsco/grpc,Vizerai/grpc,stanley-cheung/grpc,kumaralokgithub/grpc,stanley-cheung/grpc,infinit/grpc,jtattermusch/grpc,yugui/grpc,kpayson64/grpc,donnadionne/grpc,mehrdada/grpc,ncteisen/grpc,philcleveland/grpc,infinit/grpc,andrewpollock/grpc,daniel-j-born/grpc,soltanmm/grpc,MakMukhi/grpc,nicolasnoble/grpc,grani/grpc,kpayson64/grpc,carl-mastrangelo/grpc,kumaralokgithub/grpc,Vizerai/grpc,a11r/grpc,kriswuollett/grpc,arkmaxim/grpc,andrewpollock/grpc,chrisdunelm/grpc,ctiller/grpc,vsco/grpc,malexzx/grpc,muxi/grpc,grpc/grpc,y-zeng/grpc,a11r/grpc,soltanmm-google/grpc,carl-mastrangelo/grpc,soltanmm/grpc,kriswuollett/grpc,Vizerai/grpc,pmarks-net/grpc,ejona86/grpc,grani/grpc,PeterFaiman/ruby-grpc-minimal,vsco/grpc,ctiller/grpc,yang-g/grpc,perumaalgoog/grpc,fuchsia-mirror/third_party-grpc
ef4b8cf7d28021cd8e05948ca388ef24e71348bc
src/io/tools/compressor_test.cpp
src/io/tools/compressor_test.cpp
/** * @file compressor_test.cpp * @author Chase Geigle */ #include <array> #include <iostream> #include <fstream> #include "util/gzstream.h" using namespace meta; int main(int argc, char** argv) { if (argc < 3) { std::cerr << "Usage: " << argv[0] << " input output" << std::endl; return 1; } std::array<char, 1024> buffer; { std::ifstream file{argv[1], std::ios::in | std::ios::binary}; util::gzofstream output{argv[2]}; while (file) { file.read(&buffer[0], 1024); output.write(&buffer[0], file.gcount()); } } { util::gzifstream input{argv[2]}; std::ofstream output{std::string{argv[2]} + ".decompressed", std::ios::out | std::ios::binary}; std::string in; while (std::getline(input, in)) { output << in << "\n"; } } return 0; }
/** * @file compressor_test.cpp * @author Chase Geigle */ #include <array> #include <iostream> #include <fstream> #include "io/gzstream.h" using namespace meta; int main(int argc, char** argv) { if (argc < 3) { std::cerr << "Usage: " << argv[0] << " input output" << std::endl; return 1; } std::array<char, 1024> buffer; { std::ifstream file{argv[1], std::ios::in | std::ios::binary}; io::gzofstream output{argv[2]}; while (file) { file.read(&buffer[0], 1024); output.write(&buffer[0], file.gcount()); } } { io::gzifstream input{argv[2]}; std::ofstream output{std::string{argv[2]} + ".decompressed", std::ios::out | std::ios::binary}; while (input) { input.read(&buffer[0], 1024); output.write(&buffer[0], input.gcount()); } } return 0; }
Fix dummy compressor-test executable for util -> io move.
Fix dummy compressor-test executable for util -> io move.
C++
mit
esparza83/meta,esparza83/meta,husseinhazimeh/meta,esparza83/meta,saq7/MeTA,saq7/MeTA,husseinhazimeh/meta,husseinhazimeh/meta,gef756/meta,gef756/meta,gef756/meta,husseinhazimeh/meta,esparza83/meta,gef756/meta,esparza83/meta,husseinhazimeh/meta,saq7/MeTA,gef756/meta
38b4e57ff8f17230b265cbace8d218445d842c3d
src/ir/builders/MovIRBuilder.cpp
src/ir/builders/MovIRBuilder.cpp
#include <iostream> #include <sstream> #include <stdexcept> #include "MovIRBuilder.h" #include "smt2lib_utils.h" #include "SymbolicEngine.h" extern SymbolicEngine *symEngine; MovIRBuilder::MovIRBuilder(uint64_t address, const std::string &disassembly): BaseIRBuilder(address, disassembly) { } std::stringstream *MovIRBuilder::regImm(const ContextHandler &ctxH) const { std::stringstream expr; uint64_t reg = _operands[0].second; uint64_t imm = _operands[1].second; expr << smt2lib::bv(imm, ctxH.getRegisterSize(reg)); SymbolicElement *symElement = symEngine->newSymbolicElement(expr); symEngine->symbolicReg[reg] = symElement->getID(); return symElement->getExpression(); } std::stringstream *MovIRBuilder::regReg(const ContextHandler &ctxH) const { std::stringstream expr; uint64_t reg1 = _operands[0].second; uint64_t reg2 = _operands[1].second; if (symEngine->symbolicReg[ctxH.translateRegID(reg2)] != UNSET) expr << "#" << std::dec << symEngine->symbolicReg[ctxH.translateRegID(reg2)]; else expr << smt2lib::bv(ctxH.getRegisterValue(reg2), ctxH.getRegisterSize(reg1)); SymbolicElement *symElement = symEngine->newSymbolicElement(expr); symEngine->symbolicReg[ctxH.translateRegID(reg1)] = symElement->getID(); return symElement->getExpression(); } std::stringstream *MovIRBuilder::regMem(const ContextHandler &ctxH) const { return nullptr; } std::stringstream *MovIRBuilder::memImm(const ContextHandler &ctxH) const { return nullptr; } std::stringstream *MovIRBuilder::memReg(const ContextHandler &ctxH) const { return nullptr; } std::stringstream *MovIRBuilder::process(const ContextHandler &ctxH) const { checkSetup(); return templateMethod(ctxH, _operands, "MOV"); }
#include <iostream> #include <sstream> #include <stdexcept> #include "MovIRBuilder.h" #include "smt2lib_utils.h" #include "SymbolicEngine.h" extern SymbolicEngine *symEngine; MovIRBuilder::MovIRBuilder(uint64_t address, const std::string &disassembly): BaseIRBuilder(address, disassembly) { } std::stringstream *MovIRBuilder::regImm(const ContextHandler &ctxH) const { std::stringstream expr; uint64_t reg = _operands[0].second; uint64_t imm = _operands[1].second; expr << smt2lib::bv(imm, ctxH.getRegisterSize(reg)); SymbolicElement *symElement = symEngine->newSymbolicElement(expr); symEngine->symbolicReg[ctxH.translateRegID(reg)] = symElement->getID(); return symElement->getExpression(); } std::stringstream *MovIRBuilder::regReg(const ContextHandler &ctxH) const { std::stringstream expr; uint64_t reg1 = _operands[0].second; uint64_t reg2 = _operands[1].second; if (symEngine->symbolicReg[ctxH.translateRegID(reg2)] != UNSET) expr << "#" << std::dec << symEngine->symbolicReg[ctxH.translateRegID(reg2)]; else expr << smt2lib::bv(ctxH.getRegisterValue(reg2), ctxH.getRegisterSize(reg1)); SymbolicElement *symElement = symEngine->newSymbolicElement(expr); symEngine->symbolicReg[ctxH.translateRegID(reg1)] = symElement->getID(); return symElement->getExpression(); } std::stringstream *MovIRBuilder::regMem(const ContextHandler &ctxH) const { return nullptr; } std::stringstream *MovIRBuilder::memImm(const ContextHandler &ctxH) const { return nullptr; } std::stringstream *MovIRBuilder::memReg(const ContextHandler &ctxH) const { return nullptr; } std::stringstream *MovIRBuilder::process(const ContextHandler &ctxH) const { checkSetup(); return templateMethod(ctxH, _operands, "MOV"); }
Fix bug with the operand gethering information in IR - 2
Fix bug with the operand gethering information in IR - 2
C++
apache-2.0
JonathanSalwan/Triton,JonathanSalwan/Triton,JonathanSalwan/Triton,JonathanSalwan/Triton,JonathanSalwan/Triton
fb5fdd485d7bcc614d685d2a5d4f3d54d750c4f8
src/os/linux/Input.cpp
src/os/linux/Input.cpp
/* Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto 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 <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/XKBlib.h> #include "Keyboard.h" #include "OS.h" #include "Log.h" namespace crown { namespace os { //----------------------------------------------------------------------------- extern Display* display; extern Window window; static bool x11_detectable_autorepeat = false; static Cursor x11_hidden_cursor = None; //----------------------------------------------------------------------------- static void x11_create_hidden_cursor() { // Build hidden cursor Pixmap bm_no; XColor black, dummy; Colormap colormap; static char no_data[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; colormap = DefaultColormap(display, DefaultScreen(display)); XAllocNamedColor(display, colormap, "black", &black, &dummy); bm_no = XCreateBitmapFromData(display, window, no_data, 8, 8); x11_hidden_cursor = XCreatePixmapCursor(display, bm_no, bm_no, &black, &black, 0, 0); } //----------------------------------------------------------------------------- static Key x11_translate_key(int32_t x11_key) { if ((x11_key > 0x40 && x11_key < 0x5B) || (x11_key > 0x60 && x11_key < 0x7B) || (x11_key > 0x2F && x11_key < 0x3A)) { return (Key)x11_key; } switch (x11_key) { case XK_BackSpace: return KC_BACKSPACE; case XK_Tab: return KC_TAB; case XK_space: return KC_SPACE; case XK_Escape: return KC_ESCAPE; case XK_Return: return KC_ENTER; case XK_F1: return KC_F1; case XK_F2: return KC_F2; case XK_F3: return KC_F3; case XK_F4: return KC_F4; case XK_F5: return KC_F5; case XK_F6: return KC_F6; case XK_F7: return KC_F7; case XK_F8: return KC_F8; case XK_F9: return KC_F9; case XK_F10: return KC_F10; case XK_F11: return KC_F11; case XK_F12: return KC_F12; case XK_Home: return KC_HOME; case XK_Left: return KC_LEFT; case XK_Up: return KC_UP; case XK_Right: return KC_RIGHT; case XK_Down: return KC_DOWN; case XK_Page_Up: return KC_PAGE_UP; case XK_Page_Down: return KC_PAGE_DOWN; case XK_Shift_L: return KC_LSHIFT; case XK_Shift_R: return KC_RSHIFT; case XK_Control_L: return KC_LCONTROL; case XK_Control_R: return KC_RCONTROL; case XK_Caps_Lock: return KC_CAPS_LOCK; case XK_Alt_L: return KC_LALT; case XK_Alt_R: return KC_RALT; case XK_Super_L: return KC_LSUPER; case XK_Super_R: return KC_RSUPER; case XK_KP_0: return KC_KP_0; case XK_KP_1: return KC_KP_1; case XK_KP_2: return KC_KP_2; case XK_KP_3: return KC_KP_3; case XK_KP_4: return KC_KP_4; case XK_KP_5: return KC_KP_5; case XK_KP_6: return KC_KP_6; case XK_KP_7: return KC_KP_7; case XK_KP_8: return KC_KP_8; case XK_KP_9: return KC_KP_9; default: return KC_NOKEY; } } //----------------------------------------------------------------------------- void init_input() { // We want to track keyboard and mouse events XSelectInput(display, window, KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); // Check presence of detectable autorepeat Bool detectable; x11_detectable_autorepeat = (bool) XkbSetDetectableAutoRepeat(display, true, &detectable); x11_create_hidden_cursor(); } //----------------------------------------------------------------------------- void get_cursor_xy(int32_t& x, int32_t& y) { Window unused; int32_t pointer_x, pointer_y, dummy; uint32_t dummy2; XQueryPointer(display, window, &unused, &unused, &dummy, &dummy, &pointer_x, &pointer_y, &dummy2); x = pointer_x; y = pointer_y; } //----------------------------------------------------------------------------- void set_cursor_xy(int32_t x, int32_t y) { uint32_t width; uint32_t height; get_render_window_metrics(width, height); XWarpPointer(display, None, window, 0, 0, width, height, x, y); XFlush(display); } //----------------------------------------------------------------------------- void hide_cursor() { } //----------------------------------------------------------------------------- void show_cursor() { } //----------------------------------------------------------------------------- void event_loop() { XEvent event; OSEventParameter data_button[4] = {0, 0, 0, 0}; OSEventParameter data_key[4] = {0, 0, 0, 0}; while (XPending(display)) { XNextEvent(display, &event); switch (event.type) { // case ConfigureNotify: // { // _NotifyMetricsChange(event.xconfigure.x, event.xconfigure.y, // event.xconfigure.width, event.xconfigure.height); // break; // } case ButtonPress: case ButtonRelease: { OSEventType oset_type = event.type == ButtonPress ? OSET_BUTTON_PRESS : OSET_BUTTON_RELEASE; data_button[0].int_value = event.xbutton.x; data_button[1].int_value = event.xbutton.y; switch (event.xbutton.button) { case Button1: { data_button[2].int_value = 0; push_event(oset_type, data_button[0], data_button[1], data_button[2], data_button[3]); break; } case Button2: { data_button[3].int_value = 1; push_event(oset_type, data_button[0], data_button[1], data_button[2], data_button[3]); break; } case Button3: { data_button[3].int_value = 2; push_event(oset_type, data_button[0], data_button[1], data_button[2], data_button[3]); break; } } break; } case MotionNotify: { push_event(OSET_MOTION_NOTIFY, data_button[0], data_button[1], data_button[2], data_button[3]); break; } case KeyPress: case KeyRelease: { char string[4] = {0, 0, 0, 0}; int32_t len = -1; KeySym key; len = XLookupString(&event.xkey, string, 4, &key, NULL); Key kc = x11_translate_key(key); // // Check if any modifier key is pressed or released // if (kc == KC_LSHIFT || kc == KC_RSHIFT) // { // (event.type == KeyPress) ? mModifierMask |= MK_SHIFT : mModifierMask &= ~MK_SHIFT; // } // else if (kc == KC_LCONTROL || kc == KC_RCONTROL) // { // (event.type == KeyPress) ? mModifierMask |= MK_CTRL : mModifierMask &= ~MK_CTRL; // } // else if (kc == KC_LALT || kc == KC_RALT) // { // (event.type == KeyPress) ? mModifierMask |= MK_ALT : mModifierMask &= ~MK_ALT; // } OSEventType oset_type = event.type == KeyPress ? OSET_KEY_PRESS : OSET_KEY_RELEASE; data_key[0].int_value = ((int32_t)kc); push_event(oset_type, data_key[0], data_key[1], data_key[2], data_key[3]); // // Text input part // if (event.type == KeyPress && len > 0) // { // //crownEvent.event_type = ET_TEXT; // //crownEvent.text.type = TET_TEXT_INPUT; // strncpy(keyboardEvent.text, string, 4); // if (mListener) // { // mListener->TextInput(keyboardEvent); // } // } break; } case KeymapNotify: { XRefreshKeyboardMapping(&event.xmapping); break; } default: { break; } } } } } // namespace os } // namespace crown
/* Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto 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 <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/XKBlib.h> #include "Keyboard.h" #include "OS.h" #include "Log.h" namespace crown { namespace os { //----------------------------------------------------------------------------- extern Display* display; extern Window window; static bool x11_detectable_autorepeat = false; static Cursor x11_hidden_cursor = None; //----------------------------------------------------------------------------- static void x11_create_hidden_cursor() { // Build hidden cursor Pixmap bm_no; XColor black, dummy; Colormap colormap; static char no_data[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; colormap = DefaultColormap(display, DefaultScreen(display)); XAllocNamedColor(display, colormap, "black", &black, &dummy); bm_no = XCreateBitmapFromData(display, window, no_data, 8, 8); x11_hidden_cursor = XCreatePixmapCursor(display, bm_no, bm_no, &black, &black, 0, 0); } //----------------------------------------------------------------------------- static Key x11_translate_key(int32_t x11_key) { if ((x11_key > 0x40 && x11_key < 0x5B) || (x11_key > 0x60 && x11_key < 0x7B) || (x11_key > 0x2F && x11_key < 0x3A)) { return (Key)x11_key; } switch (x11_key) { case XK_BackSpace: return KC_BACKSPACE; case XK_Tab: return KC_TAB; case XK_space: return KC_SPACE; case XK_Escape: return KC_ESCAPE; case XK_Return: return KC_ENTER; case XK_F1: return KC_F1; case XK_F2: return KC_F2; case XK_F3: return KC_F3; case XK_F4: return KC_F4; case XK_F5: return KC_F5; case XK_F6: return KC_F6; case XK_F7: return KC_F7; case XK_F8: return KC_F8; case XK_F9: return KC_F9; case XK_F10: return KC_F10; case XK_F11: return KC_F11; case XK_F12: return KC_F12; case XK_Home: return KC_HOME; case XK_Left: return KC_LEFT; case XK_Up: return KC_UP; case XK_Right: return KC_RIGHT; case XK_Down: return KC_DOWN; case XK_Page_Up: return KC_PAGE_UP; case XK_Page_Down: return KC_PAGE_DOWN; case XK_Shift_L: return KC_LSHIFT; case XK_Shift_R: return KC_RSHIFT; case XK_Control_L: return KC_LCONTROL; case XK_Control_R: return KC_RCONTROL; case XK_Caps_Lock: return KC_CAPS_LOCK; case XK_Alt_L: return KC_LALT; case XK_Alt_R: return KC_RALT; case XK_Super_L: return KC_LSUPER; case XK_Super_R: return KC_RSUPER; case XK_KP_0: return KC_KP_0; case XK_KP_1: return KC_KP_1; case XK_KP_2: return KC_KP_2; case XK_KP_3: return KC_KP_3; case XK_KP_4: return KC_KP_4; case XK_KP_5: return KC_KP_5; case XK_KP_6: return KC_KP_6; case XK_KP_7: return KC_KP_7; case XK_KP_8: return KC_KP_8; case XK_KP_9: return KC_KP_9; default: return KC_NOKEY; } } //----------------------------------------------------------------------------- void init_input() { // We want to track keyboard and mouse events XSelectInput(display, window, KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); // Check presence of detectable autorepeat Bool detectable; x11_detectable_autorepeat = (bool) XkbSetDetectableAutoRepeat(display, true, &detectable); x11_create_hidden_cursor(); } //----------------------------------------------------------------------------- void get_cursor_xy(int32_t& x, int32_t& y) { Window unused; int32_t pointer_x, pointer_y, dummy; uint32_t dummy2; XQueryPointer(display, window, &unused, &unused, &dummy, &dummy, &pointer_x, &pointer_y, &dummy2); x = pointer_x; y = pointer_y; } //----------------------------------------------------------------------------- void set_cursor_xy(int32_t x, int32_t y) { uint32_t width; uint32_t height; get_render_window_metrics(width, height); XWarpPointer(display, None, window, 0, 0, width, height, x, y); XFlush(display); } //----------------------------------------------------------------------------- void hide_cursor() { XDefineCursor(display, window, x11_hidden_cursor); } //----------------------------------------------------------------------------- void show_cursor() { XDefineCursor(display, window, None); } //----------------------------------------------------------------------------- void event_loop() { XEvent event; OSEventParameter data_button[4] = {0, 0, 0, 0}; OSEventParameter data_key[4] = {0, 0, 0, 0}; while (XPending(display)) { XNextEvent(display, &event); switch (event.type) { // case ConfigureNotify: // { // _NotifyMetricsChange(event.xconfigure.x, event.xconfigure.y, // event.xconfigure.width, event.xconfigure.height); // break; // } case ButtonPress: case ButtonRelease: { OSEventType oset_type = event.type == ButtonPress ? OSET_BUTTON_PRESS : OSET_BUTTON_RELEASE; data_button[0].int_value = event.xbutton.x; data_button[1].int_value = event.xbutton.y; switch (event.xbutton.button) { case Button1: { data_button[2].int_value = 0; push_event(oset_type, data_button[0], data_button[1], data_button[2], data_button[3]); break; } case Button2: { data_button[3].int_value = 1; push_event(oset_type, data_button[0], data_button[1], data_button[2], data_button[3]); break; } case Button3: { data_button[3].int_value = 2; push_event(oset_type, data_button[0], data_button[1], data_button[2], data_button[3]); break; } } break; } case MotionNotify: { push_event(OSET_MOTION_NOTIFY, data_button[0], data_button[1], data_button[2], data_button[3]); break; } case KeyPress: case KeyRelease: { char string[4] = {0, 0, 0, 0}; int32_t len = -1; KeySym key; len = XLookupString(&event.xkey, string, 4, &key, NULL); Key kc = x11_translate_key(key); // // Check if any modifier key is pressed or released // if (kc == KC_LSHIFT || kc == KC_RSHIFT) // { // (event.type == KeyPress) ? mModifierMask |= MK_SHIFT : mModifierMask &= ~MK_SHIFT; // } // else if (kc == KC_LCONTROL || kc == KC_RCONTROL) // { // (event.type == KeyPress) ? mModifierMask |= MK_CTRL : mModifierMask &= ~MK_CTRL; // } // else if (kc == KC_LALT || kc == KC_RALT) // { // (event.type == KeyPress) ? mModifierMask |= MK_ALT : mModifierMask &= ~MK_ALT; // } OSEventType oset_type = event.type == KeyPress ? OSET_KEY_PRESS : OSET_KEY_RELEASE; data_key[0].int_value = ((int32_t)kc); push_event(oset_type, data_key[0], data_key[1], data_key[2], data_key[3]); // // Text input part // if (event.type == KeyPress && len > 0) // { // //crownEvent.event_type = ET_TEXT; // //crownEvent.text.type = TET_TEXT_INPUT; // strncpy(keyboardEvent.text, string, 4); // if (mListener) // { // mListener->TextInput(keyboardEvent); // } // } break; } case KeymapNotify: { XRefreshKeyboardMapping(&event.xmapping); break; } default: { break; } } } } } // namespace os } // namespace crown
Implement show/hide_cursor() under Linux
Implement show/hide_cursor() under Linux
C++
mit
galek/crown,dbartolini/crown,dbartolini/crown,dbartolini/crown,taylor001/crown,mikymod/crown,galek/crown,taylor001/crown,galek/crown,taylor001/crown,taylor001/crown,mikymod/crown,dbartolini/crown,mikymod/crown,mikymod/crown,galek/crown
be460364e17817db978e25366088a4a43515638c
src/libmv/multiview/affine_2d.cc
src/libmv/multiview/affine_2d.cc
// Copyright (c) 2009 libmv authors. // // 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 "libmv/multiview/affine_2d.h" #include <iostream> namespace libmv { // Parametrization // cos -sin tx // sin cos ty // 0 0 1 // It give the following system A x = B : // | Xa -Ya 0 1 | | sin | | Xb | // | Xa Ya 1 0 | | cos | | Yb | // | tx | = // | ty | // Scale can be estimated if the angle is known. Because x(0) = s * sin(angle). bool Affine2D_FromCorrespondencesLinear(const Mat &x1, const Mat &x2, Mat3 *M) { assert(2 == x1.rows()); assert(2 <= x1.cols()); assert(x1.rows() == x2.rows()); assert(x1.cols() == x2.cols()); const int n = x1.cols(); Mat A = Mat::Zero(2*n, 4); Mat b = Mat::Zero(2*n, 1); for (int i = 0; i < n; ++i) { const int j= i * 2; A(j,0) = -x1(1,i); A(j,1) = x1(0,i); A(j,2) = 1.0; A(j,3) = 0.0; A(j+1,0) = x1(0,i); A(j+1,1) = x1(1,i); A(j+1,2) = 0.0; A(j+1,3) = 1.0; b(j,0) = x2(0,i); b(j+1,0) = x2(1,i); } // Solve Ax=B Vec x; A.lu().solve(b, &x); // Configure output matrix : (*M)<<x(1),x(0),x(2), // cos sin tx -x(0), x(1),x(3),// sin cos ty 0.0, 0.0, 1.0; return true; } }
// Copyright (c) 2009 libmv authors. // // 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 "libmv/multiview/affine_2d.h" #include <iostream> namespace libmv { // Parametrization // cos -sin tx // sin cos ty // 0 0 1 // It give the following system A x = B : // | Xa -Ya 0 1 | | sin | | Xb | // | Xa Ya 1 0 | | cos | | Yb | // | tx | = // | ty | // Scale can be estimated if the angle is known. Because x(0) = s * sin(angle). bool Affine2D_FromCorrespondencesLinear(const Mat &x1, const Mat &x2, Mat3 *M) { assert(2 == x1.rows()); assert(2 <= x1.cols()); assert(x1.rows() == x2.rows()); assert(x1.cols() == x2.cols()); const int n = x1.cols(); Mat A = Mat::Zero(2*n, 4); Mat b = Mat::Zero(2*n, 1); for (int i = 0; i < n; ++i) { const int j= i * 2; A(j,0) = -x1(1,i); A(j,1) = x1(0,i); A(j,2) = 1.0; A(j,3) = 0.0; A(j+1,0) = x1(0,i); A(j+1,1) = x1(1,i); A(j+1,2) = 0.0; A(j+1,3) = 1.0; b(j,0) = x2(0,i); b(j+1,0) = x2(1,i); } // Solve Ax=B Vec x; A.lu().solve(b, &x); // Configure output matrix : (*M)<<x(1), x(0), x(2), // cos sin tx -x(0), x(1), x(3), // sin cos ty 0.0, 0.0, 1.0; return true; } }
Fix alignement.
Fix alignement.
C++
mit
manjunathnarayana/libmv,hjm168168/libmv,Ashwinning/libmv,sanyaade-g2g-repos/libmv,Shinohara-Takayuki/libmv,manjunathnarayana/libmv,jackyspeed/libmv,KangKyungSoo/libmv,Ashwinning/libmv,pombreda/libmv,jackyspeed/libmv,Shinohara-Takayuki/libmv,leoujz/libmv,sanyaade-g2g-repos/libmv,KangKyungSoo/libmv,manjunathnarayana/libmv,guivi01/libmv,tanmengwen/libmv,Ashwinning/libmv,tanmengwen/libmv,pombreda/libmv,tanmengwen/libmv,leoujz/libmv,pombreda/libmv,KangKyungSoo/libmv,manjunathnarayana/libmv,leoujz/libmv,Danath/libmv,sanyaade-g2g-repos/libmv,jackyspeed/libmv,guivi01/libmv,Danath/libmv,hjm168168/libmv,sanyaade-g2g-repos/libmv,Shinohara-Takayuki/libmv,hjm168168/libmv,jackyspeed/libmv,guivi01/libmv,leoujz/libmv,guivi01/libmv,Danath/libmv,KangKyungSoo/libmv,Danath/libmv,tanmengwen/libmv,pombreda/libmv,hjm168168/libmv,Ashwinning/libmv,Shinohara-Takayuki/libmv
9bc60527909825f01f72d31f5d580df8fdb482e4
src/platform/socket.cc
src/platform/socket.cc
// Copyright 2013 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "platform/socket.h" #if V8_OS_POSIX #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #endif #include <cerrno> #include "checks.h" #include "once.h" namespace v8 { namespace internal { #if V8_OS_WIN static V8_DECLARE_ONCE(initialize_winsock) = V8_ONCE_INIT; static void InitializeWinsock() { WSADATA wsa_data; int result = WSAStartup(MAKEWORD(1, 0), &wsa_data); CHECK_EQ(0, result); } #endif // V8_OS_WIN Socket::Socket() { #if V8_OS_WIN // Be sure to initialize the WinSock DLL first. CallOnce(&initialize_winsock, &InitializeWinsock); #endif // V8_OS_WIN // Create the native socket handle. native_handle_ = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); } bool Socket::Bind(int port) { ASSERT_GE(port, 0); ASSERT_LT(port, 65536); if (!IsValid()) return false; struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); sin.sin_port = htons(static_cast<uint16_t>(port)); int result = ::bind( native_handle_, reinterpret_cast<struct sockaddr*>(&sin), sizeof(sin)); return result == 0; } bool Socket::Listen(int backlog) { if (!IsValid()) return false; int result = ::listen(native_handle_, backlog); return result == 0; } Socket* Socket::Accept() { if (!IsValid()) return NULL; while (true) { NativeHandle native_handle = ::accept(native_handle_, NULL, NULL); if (native_handle == kInvalidNativeHandle) { #if V8_OS_POSIX if (errno == EINTR) continue; // Retry after signal. #endif return NULL; } return new Socket(native_handle); } } bool Socket::Connect(const char* host, const char* port) { ASSERT_NE(NULL, host); ASSERT_NE(NULL, port); if (!IsValid()) return false; // Lookup host and port. struct addrinfo* info = NULL; struct addrinfo hint; memset(&hint, 0, sizeof(hint)); hint.ai_family = AF_INET; hint.ai_socktype = SOCK_STREAM; hint.ai_protocol = IPPROTO_TCP; int result = ::getaddrinfo(host, port, &hint, &info); if (result != 0) { return false; } // Connect to the host on the given port. for (struct addrinfo* ai = info; ai != NULL; ai = ai->ai_next) { // Try to connect using this addr info. while (true) { result = ::connect(native_handle_, ai->ai_addr, ai->ai_addrlen); if (result == 0) { freeaddrinfo(info); return true; } #if V8_OS_POSIX if (errno == EINTR) continue; // Retry after signal. #endif break; } } freeaddrinfo(info); return false; } bool Socket::Shutdown() { if (!IsValid()) return false; // Shutdown socket for both read and write. #if V8_OS_POSIX int result = ::shutdown(native_handle_, SHUT_RDWR); ::close(native_handle_); #elif V8_OS_WIN int result = ::shutdown(native_handle_, SD_BOTH); ::closesocket(native_handle_); #endif native_handle_ = kInvalidNativeHandle; return result == 0; } int Socket::Send(const char* buffer, int length) { ASSERT(length <= 0 || buffer != NULL); if (!IsValid()) return 0; int offset = 0; while (offset < length) { int result = ::send(native_handle_, buffer + offset, length - offset, 0); if (result == 0) { break; } else if (result > 0) { ASSERT(result <= length - offset); offset += result; } else { #if V8_OS_POSIX if (errno == EINTR) continue; // Retry after signal. #endif return 0; } } return offset; } int Socket::Receive(char* buffer, int length) { if (!IsValid()) return 0; if (length <= 0) return 0; ASSERT_NE(NULL, buffer); while (true) { int result = ::recv(native_handle_, buffer, length, 0); if (result < 0) { #if V8_OS_POSIX if (errno == EINTR) continue; // Retry after signal. #endif return 0; } return result; } } bool Socket::SetReuseAddress(bool reuse_address) { if (!IsValid()) return 0; int v = reuse_address ? 1 : 0; int result = ::setsockopt(native_handle_, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&v), sizeof(v)); return result == 0; } // static int Socket::GetLastError() { #if V8_OS_POSIX return errno; #elif V8_OS_WIN // Be sure to initialize the WinSock DLL first. CallOnce(&initialize_winsock, &InitializeWinsock); // Now we can safely perform WSA calls. return ::WSAGetLastError(); #endif } } } // namespace v8::internal
// Copyright 2013 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "platform/socket.h" #if V8_OS_POSIX #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #endif #include <cerrno> #include "checks.h" #include "once.h" namespace v8 { namespace internal { #if V8_OS_WIN static V8_DECLARE_ONCE(initialize_winsock) = V8_ONCE_INIT; static void InitializeWinsock() { WSADATA wsa_data; int result = WSAStartup(MAKEWORD(1, 0), &wsa_data); CHECK_EQ(0, result); } #endif // V8_OS_WIN Socket::Socket() { #if V8_OS_WIN // Be sure to initialize the WinSock DLL first. CallOnce(&initialize_winsock, &InitializeWinsock); #endif // V8_OS_WIN // Create the native socket handle. native_handle_ = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); } bool Socket::Bind(int port) { ASSERT_GE(port, 0); ASSERT_LT(port, 65536); if (!IsValid()) return false; struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); sin.sin_port = htons(static_cast<uint16_t>(port)); int result = ::bind( native_handle_, reinterpret_cast<struct sockaddr*>(&sin), sizeof(sin)); return result == 0; } bool Socket::Listen(int backlog) { if (!IsValid()) return false; int result = ::listen(native_handle_, backlog); return result == 0; } Socket* Socket::Accept() { if (!IsValid()) return NULL; while (true) { NativeHandle native_handle = ::accept(native_handle_, NULL, NULL); if (native_handle == kInvalidNativeHandle) { #if V8_OS_POSIX if (errno == EINTR) continue; // Retry after signal. #endif return NULL; } return new Socket(native_handle); } } bool Socket::Connect(const char* host, const char* port) { ASSERT_NE(NULL, host); ASSERT_NE(NULL, port); if (!IsValid()) return false; // Lookup host and port. struct addrinfo* info = NULL; struct addrinfo hint; memset(&hint, 0, sizeof(hint)); hint.ai_family = AF_INET; hint.ai_socktype = SOCK_STREAM; hint.ai_protocol = IPPROTO_TCP; int result = ::getaddrinfo(host, port, &hint, &info); if (result != 0) { return false; } // Connect to the host on the given port. for (struct addrinfo* ai = info; ai != NULL; ai = ai->ai_next) { // Try to connect using this addr info. while (true) { result = ::connect( native_handle_, ai->ai_addr, static_cast<int>(ai->ai_addrlen)); if (result == 0) { freeaddrinfo(info); return true; } #if V8_OS_POSIX if (errno == EINTR) continue; // Retry after signal. #endif break; } } freeaddrinfo(info); return false; } bool Socket::Shutdown() { if (!IsValid()) return false; // Shutdown socket for both read and write. #if V8_OS_POSIX int result = ::shutdown(native_handle_, SHUT_RDWR); ::close(native_handle_); #elif V8_OS_WIN int result = ::shutdown(native_handle_, SD_BOTH); ::closesocket(native_handle_); #endif native_handle_ = kInvalidNativeHandle; return result == 0; } int Socket::Send(const char* buffer, int length) { ASSERT(length <= 0 || buffer != NULL); if (!IsValid()) return 0; int offset = 0; while (offset < length) { int result = ::send(native_handle_, buffer + offset, length - offset, 0); if (result == 0) { break; } else if (result > 0) { ASSERT(result <= length - offset); offset += result; } else { #if V8_OS_POSIX if (errno == EINTR) continue; // Retry after signal. #endif return 0; } } return offset; } int Socket::Receive(char* buffer, int length) { if (!IsValid()) return 0; if (length <= 0) return 0; ASSERT_NE(NULL, buffer); while (true) { int result = ::recv(native_handle_, buffer, length, 0); if (result < 0) { #if V8_OS_POSIX if (errno == EINTR) continue; // Retry after signal. #endif return 0; } return result; } } bool Socket::SetReuseAddress(bool reuse_address) { if (!IsValid()) return 0; int v = reuse_address ? 1 : 0; int result = ::setsockopt(native_handle_, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&v), sizeof(v)); return result == 0; } // static int Socket::GetLastError() { #if V8_OS_POSIX return errno; #elif V8_OS_WIN // Be sure to initialize the WinSock DLL first. CallOnce(&initialize_winsock, &InitializeWinsock); // Now we can safely perform WSA calls. return ::WSAGetLastError(); #endif } } } // namespace v8::internal
Build fix for Win64 after r16521.
Build fix for Win64 after r16521. [email protected] Review URL: https://codereview.chromium.org/23850003 git-svn-id: b158db1e4b4ab85d4c9e510fdef4b1e8c614b15b@16524 ce2b1a6d-e550-0410-aec6-3dcde31c8c00
C++
mit
UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh,UniversalFuture/moosh
4284bee28c225a1e22b42e8f4a71246be7e6744a
src/llvm/LLVMDependenceGraph.cpp
src/llvm/LLVMDependenceGraph.cpp
/// XXX add licence // #ifdef HAVE_LLVM #ifndef ENABLE_CFG #error "Need CFG enabled for building LLVM Dependence Graph" #endif #include <utility> #include <unordered_map> #include <set> #include <llvm/IR/Module.h> #include <llvm/IR/Instruction.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/Value.h> #include <llvm/IR/CFG.h> #include <llvm/Support/raw_ostream.h> #include "LLVMDependenceGraph.h" using llvm::errs; using std::make_pair; namespace dg { LLVMNode **LLVMNode::findOperands() { using namespace llvm; const Value *val = getKey(); if (const AllocaInst *Inst = dyn_cast<AllocaInst>(val)) { operands = new LLVMNode *[1]; operands[0] = dg->getNode(val); operands_num = 1; } else if (const StoreInst *Inst = dyn_cast<StoreInst>(val)) { operands = new LLVMNode *[2]; operands[0] = dg->getNode(Inst->getPointerOperand()); operands[1] = dg->getNode(Inst->getValueOperand()); operands_num = 2; assert(operands[0] && "StoreInst pointer operand without node"); if (!operands[1]) { errs() << "WARN: StoreInst value operand without node: " << *Inst->getValueOperand() << "\n"; } } else if (const LoadInst *Inst = dyn_cast<LoadInst>(val)) { operands = new LLVMNode *[1]; operands[0] = dg->getNode(Inst->getPointerOperand()); operands_num = 1; } else if (const GetElementPtrInst *Inst = dyn_cast<GetElementPtrInst>(val)) { operands = new LLVMNode *[1]; operands[0] = dg->getNode(Inst->getPointerOperand()); operands_num = 1; } else if (const CallInst *Inst = dyn_cast<CallInst>(val)) { // we store the called function as a first operand // and all the arguments as the other operands operands_num = Inst->getNumArgOperands() + 1; operands = new LLVMNode *[operands_num]; operands[0] = dg->getNode(Inst->getCalledValue()); for (int i = 0; i < operands_num - 1; ++i) operands[i + 1] = dg->getNode(Inst->getArgOperand(i)); } else if (const ReturnInst *Inst = dyn_cast<ReturnInst>(val)) { operands = new LLVMNode *[1]; operands[0] = dg->getNode(Inst->getReturnValue()); operands_num = 1; } else if (const CastInst *Inst = dyn_cast<CastInst>(val)) { operands = new LLVMNode *[1]; operands[0] = dg->getNode(Inst->stripPointerCasts()); if (!operands[0]) errs() << "WARN: CastInst with unstrippable pointer cast" << *Inst << "\n"; operands_num = 1; } } /// ------------------------------------------------------------------ // -- LLVMDependenceGraph /// ------------------------------------------------------------------ LLVMDependenceGraph::~LLVMDependenceGraph() { // delete nodes for (auto I = begin(), E = end(); I != E; ++I) { LLVMNode *node = I->second; if (node) { for (auto subgraph : node->getSubgraphs()) { // graphs are referenced, once the refcount is 0 // the graph will be deleted // Because of recursive calls, graph can be its // own subgraph. In that case we're in the destructor // already, so do not delete it subgraph->unref(subgraph != this); } LLVMDGParameters *params = node->getParameters(); if (params) { for (auto par : *params) { delete par.second.in; delete par.second.out; } delete params; } if (!node->getBasicBlock() && !llvm::isa<llvm::Function>(*I->first)) errs() << "WARN: Value " << *I->first << "had no BB assigned\n"; delete node; } else { errs() << "WARN: Value " << *I->first << "had no node assigned\n"; } } } bool LLVMDependenceGraph::build(llvm::Module *m, llvm::Function *entry) { // get entry function if not given if (!entry) entry = m->getFunction("main"); if (!entry) { errs() << "No entry function found/given\n"; return false; } // build recursively DG from entry point build(entry); }; bool LLVMDependenceGraph::buildSubgraph(LLVMNode *node) { using namespace llvm; LLVMBBlock *BB; const Value *val = node->getValue(); const CallInst *CInst = dyn_cast<CallInst>(val); assert(CInst && "buildSubgraph called on non-CallInst"); Function *callFunc = CInst->getCalledFunction(); // if we don't have this subgraph constructed, construct it // else just add call edge LLVMDependenceGraph *&subgraph = constructedFunctions[callFunc]; if (!subgraph) { // since we have reference the the pointer in // constructedFunctions, we can assing to it subgraph = new LLVMDependenceGraph(); bool ret = subgraph->build(callFunc); // at least for now use just assert, if we'll // have a reason to handle such failures at some // point, we can change it assert(ret && "Building subgraph failed"); // we built the subgraph, so it has refcount = 1, // later in the code we call addSubgraph, which // increases the refcount to 2, but we need this // subgraph to has refcount 1, so unref it subgraph->unref(false /* deleteOnZero */); } BB = node->getBasicBlock(); assert(BB && "do not have BB; this is a bug, sir"); BB->addCallsite(node); // make the subgraph a subgraph of current node // addSubgraph will increase refcount of the graph node->addSubgraph(subgraph); node->addActualParameters(subgraph); } static bool is_func_defined(const llvm::CallInst *CInst) { llvm::Function *callFunc = CInst->getCalledFunction(); if (callFunc->size() == 0) { #if DEBUG_ENABLED llvm::errs() << "Skipping undefined function '" << callFunc->getName() << "'\n"; #endif return false; } return true; } void LLVMDependenceGraph::handleInstruction(const llvm::Value *val, LLVMNode *node) { using namespace llvm; if (const CallInst *CInst = dyn_cast<CallInst>(val)) { if (is_func_defined(CInst)) buildSubgraph(node); } } LLVMBBlock *LLVMDependenceGraph::build(const llvm::BasicBlock& llvmBB) { using namespace llvm; BasicBlock::const_iterator IT = llvmBB.begin(); const Value *val = &(*IT); LLVMNode *predNode = nullptr; LLVMNode *node = new LLVMNode(val); LLVMBBlock *BB = new LLVMBBlock(node); addNode(node); handleInstruction(val, node); ++IT; // shift to next instruction, we have the first one handled predNode = node; // iterate over the instruction and create node for every single // one of them + add CFG edges for (BasicBlock::const_iterator Inst = IT, EInst = llvmBB.end(); Inst != EInst; ++Inst) { val = &(*Inst); node = new LLVMNode(val); // add new node to this dependence graph addNode(node); // add successor to predcessor node if (predNode) predNode->setSuccessor(node); // set new predcessor node for next iteration predNode = node; // take instruction specific actions handleInstruction(val, node); } // check if this is the exit node of function const TerminatorInst *term = llvmBB.getTerminator(); if (!term) { errs() << "WARN: Basic block is not well formed\n" << llvmBB << "\n"; return BB; } // create one unified exit node from function and add control dependence // to it from every return instruction. We could use llvm pass that // would do it for us, but then we would lost the advantage of working // on dep. graph that is not for whole llvm const ReturnInst *ret = dyn_cast<ReturnInst>(term); if (ret) { LLVMNode *ext = getExit(); if (!ext) { // we need new llvm value, so that the nodes won't collide ReturnInst *phonyRet = ReturnInst::Create(ret->getContext()/*, ret->getReturnValue()*/); if (!phonyRet) { errs() << "ERR: Failed creating phony return value " << "for exit node\n"; // XXX later we could return somehow more mercifully abort(); } ext = new LLVMNode(phonyRet); addNode(ext); setExit(ext); LLVMBBlock *retBB = new LLVMBBlock(ext, ext); setExitBB(retBB); } // add control dependence from this (return) node // to EXIT node assert(node && "BUG, no node after we went through basic block"); node->addControlDependence(ext); BB->addSuccessor(getExitBB()); } // set last node BB->setLastNode(node); // sanity check if we have the first and the last node set assert(BB->getFirstNode() && "No first node in BB"); assert(BB->getLastNode() && "No last node in BB"); return BB; } bool LLVMDependenceGraph::build(llvm::Function *func) { using namespace llvm; assert(func && "Passed no func"); // do we have anything to process? if (func->size() == 0) return false; #if DEBUG_ENABLED llvm::errs() << "Building graph for '" << func->getName() << "'\n"; #endif // create entry node LLVMNode *entry = new LLVMNode(func); addNode(entry); setEntry(entry); constructedFunctions.insert(make_pair(func, this)); std::unordered_map<llvm::BasicBlock *, LLVMBBlock *> createdBlocks; createdBlocks.reserve(func->size()); // iterate over basic blocks for (llvm::BasicBlock& llvmBB : *func) { LLVMBBlock *BB = build(llvmBB); createdBlocks[&llvmBB] = BB; // first basic block is the entry BB if (!getEntryBB()) setEntryBB(BB); } // add CFG edges for (auto it : createdBlocks) { BasicBlock *llvmBB = it.first; LLVMBBlock *BB = it.second; for (succ_iterator S = succ_begin(llvmBB), SE = succ_end(llvmBB); S != SE; ++S) { LLVMBBlock *succ = createdBlocks[*S]; assert(succ && "Missing basic block"); BB->addSuccessor(succ); } } // check if we have everything assert(getEntry() && "Missing entry node"); assert(getExit() && "Missing exit node"); assert(getEntryBB() && "Missing entry BB"); assert(getExitBB() && "Missing exit BB"); // add CFG edge from entry point to the first instruction entry->addControlDependence(getEntryBB()->getFirstNode()); addFormalParameters(); return true; } void LLVMNode::addActualParameters(LLVMDependenceGraph *funcGraph) { using namespace llvm; const CallInst *CInst = dyn_cast<CallInst>(key); assert(CInst && "addActualParameters called on non-CallInst"); // do not add redundant nodes const Function *func = CInst->getCalledFunction(); if (func->arg_size() == 0) return; LLVMDGParameters *params = new LLVMDGParameters(); LLVMDGParameters *old = addParameters(params); assert(old == nullptr && "Replaced parameters"); LLVMNode *in, *out; for (const Value *val : CInst->arg_operands()) { in = new LLVMNode(val); out = new LLVMNode(val); params->add(val, in, out); // add control edges from this node to parameters addControlDependence(in); addControlDependence(out); // add parameter edges -- these are just normal dependece edges //LLVMNode *fp = (*funcGraph)[val]; //assert(fp && "Do not have formal parametr"); //nn->addDataDependence(fp); } } void LLVMDependenceGraph::addFormalParameters() { using namespace llvm; LLVMNode *entryNode = getEntry(); assert(entryNode && "No entry node when adding formal parameters"); const Function *func = dyn_cast<Function>(entryNode->getValue()); assert(func && "entry node value is not a function"); //assert(func->arg_size() != 0 && "This function is undefined?"); if (func->arg_size() == 0) return; LLVMDGParameters *params = new LLVMDGParameters(); entryNode->addParameters(params); LLVMNode *in, *out; for (auto I = func->arg_begin(), E = func->arg_end(); I != E; ++I) { const Value *val = (&*I); in = new LLVMNode(val); out = new LLVMNode(val); params->add(val, in, out); // add control edges entryNode->addControlDependence(in); entryNode->addControlDependence(out); } } } // namespace dg #endif /* HAVE_LLVM */
/// XXX add licence // #ifdef HAVE_LLVM #ifndef ENABLE_CFG #error "Need CFG enabled for building LLVM Dependence Graph" #endif #include <utility> #include <unordered_map> #include <set> #include <llvm/IR/Module.h> #include <llvm/IR/Instruction.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/Value.h> #include <llvm/IR/CFG.h> #include <llvm/Support/raw_ostream.h> #include "LLVMDependenceGraph.h" using llvm::errs; using std::make_pair; namespace dg { LLVMNode **LLVMNode::findOperands() { using namespace llvm; const Value *val = getKey(); if (const AllocaInst *Inst = dyn_cast<AllocaInst>(val)) { operands = new LLVMNode *[1]; operands[0] = dg->getNode(val); operands_num = 1; } else if (const StoreInst *Inst = dyn_cast<StoreInst>(val)) { operands = new LLVMNode *[2]; operands[0] = dg->getNode(Inst->getPointerOperand()); operands[1] = dg->getNode(Inst->getValueOperand()); operands_num = 2; assert(operands[0] && "StoreInst pointer operand without node"); if (!operands[1]) { errs() << "WARN: StoreInst value operand without node: " << *Inst->getValueOperand() << "\n"; } } else if (const LoadInst *Inst = dyn_cast<LoadInst>(val)) { operands = new LLVMNode *[1]; operands[0] = dg->getNode(Inst->getPointerOperand()); operands_num = 1; } else if (const GetElementPtrInst *Inst = dyn_cast<GetElementPtrInst>(val)) { operands = new LLVMNode *[1]; operands[0] = dg->getNode(Inst->getPointerOperand()); operands_num = 1; } else if (const CallInst *Inst = dyn_cast<CallInst>(val)) { // we store the called function as a first operand // and all the arguments as the other operands operands_num = Inst->getNumArgOperands() + 1; operands = new LLVMNode *[operands_num]; operands[0] = dg->getNode(Inst->getCalledValue()); for (int i = 0; i < operands_num - 1; ++i) operands[i + 1] = dg->getNode(Inst->getArgOperand(i)); } else if (const ReturnInst *Inst = dyn_cast<ReturnInst>(val)) { operands = new LLVMNode *[1]; operands[0] = dg->getNode(Inst->getReturnValue()); operands_num = 1; } else if (const CastInst *Inst = dyn_cast<CastInst>(val)) { operands = new LLVMNode *[1]; operands[0] = dg->getNode(Inst->stripPointerCasts()); if (!operands[0]) errs() << "WARN: CastInst with unstrippable pointer cast" << *Inst << "\n"; operands_num = 1; } } /// ------------------------------------------------------------------ // -- LLVMDependenceGraph /// ------------------------------------------------------------------ LLVMDependenceGraph::~LLVMDependenceGraph() { // delete nodes for (auto I = begin(), E = end(); I != E; ++I) { LLVMNode *node = I->second; if (node) { for (auto subgraph : node->getSubgraphs()) { // graphs are referenced, once the refcount is 0 // the graph will be deleted // Because of recursive calls, graph can be its // own subgraph. In that case we're in the destructor // already, so do not delete it subgraph->unref(subgraph != this); } LLVMDGParameters *params = node->getParameters(); if (params) { for (auto par : *params) { delete par.second.in; delete par.second.out; } delete params; } if (!node->getBasicBlock() && !llvm::isa<llvm::Function>(*I->first)) errs() << "WARN: Value " << *I->first << "had no BB assigned\n"; delete node; } else { errs() << "WARN: Value " << *I->first << "had no node assigned\n"; } } } bool LLVMDependenceGraph::build(llvm::Module *m, llvm::Function *entry) { // get entry function if not given if (!entry) entry = m->getFunction("main"); if (!entry) { errs() << "No entry function found/given\n"; return false; } // build recursively DG from entry point build(entry); }; bool LLVMDependenceGraph::buildSubgraph(LLVMNode *node) { using namespace llvm; LLVMBBlock *BB; const Value *val = node->getValue(); const CallInst *CInst = dyn_cast<CallInst>(val); assert(CInst && "buildSubgraph called on non-CallInst"); Function *callFunc = CInst->getCalledFunction(); // if we don't have this subgraph constructed, construct it // else just add call edge LLVMDependenceGraph *&subgraph = constructedFunctions[callFunc]; if (!subgraph) { // since we have reference the the pointer in // constructedFunctions, we can assing to it subgraph = new LLVMDependenceGraph(); bool ret = subgraph->build(callFunc); // at least for now use just assert, if we'll // have a reason to handle such failures at some // point, we can change it assert(ret && "Building subgraph failed"); // we built the subgraph, so it has refcount = 1, // later in the code we call addSubgraph, which // increases the refcount to 2, but we need this // subgraph to has refcount 1, so unref it subgraph->unref(false /* deleteOnZero */); } BB = node->getBasicBlock(); assert(BB && "do not have BB; this is a bug, sir"); BB->addCallsite(node); // make the subgraph a subgraph of current node // addSubgraph will increase refcount of the graph node->addSubgraph(subgraph); node->addActualParameters(subgraph); } static bool is_func_defined(const llvm::CallInst *CInst) { llvm::Function *callFunc = CInst->getCalledFunction(); if (callFunc->size() == 0) { #if DEBUG_ENABLED llvm::errs() << "Skipping undefined function '" << callFunc->getName() << "'\n"; #endif return false; } return true; } void LLVMDependenceGraph::handleInstruction(const llvm::Value *val, LLVMNode *node) { using namespace llvm; if (const CallInst *CInst = dyn_cast<CallInst>(val)) { if (is_func_defined(CInst)) buildSubgraph(node); } } LLVMBBlock *LLVMDependenceGraph::build(const llvm::BasicBlock& llvmBB) { using namespace llvm; BasicBlock::const_iterator IT = llvmBB.begin(); const Value *val = &(*IT); LLVMNode *predNode = nullptr; LLVMNode *node = new LLVMNode(val); LLVMBBlock *BB = new LLVMBBlock(node); addNode(node); handleInstruction(val, node); ++IT; // shift to next instruction, we have the first one handled predNode = node; // iterate over the instruction and create node for every single // one of them + add CFG edges for (BasicBlock::const_iterator Inst = IT, EInst = llvmBB.end(); Inst != EInst; ++Inst) { val = &(*Inst); node = new LLVMNode(val); // add new node to this dependence graph addNode(node); // add successor to predcessor node if (predNode) predNode->setSuccessor(node); // set new predcessor node for next iteration predNode = node; // take instruction specific actions handleInstruction(val, node); } // check if this is the exit node of function const TerminatorInst *term = llvmBB.getTerminator(); if (!term) { errs() << "WARN: Basic block is not well formed\n" << llvmBB << "\n"; return BB; } // create one unified exit node from function and add control dependence // to it from every return instruction. We could use llvm pass that // would do it for us, but then we would lost the advantage of working // on dep. graph that is not for whole llvm const ReturnInst *ret = dyn_cast<ReturnInst>(term); if (ret) { LLVMNode *ext = getExit(); if (!ext) { // we need new llvm value, so that the nodes won't collide ReturnInst *phonyRet = ReturnInst::Create(ret->getContext()/*, ret->getReturnValue()*/); if (!phonyRet) { errs() << "ERR: Failed creating phony return value " << "for exit node\n"; // XXX later we could return somehow more mercifully abort(); } ext = new LLVMNode(phonyRet); addNode(ext); setExit(ext); LLVMBBlock *retBB = new LLVMBBlock(ext, ext); setExitBB(retBB); } // add control dependence from this (return) node // to EXIT node assert(node && "BUG, no node after we went through basic block"); node->addControlDependence(ext); BB->addSuccessor(getExitBB()); } // set last node BB->setLastNode(node); // sanity check if we have the first and the last node set assert(BB->getFirstNode() && "No first node in BB"); assert(BB->getLastNode() && "No last node in BB"); return BB; } bool LLVMDependenceGraph::build(llvm::Function *func) { using namespace llvm; assert(func && "Passed no func"); // do we have anything to process? if (func->size() == 0) return false; #if DEBUG_ENABLED llvm::errs() << "Building graph for '" << func->getName() << "'\n"; #endif // create entry node LLVMNode *entry = new LLVMNode(func); addNode(entry); setEntry(entry); constructedFunctions.insert(make_pair(func, this)); std::unordered_map<llvm::BasicBlock *, LLVMBBlock *> createdBlocks; createdBlocks.reserve(func->size()); // iterate over basic blocks for (llvm::BasicBlock& llvmBB : *func) { LLVMBBlock *BB = build(llvmBB); createdBlocks[&llvmBB] = BB; // first basic block is the entry BB if (!getEntryBB()) setEntryBB(BB); } // add CFG edges for (auto it : createdBlocks) { BasicBlock *llvmBB = it.first; LLVMBBlock *BB = it.second; for (succ_iterator S = succ_begin(llvmBB), SE = succ_end(llvmBB); S != SE; ++S) { LLVMBBlock *succ = createdBlocks[*S]; assert(succ && "Missing basic block"); BB->addSuccessor(succ); } } // check if we have everything assert(getEntry() && "Missing entry node"); assert(getExit() && "Missing exit node"); assert(getEntryBB() && "Missing entry BB"); assert(getExitBB() && "Missing exit BB"); // add CFG edge from entry point to the first instruction entry->addControlDependence(getEntryBB()->getFirstNode()); addFormalParameters(); return true; } void LLVMNode::addActualParameters(LLVMDependenceGraph *funcGraph) { using namespace llvm; const CallInst *CInst = dyn_cast<CallInst>(key); assert(CInst && "addActualParameters called on non-CallInst"); // do not add redundant nodes const Function *func = CInst->getCalledFunction(); if (func->arg_size() == 0) return; LLVMDGParameters *params = new LLVMDGParameters(); LLVMDGParameters *old = addParameters(params); assert(old == nullptr && "Replaced parameters"); LLVMNode *in, *out; for (const Value *val : CInst->arg_operands()) { in = new LLVMNode(val); out = new LLVMNode(val); params->add(val, in, out); // add control edges from this node to parameters addControlDependence(in); addControlDependence(out); // add parameter edges -- these are just normal dependece edges //LLVMNode *fp = (*funcGraph)[val]; //assert(fp && "Do not have formal parametr"); //nn->addDataDependence(fp); } } void LLVMDependenceGraph::addFormalParameters() { using namespace llvm; LLVMNode *entryNode = getEntry(); assert(entryNode && "No entry node when adding formal parameters"); const Function *func = dyn_cast<Function>(entryNode->getValue()); assert(func && "entry node value is not a function"); //assert(func->arg_size() != 0 && "This function is undefined?"); if (func->arg_size() == 0) return; LLVMDGParameters *params = new LLVMDGParameters(); setParameters(params); LLVMNode *in, *out; for (auto I = func->arg_begin(), E = func->arg_end(); I != E; ++I) { const Value *val = (&*I); in = new LLVMNode(val); out = new LLVMNode(val); params->add(val, in, out); // add control edges entryNode->addControlDependence(in); entryNode->addControlDependence(out); } } } // namespace dg #endif /* HAVE_LLVM */
set formal parameters to dg not to entry node
llvmdg: set formal parameters to dg not to entry node We changed the behaviour in some of previous commits Signed-off-by: Marek Chalupa <[email protected]>
C++
mit
mchalupa/dg,mchalupa/dg,mchalupa/dg,mchalupa/dg
340d0b08bf92597ad68de837100584c90914ede7
src/qt/aboutdialog.cpp
src/qt/aboutdialog.cpp
#include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" // Copyright year (2009-this) // Todo: update this when changing our copyright comments in the source const int ABOUTDIALOG_COPYRIGHT_YEAR = 2013; AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers") + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("2011-%1 The Litecoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR) + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("%1 The Anoncoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR)); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); }
#include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" // Copyright year (2009-this) // Todo: update this when changing our copyright comments in the source const int ABOUTDIALOG_COPYRIGHT_YEAR = 2017; AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers") + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("2011-%1 The Litecoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR) + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("2013-%1 The Anoncoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR) + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("2015-%1 The i2pd developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR) + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("%1 The Gostcoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR)); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); }
correct About dialog
correct About dialog
C++
mit
GOSTSec/gostcoin,hypnosis-i2p/gostcoin,GOSTSec/gostcoin,hypnosis-i2p/gostcoin,GOSTSec/gostcoin,hypnosis-i2p/gostcoin,hypnosis-i2p/gostcoin,GOSTSec/gostcoin,hypnosis-i2p/gostcoin,GOSTSec/gostcoin
c1685b3a5052de377735f69e53e50741dbe5b52a
tools/llvm-link/llvm-link.cpp
tools/llvm-link/llvm-link.cpp
//===- llvm-link.cpp - Low-level LLVM linker ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility may be invoked in the following manner: // llvm-link a.bc b.bc c.bc -o x.bc // //===----------------------------------------------------------------------===// #include "llvm/Linker.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/SystemUtils.h" #include "llvm/Support/ToolOutputFile.h" #include <memory> using namespace llvm; static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, cl::desc("<input bitcode files>")); static cl::opt<std::string> OutputFilename("o", cl::desc("Override output filename"), cl::init("-"), cl::value_desc("filename")); static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals")); static cl::opt<bool> OutputAssembly("S", cl::desc("Write output as LLVM assembly"), cl::Hidden); static cl::opt<bool> Verbose("v", cl::desc("Print information about actions taken")); static cl::opt<bool> DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden); // LoadFile - Read the specified bitcode file in and return it. This routine // searches the link path for the specified file to try to find it... // static inline Module *LoadFile(const char *argv0, const std::string &FN, LLVMContext& Context) { sys::Path Filename; if (!Filename.set(FN)) { errs() << "Invalid file name: '" << FN << "'\n"; return NULL; } SMDiagnostic Err; if (Verbose) errs() << "Loading '" << Filename.c_str() << "'\n"; Module* Result = 0; const std::string &FNStr = Filename.str(); Result = ParseIRFile(FNStr, Err, Context); if (Result) return Result; // Load successful! Err.print(argv0, errs()); return NULL; } int main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); LLVMContext &Context = getGlobalContext(); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm linker\n"); unsigned BaseArg = 0; std::string ErrorMessage; OwningPtr<Module> Composite(LoadFile(argv[0], InputFilenames[BaseArg], Context)); if (Composite.get() == 0) { errs() << argv[0] << ": error loading file '" << InputFilenames[BaseArg] << "'\n"; return 1; } for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) { OwningPtr<Module> M(LoadFile(argv[0], InputFilenames[i], Context)); if (M.get() == 0) { errs() << argv[0] << ": error loading file '" <<InputFilenames[i]<< "'\n"; return 1; } if (Verbose) errs() << "Linking in '" << InputFilenames[i] << "'\n"; if (Linker::LinkModules(Composite.get(), M.get(), Linker::DestroySource, &ErrorMessage)) { errs() << argv[0] << ": link error in '" << InputFilenames[i] << "': " << ErrorMessage << "\n"; return 1; } } if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite; std::string ErrorInfo; tool_output_file Out(OutputFilename.c_str(), ErrorInfo, raw_fd_ostream::F_Binary); if (!ErrorInfo.empty()) { errs() << ErrorInfo << '\n'; return 1; } if (verifyModule(*Composite)) { errs() << argv[0] << ": linked module is broken!\n"; return 1; } if (Verbose) errs() << "Writing bitcode...\n"; if (OutputAssembly) { Out.os() << *Composite; } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true)) WriteBitcodeToFile(Composite.get(), Out.os()); // Declare success. Out.keep(); return 0; }
//===- llvm-link.cpp - Low-level LLVM linker ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility may be invoked in the following manner: // llvm-link a.bc b.bc c.bc -o x.bc // //===----------------------------------------------------------------------===// #include "llvm/Linker.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/SystemUtils.h" #include "llvm/Support/ToolOutputFile.h" #include <memory> using namespace llvm; static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, cl::desc("<input bitcode files>")); static cl::opt<std::string> OutputFilename("o", cl::desc("Override output filename"), cl::init("-"), cl::value_desc("filename")); static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals")); static cl::opt<bool> OutputAssembly("S", cl::desc("Write output as LLVM assembly"), cl::Hidden); static cl::opt<bool> Verbose("v", cl::desc("Print information about actions taken")); static cl::opt<bool> DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden); // LoadFile - Read the specified bitcode file in and return it. This routine // searches the link path for the specified file to try to find it... // static inline Module *LoadFile(const char *argv0, const std::string &FN, LLVMContext& Context) { sys::Path Filename; if (!Filename.set(FN)) { errs() << "Invalid file name: '" << FN << "'\n"; return NULL; } SMDiagnostic Err; if (Verbose) errs() << "Loading '" << Filename.c_str() << "'\n"; Module* Result = 0; const std::string &FNStr = Filename.str(); Result = ParseIRFile(FNStr, Err, Context); if (Result) return Result; // Load successful! Err.print(argv0, errs()); return NULL; } int main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); LLVMContext &Context = getGlobalContext(); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm linker\n"); unsigned BaseArg = 0; std::string ErrorMessage; OwningPtr<Module> Composite(LoadFile(argv[0], InputFilenames[BaseArg], Context)); if (Composite.get() == 0) { errs() << argv[0] << ": error loading file '" << InputFilenames[BaseArg] << "'\n"; return 1; } Linker L(Composite.get()); for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) { OwningPtr<Module> M(LoadFile(argv[0], InputFilenames[i], Context)); if (M.get() == 0) { errs() << argv[0] << ": error loading file '" <<InputFilenames[i]<< "'\n"; return 1; } if (Verbose) errs() << "Linking in '" << InputFilenames[i] << "'\n"; if (L.linkInModule(M.get(), &ErrorMessage)) { errs() << argv[0] << ": link error in '" << InputFilenames[i] << "': " << ErrorMessage << "\n"; return 1; } } if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite; std::string ErrorInfo; tool_output_file Out(OutputFilename.c_str(), ErrorInfo, raw_fd_ostream::F_Binary); if (!ErrorInfo.empty()) { errs() << ErrorInfo << '\n'; return 1; } if (verifyModule(*Composite)) { errs() << argv[0] << ": linked module is broken!\n"; return 1; } if (Verbose) errs() << "Writing bitcode...\n"; if (OutputAssembly) { Out.os() << *Composite; } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true)) WriteBitcodeToFile(Composite.get(), Out.os()); // Declare success. Out.keep(); return 0; }
Optimize llvm-link too.
Optimize llvm-link too. This takes the linking of almost all modules in a clang build from 6:32 to 0:19. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@181105 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap
ec32354110084e3edeb71504e5db2517554bb6f4
tools/osm-sisyphus/upload.cpp
tools/osm-sisyphus/upload.cpp
#include "upload.h" #include "logger.h" #include <QtCore/QDebug> #include <QtCore/QProcess> #include <QtCore/QDateTime> #include <QtCore/QDir> #include <QtCore/QTemporaryFile> #include <QtCore/QUrl> #include <QtXml/QDomDocument> Upload::Upload(QObject *parent) : QObject(parent), m_cacheDownloads(false), m_uploadFiles(true) { // nothing to do } void Upload::processQueue() { if (m_queue.isEmpty()) { return; } Package const package = m_queue.takeFirst(); if (upload(package)) { QString const message = QString("File %1 (%2) successfully created and uploaded").arg(package.file.fileName()).arg(Region::fileSize(package.file)); Logger::instance().setStatus(package.region.id(), package.region.name(), "finished", message); } deleteFile(package.file); processQueue(); } bool Upload::upload(const Package &package) { if (!m_uploadFiles) { return true; } QProcess ssh; QStringList arguments; QString const auth = "[email protected]"; arguments << auth; arguments << "mkdir" << "-p"; QString remoteDir = QString("/home/marble/web/monav/") + targetDir(); arguments << remoteDir; ssh.start("ssh", arguments); ssh.waitForFinished(1000 * 60 * 10); // wait up to 10 minutes for mkdir to complete if (ssh.exitStatus() != QProcess::NormalExit || ssh.exitCode() != 0) { qDebug() << "Failed to create remote directory " << remoteDir; Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to create remote directory: " + ssh.readAllStandardError()); return false; } QProcess scp; arguments.clear(); arguments << package.file.absoluteFilePath(); QString target = remoteDir + "/" + package.file.fileName(); arguments << auth + ":" + target; scp.start("scp", arguments); scp.waitForFinished(1000 * 60 * 60 * 12); // wait up to 12 hours for upload to complete if (scp.exitStatus() != QProcess::NormalExit || scp.exitCode() != 0) { qDebug() << "Failed to upload " << target; Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to upload file: " + scp.readAllStandardError()); return false; } return adjustNewstuffFile(package); } void Upload::deleteFile(const QFileInfo &file) { if (!m_cacheDownloads) { QFile::remove(file.absoluteFilePath()); } } bool Upload::adjustNewstuffFile(const Package &package) { if (m_xml.isNull()) { QTemporaryFile tempFile(QDir::tempPath() + "/monav-maps-XXXXXX.xml"); tempFile.setAutoRemove(false); tempFile.open(); QString monavFilename = tempFile.fileName(); tempFile.close(); QProcess wget; QStringList const arguments = QStringList() << "http://files.kde.org/marble/newstuff/maps-monav.xml" << "-O" << monavFilename; wget.start("wget", arguments); wget.waitForFinished(1000 * 60 * 60 * 12); // wait up to 12 hours for download to complete if (wget.exitStatus() != QProcess::NormalExit || wget.exitCode() != 0) { qDebug() << "Failed to download newstuff file from files.kde.org"; Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to sync newstuff file: " + wget.readAllStandardError()); return false; } QFile file(monavFilename); if (!file.open(QFile::ReadOnly)) { qDebug() << "Failed to open newstuff file" << monavFilename; Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to open newstuff file."); return false; } if ( !m_xml.setContent( &file ) ) { qDebug() << "Cannot parse newstuff xml file."; Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to parse newstuff .xml file."); return false; } QFile::remove(monavFilename); } QDomElement root = m_xml.documentElement(); QDomNodeList regions = root.elementsByTagName( "stuff" ); for ( unsigned int i = 0; i < regions.length(); ++i ) { QDomNode node = regions.item( i ); if (!node.namedItem("payload").isNull()) { QUrl url = node.namedItem("payload").toElement().text(); QFileInfo fileInfo(url.path()); if (fileInfo.fileName() == package.file.fileName()) { QString removeFile; QDomNode dateNode = node.namedItem("releasedate"); if (!dateNode.isNull()) { dateNode.removeChild(dateNode.firstChild()); dateNode.appendChild(m_xml.createTextNode(releaseDate())); } QDomNode versionNode = node.namedItem("version"); if (!versionNode.isNull()) { double version = versionNode.toElement().text().toDouble(); versionNode.removeChild(versionNode.firstChild()); versionNode.appendChild(m_xml.createTextNode(QString::number(version+0.1, 'f', 1))); } QDomNode payloadNode = node.namedItem("payload"); payloadNode.removeChild(payloadNode.firstChild()); if (fileInfo.dir().dirName() != targetDir()) { removeFile = QString("/home/marble/web/monav/%1/%2").arg(fileInfo.dir().dirName()).arg(package.file.fileName()); qDebug() << "Going to remove the old file " << removeFile; } QString payload = "http://files.kde.org/marble/monav/%1/%2"; payload = payload.arg(targetDir()).arg(package.file.fileName()); payloadNode.appendChild(m_xml.createTextNode(payload)); return removeFile.isEmpty() ? uploadNewstuff() : (uploadNewstuff() && deleteRemoteFile(removeFile)); } } } QDomNode stuff = root.appendChild(m_xml.createElement("stuff")); stuff.toElement().setAttribute("category", "marble/routing/monav"); QDomNode nameNode = stuff.appendChild(m_xml.createElement("name")); nameNode.toElement().setAttribute("lang", "en"); QString name = "%1 / %2 (%3)"; if (package.region.country().isEmpty()) { name = name.arg(package.region.continent()).arg(package.region.name()); name = name.arg(package.transport); } else { name = "%1 / %2 / %3 (%4)"; name = name.arg(package.region.continent()).arg(package.region.country()); name = name.arg(package.region.name()).arg(package.transport); } nameNode.appendChild(m_xml.createTextNode(name)); QDomNode authorNode = stuff.appendChild(m_xml.createElement("author")); authorNode.appendChild(m_xml.createTextNode("Automatically created from map data assembled by the OpenStreetMap community")); QDomNode licenseNode = stuff.appendChild(m_xml.createElement("license")); licenseNode.appendChild(m_xml.createTextNode("Creative Commons by-SA 2.0")); QDomNode summaryNode = stuff.appendChild(m_xml.createElement("license")); QString summary = "Requires KDE >= 4.6: Offline Routing in %1, %2"; summary = summary.arg(package.region.name()).arg(package.region.continent()); summaryNode.appendChild(m_xml.createTextNode(summary)); QDomNode versionNode = stuff.appendChild(m_xml.createElement("version")); versionNode.appendChild(m_xml.createTextNode("0.1")); QDomNode dateNode = stuff.appendChild(m_xml.createElement("releasedate")); dateNode.appendChild(m_xml.createTextNode(releaseDate())); QDomNode previewNode = stuff.appendChild(m_xml.createElement("preview")); QString preview = "http://files.kde.org/marble/monav/previews/%1-preview.png"; preview = preview.arg(package.region.id()); previewNode.appendChild(m_xml.createTextNode(summary)); QDomNode payloadNode = stuff.appendChild(m_xml.createElement("payload")); payloadNode.toElement().setAttribute("lang", "en"); QString payload = "http://files.kde.org/marble/monav/%1/%2"; payload = payload.arg(targetDir()).arg(package.file.fileName()); payloadNode.appendChild(m_xml.createTextNode(payload)); return uploadNewstuff(); } bool Upload::uploadNewstuff() { QTemporaryFile outFile(QDir::tempPath() + "/monav-maps-out-XXXXXX.xml"); outFile.open(); QTextStream outStream(&outFile); outStream << m_xml.toString(2); outStream.flush(); QProcess scp; QStringList arguments; arguments << outFile.fileName(); arguments << "[email protected]:/home/marble/web/newstuff/maps-monav.xml"; scp.start("scp", arguments); scp.waitForFinished(1000 * 60 * 60 * 12); // wait up to 12 hours for upload to complete if (scp.exitStatus() != QProcess::NormalExit || scp.exitCode() != 0) { qDebug() << "Failed to upload " << outFile.fileName() << ": " << scp.readAllStandardError(); return false; } return true; } bool Upload::deleteRemoteFile(const QString &filename) { if (filename.isEmpty()) { return true; } if (!filename.startsWith("/home/marble/")) { return false; } QProcess ssh; QStringList arguments; arguments << "[email protected]" << "rm" << filename; ssh.start("ssh", arguments); ssh.waitForFinished(1000 * 60 * 10); // wait up to 10 minutes for rm to complete if (ssh.exitStatus() != QProcess::NormalExit || ssh.exitCode() != 0) { qDebug() << "Failed to delete remote file " << filename; return false; } return true; } void Upload::uploadAndDelete(const Region &region, const QFileInfo &file, const QString &transport) { Package package; package.region = region; package.file = file; package.transport = transport; m_queue.removeAll(package); m_queue << package; processQueue(); } bool Upload::Package::operator ==(const Upload::Package &other) const { return region == other.region; } Upload &Upload::instance() { static Upload m_instance; return m_instance; } bool Upload::cacheDownloads() const { return m_cacheDownloads; } bool Upload::uploadFiles() const { return m_uploadFiles; } void Upload::setCacheDownloads(bool arg) { m_cacheDownloads = arg; } void Upload::setUploadFiles(bool arg) { m_uploadFiles = arg; } QString Upload::targetDir() const { QString targetDir = "%1-w%2"; targetDir = targetDir.arg(QDateTime::currentDateTime().date().year()); targetDir = targetDir.arg(QDateTime::currentDateTime().date().weekNumber()); return targetDir; } QString Upload::releaseDate() const { return QDateTime::currentDateTime().toString("MM/dd/yy"); }
#include "upload.h" #include "logger.h" #include <QtCore/QDebug> #include <QtCore/QProcess> #include <QtCore/QDateTime> #include <QtCore/QDir> #include <QtCore/QTemporaryFile> #include <QtCore/QUrl> #include <QtXml/QDomDocument> Upload::Upload(QObject *parent) : QObject(parent), m_cacheDownloads(false), m_uploadFiles(true) { // nothing to do } void Upload::processQueue() { if (m_queue.isEmpty()) { return; } Package const package = m_queue.takeFirst(); if (upload(package)) { QString const message = QString("File %1 (%2) successfully created and uploaded").arg(package.file.fileName()).arg(Region::fileSize(package.file)); Logger::instance().setStatus(package.region.id(), package.region.name(), "finished", message); } deleteFile(package.file); processQueue(); } bool Upload::upload(const Package &package) { if (!m_uploadFiles) { return true; } QProcess ssh; QStringList arguments; QString const auth = "[email protected]"; arguments << auth; arguments << "mkdir" << "-p"; QString remoteDir = QString("/home/marble/web/monav/") + targetDir(); arguments << remoteDir; ssh.start("ssh", arguments); ssh.waitForFinished(1000 * 60 * 10); // wait up to 10 minutes for mkdir to complete if (ssh.exitStatus() != QProcess::NormalExit || ssh.exitCode() != 0) { qDebug() << "Failed to create remote directory " << remoteDir; Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to create remote directory: " + ssh.readAllStandardError()); return false; } QProcess scp; arguments.clear(); arguments << package.file.absoluteFilePath(); QString target = remoteDir + "/" + package.file.fileName(); arguments << auth + ":" + target; scp.start("scp", arguments); scp.waitForFinished(1000 * 60 * 60 * 12); // wait up to 12 hours for upload to complete if (scp.exitStatus() != QProcess::NormalExit || scp.exitCode() != 0) { qDebug() << "Failed to upload " << target; Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to upload file: " + scp.readAllStandardError()); return false; } return adjustNewstuffFile(package); } void Upload::deleteFile(const QFileInfo &file) { if (!m_cacheDownloads) { QFile::remove(file.absoluteFilePath()); } } bool Upload::adjustNewstuffFile(const Package &package) { if (m_xml.isNull()) { QTemporaryFile tempFile(QDir::tempPath() + "/monav-maps-XXXXXX.xml"); tempFile.setAutoRemove(false); tempFile.open(); QString monavFilename = tempFile.fileName(); tempFile.close(); QProcess wget; QStringList const arguments = QStringList() << "http://files.kde.org/marble/newstuff/maps-monav.xml" << "-O" << monavFilename; wget.start("wget", arguments); wget.waitForFinished(1000 * 60 * 60 * 12); // wait up to 12 hours for download to complete if (wget.exitStatus() != QProcess::NormalExit || wget.exitCode() != 0) { qDebug() << "Failed to download newstuff file from files.kde.org"; Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to sync newstuff file: " + wget.readAllStandardError()); return false; } QFile file(monavFilename); if (!file.open(QFile::ReadOnly)) { qDebug() << "Failed to open newstuff file" << monavFilename; Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to open newstuff file."); return false; } if ( !m_xml.setContent( &file ) ) { qDebug() << "Cannot parse newstuff xml file."; Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to parse newstuff .xml file."); return false; } QFile::remove(monavFilename); } QDomElement root = m_xml.documentElement(); QDomNodeList regions = root.elementsByTagName( "stuff" ); for ( unsigned int i = 0; i < regions.length(); ++i ) { QDomNode node = regions.item( i ); if (!node.namedItem("payload").isNull()) { QUrl url = node.namedItem("payload").toElement().text(); QFileInfo fileInfo(url.path()); if (fileInfo.fileName() == package.file.fileName()) { QString removeFile; QDomNode dateNode = node.namedItem("releasedate"); if (!dateNode.isNull()) { dateNode.removeChild(dateNode.firstChild()); dateNode.appendChild(m_xml.createTextNode(releaseDate())); } QDomNode versionNode = node.namedItem("version"); if (!versionNode.isNull()) { double version = versionNode.toElement().text().toDouble(); versionNode.removeChild(versionNode.firstChild()); versionNode.appendChild(m_xml.createTextNode(QString::number(version+0.1, 'f', 1))); } QDomNode payloadNode = node.namedItem("payload"); payloadNode.removeChild(payloadNode.firstChild()); if (fileInfo.dir().dirName() != targetDir()) { removeFile = QString("/home/marble/web/monav/%1/%2").arg(fileInfo.dir().dirName()).arg(package.file.fileName()); qDebug() << "Going to remove the old file " << removeFile; } QString payload = "http://files.kde.org/marble/monav/%1/%2"; payload = payload.arg(targetDir()).arg(package.file.fileName()); payloadNode.appendChild(m_xml.createTextNode(payload)); return removeFile.isEmpty() ? uploadNewstuff() : (uploadNewstuff() && deleteRemoteFile(removeFile)); } } } QDomNode stuff = root.appendChild(m_xml.createElement("stuff")); stuff.toElement().setAttribute("category", "marble/routing/monav"); QDomNode nameNode = stuff.appendChild(m_xml.createElement("name")); nameNode.toElement().setAttribute("lang", "en"); QString name = "%1 / %2 (%3)"; if (package.region.country().isEmpty()) { name = name.arg(package.region.continent()).arg(package.region.name()); name = name.arg(package.transport); } else { name = "%1 / %2 / %3 (%4)"; name = name.arg(package.region.continent()).arg(package.region.country()); name = name.arg(package.region.name()).arg(package.transport); } nameNode.appendChild(m_xml.createTextNode(name)); QDomNode authorNode = stuff.appendChild(m_xml.createElement("author")); authorNode.appendChild(m_xml.createTextNode("Automatically created from map data assembled by the OpenStreetMap community")); QDomNode licenseNode = stuff.appendChild(m_xml.createElement("license")); licenseNode.appendChild(m_xml.createTextNode("Creative Commons by-SA 2.0")); QDomNode summaryNode = stuff.appendChild(m_xml.createElement("summary")); QString summary = "Requires KDE >= 4.6: Offline Routing in %1, %2"; summary = summary.arg(package.region.name()).arg(package.region.continent()); summaryNode.appendChild(m_xml.createTextNode(summary)); QDomNode versionNode = stuff.appendChild(m_xml.createElement("version")); versionNode.appendChild(m_xml.createTextNode("0.1")); QDomNode dateNode = stuff.appendChild(m_xml.createElement("releasedate")); dateNode.appendChild(m_xml.createTextNode(releaseDate())); QDomNode previewNode = stuff.appendChild(m_xml.createElement("preview")); QString preview = "http://files.kde.org/marble/monav/previews/%1-preview.png"; preview = preview.arg(package.region.id()); previewNode.appendChild(m_xml.createTextNode(summary)); QDomNode payloadNode = stuff.appendChild(m_xml.createElement("payload")); payloadNode.toElement().setAttribute("lang", "en"); QString payload = "http://files.kde.org/marble/monav/%1/%2"; payload = payload.arg(targetDir()).arg(package.file.fileName()); payloadNode.appendChild(m_xml.createTextNode(payload)); return uploadNewstuff(); } bool Upload::uploadNewstuff() { QTemporaryFile outFile(QDir::tempPath() + "/monav-maps-out-XXXXXX.xml"); outFile.open(); QTextStream outStream(&outFile); outStream << m_xml.toString(2); outStream.flush(); QProcess scp; QStringList arguments; arguments << outFile.fileName(); arguments << "[email protected]:/home/marble/web/newstuff/maps-monav.xml"; scp.start("scp", arguments); scp.waitForFinished(1000 * 60 * 60 * 12); // wait up to 12 hours for upload to complete if (scp.exitStatus() != QProcess::NormalExit || scp.exitCode() != 0) { qDebug() << "Failed to upload " << outFile.fileName() << ": " << scp.readAllStandardError(); return false; } return true; } bool Upload::deleteRemoteFile(const QString &filename) { if (filename.isEmpty()) { return true; } if (!filename.startsWith("/home/marble/")) { return false; } QProcess ssh; QStringList arguments; arguments << "[email protected]" << "rm" << filename; ssh.start("ssh", arguments); ssh.waitForFinished(1000 * 60 * 10); // wait up to 10 minutes for rm to complete if (ssh.exitStatus() != QProcess::NormalExit || ssh.exitCode() != 0) { qDebug() << "Failed to delete remote file " << filename; return false; } return true; } void Upload::uploadAndDelete(const Region &region, const QFileInfo &file, const QString &transport) { Package package; package.region = region; package.file = file; package.transport = transport; m_queue.removeAll(package); m_queue << package; processQueue(); } bool Upload::Package::operator ==(const Upload::Package &other) const { return region == other.region; } Upload &Upload::instance() { static Upload m_instance; return m_instance; } bool Upload::cacheDownloads() const { return m_cacheDownloads; } bool Upload::uploadFiles() const { return m_uploadFiles; } void Upload::setCacheDownloads(bool arg) { m_cacheDownloads = arg; } void Upload::setUploadFiles(bool arg) { m_uploadFiles = arg; } QString Upload::targetDir() const { QString targetDir = "%1-w%2"; targetDir = targetDir.arg(QDateTime::currentDateTime().date().year()); targetDir = targetDir.arg(QDateTime::currentDateTime().date().weekNumber()); return targetDir; } QString Upload::releaseDate() const { return QDateTime::currentDateTime().toString("MM/dd/yy"); }
Fix summary tag
Fix summary tag
C++
lgpl-2.1
oberluz/marble,adraghici/marble,adraghici/marble,Earthwings/marble,probonopd/marble,Earthwings/marble,probonopd/marble,tucnak/marble,AndreiDuma/marble,quannt24/marble,AndreiDuma/marble,tzapzoor/marble,Earthwings/marble,tucnak/marble,David-Gil/marble-dev,quannt24/marble,probonopd/marble,tzapzoor/marble,Earthwings/marble,quannt24/marble,tucnak/marble,probonopd/marble,rku/marble,utkuaydin/marble,AndreiDuma/marble,AndreiDuma/marble,oberluz/marble,AndreiDuma/marble,Earthwings/marble,David-Gil/marble-dev,Earthwings/marble,tucnak/marble,tzapzoor/marble,oberluz/marble,David-Gil/marble-dev,tzapzoor/marble,probonopd/marble,utkuaydin/marble,tzapzoor/marble,utkuaydin/marble,probonopd/marble,oberluz/marble,probonopd/marble,oberluz/marble,tucnak/marble,quannt24/marble,utkuaydin/marble,adraghici/marble,oberluz/marble,adraghici/marble,adraghici/marble,rku/marble,utkuaydin/marble,tzapzoor/marble,tucnak/marble,rku/marble,David-Gil/marble-dev,adraghici/marble,tzapzoor/marble,rku/marble,quannt24/marble,quannt24/marble,utkuaydin/marble,AndreiDuma/marble,David-Gil/marble-dev,tzapzoor/marble,rku/marble,rku/marble,quannt24/marble,tucnak/marble,David-Gil/marble-dev
9dcc5b19ae2bdcb436e49d098db59f7088cd0936
SurgSim/Collision/ContactCalculation.cpp
SurgSim/Collision/ContactCalculation.cpp
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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 <thread> #include "SurgSim/Collision/ContactCalculation.h" #include "SurgSim/Collision/DcdCollision.h" #include "SurgSim/Collision/DefaultContactCalculation.h" #include "SurgSim/Collision/Representation.h" namespace SurgSim { namespace Collision { ContactCalculation::TableType ContactCalculation::m_contactCalculations; std::once_flag ContactCalculation::m_initializationFlag; ContactCalculation::ContactCalculation() { } ContactCalculation::~ContactCalculation() { } void ContactCalculation::registerContactCalculation(const std::shared_ptr<ContactCalculation>& calculation) { std::call_once(m_initializationFlag, ContactCalculation::initializeTable); privateRegister(calculation, calculation->getShapeTypes()); } const ContactCalculation::TableType& ContactCalculation::getContactTable() { std::call_once(m_initializationFlag, ContactCalculation::initializeTable); return m_contactCalculations; } void ContactCalculation::calculateContact(std::shared_ptr<CollisionPair> pair) { doCalculateContact(pair); } std::list<std::shared_ptr<Contact>> ContactCalculation::calculateContact( const std::shared_ptr<Math::Shape>& shape1, const Math::RigidTransform3d& pose1, const std::shared_ptr<Math::Shape>& shape2, const Math::RigidTransform3d& pose2) { auto types = getShapeTypes(); auto incoming = std::make_pair(shape1->getType(), shape2->getType()); if (incoming == types) { return doCalculateContact(shape1, pose1, shape2, pose2); } if (incoming.first == types.second && incoming.second == types.first) { auto contacts = doCalculateContact(shape2, pose2, shape1, pose1); for (const auto& contact : contacts) { contact->normal = -contact->normal; contact->force = -contact->force; } return contacts; } SURGSIM_FAILURE() << "Incorrect shape type for this calculation expected " << types.first << ", " << types.second << " received " << incoming.first << ", " << incoming.second << "."; return std::list<std::shared_ptr<Contact>>(); } void ContactCalculation::doCalculateContact(std::shared_ptr<CollisionPair> pair) { std::pair<int, int> shapeTypes = getShapeTypes(); int firstShapeType = pair->getFirst()->getShapeType(); int secondShapeType = pair->getSecond()->getShapeType(); if (firstShapeType != secondShapeType && firstShapeType == shapeTypes.second && secondShapeType == shapeTypes.first) { pair->swapRepresentations(); std::swap(firstShapeType, secondShapeType); } if (shapeTypes.first != SurgSim::Math::SHAPE_TYPE_NONE) { SURGSIM_ASSERT(firstShapeType == shapeTypes.first) << "First Object, wrong type of object" << firstShapeType; } if (shapeTypes.second != SurgSim::Math::SHAPE_TYPE_NONE) { SURGSIM_ASSERT(secondShapeType == shapeTypes.second) << "Second Object, wrong type of object" << secondShapeType; } std::shared_ptr<Math::Shape> shape1 = pair->getFirst()->getShape(); if (shape1->isTransformable()) { shape1 = pair->getFirst()->getPosedShape(); } std::shared_ptr<Math::Shape> shape2 = pair->getSecond()->getShape(); if (shape2->isTransformable()) { shape2 = pair->getSecond()->getPosedShape(); } auto contacts = doCalculateContact(shape1, pair->getFirst()->getPose(), shape2, pair->getSecond()->getPose()); for (auto& contact : contacts) { pair->addContact(contact); } } void ContactCalculation::initializeTable() { for (int i = 0; i < SurgSim::Math::SHAPE_TYPE_COUNT; ++i) { for (int j = 0; j < SurgSim::Math::SHAPE_TYPE_COUNT; ++j) { m_contactCalculations[i][j].reset(new Collision::DefaultContactCalculation(false)); } } ContactCalculation::privateRegister(std::make_shared<Collision::BoxCapsuleDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::BoxDoubleSidedPlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::BoxPlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::BoxSphereDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::CapsuleSphereDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::OctreeCapsuleDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::OctreeDoubleSidedPlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::OctreePlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::OctreeSphereDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::SegmentMeshTriangleMeshDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::SphereSphereDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::SphereDoubleSidedPlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::SpherePlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::TriangleMeshParticlesDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::TriangleMeshPlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::TriangleMeshTriangleMeshDcdContact>()); const std::array<int, Math::SHAPE_TYPE_COUNT> allshapes = { Math::SHAPE_TYPE_BOX, Math::SHAPE_TYPE_CAPSULE, Math::SHAPE_TYPE_CYLINDER, Math::SHAPE_TYPE_DOUBLESIDEDPLANE, Math::SHAPE_TYPE_MESH, Math::SHAPE_TYPE_OCTREE, Math::SHAPE_TYPE_PARTICLES, Math::SHAPE_TYPE_PLANE, Math::SHAPE_TYPE_SPHERE, Math::SHAPE_TYPE_SURFACEMESH, Math::SHAPE_TYPE_SEGMENTMESH, Math::SHAPE_TYPE_COMPOUNDSHAPE }; for (auto type : allshapes) { ContactCalculation::privateRegister(std::make_shared<Collision::CompoundShapeDcdContact>( std::make_pair(Math::SHAPE_TYPE_COMPOUNDSHAPE, type))); } } void ContactCalculation::privateRegister( const std::shared_ptr<ContactCalculation>& calculation) { privateRegister(calculation, calculation->getShapeTypes()); } void ContactCalculation::privateRegister( const std::shared_ptr<ContactCalculation>& calculation, const std::pair<int, int>& types) { m_contactCalculations[types.first][types.second] = calculation; m_contactCalculations[types.second][types.first] = calculation; } }; // namespace Collision }; // namespace SurgSim
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions 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 <thread> #include "SurgSim/Collision/ContactCalculation.h" #include "SurgSim/Collision/DcdCollision.h" #include "SurgSim/Collision/DefaultContactCalculation.h" #include "SurgSim/Collision/Representation.h" namespace SurgSim { namespace Collision { ContactCalculation::TableType ContactCalculation::m_contactCalculations; std::once_flag ContactCalculation::m_initializationFlag; ContactCalculation::ContactCalculation() { } ContactCalculation::~ContactCalculation() { } void ContactCalculation::registerContactCalculation(const std::shared_ptr<ContactCalculation>& calculation) { std::call_once(m_initializationFlag, ContactCalculation::initializeTable); privateRegister(calculation, calculation->getShapeTypes()); } const ContactCalculation::TableType& ContactCalculation::getContactTable() { std::call_once(m_initializationFlag, ContactCalculation::initializeTable); return m_contactCalculations; } void ContactCalculation::calculateContact(std::shared_ptr<CollisionPair> pair) { doCalculateContact(pair); } std::list<std::shared_ptr<Contact>> ContactCalculation::calculateContact( const std::shared_ptr<Math::Shape>& shape1, const Math::RigidTransform3d& pose1, const std::shared_ptr<Math::Shape>& shape2, const Math::RigidTransform3d& pose2) { auto types = getShapeTypes(); auto incoming = std::make_pair(shape1->getType(), shape2->getType()); if (incoming == types) { return doCalculateContact(shape1, pose1, shape2, pose2); } if (incoming.first == types.second && incoming.second == types.first) { auto contacts = doCalculateContact(shape2, pose2, shape1, pose1); for (const auto& contact : contacts) { contact->normal = -contact->normal; contact->force = -contact->force; } return contacts; } if (types.first != Math::SHAPE_TYPE_NONE && types.second != Math::SHAPE_TYPE_NONE) { SURGSIM_FAILURE() << "Incorrect shape type for this calculation expected " << types.first << ", " << types.second << " received " << incoming.first << ", " << incoming.second << "."; } return std::list<std::shared_ptr<Contact>>(); } void ContactCalculation::doCalculateContact(std::shared_ptr<CollisionPair> pair) { std::pair<int, int> shapeTypes = getShapeTypes(); int firstShapeType = pair->getFirst()->getShapeType(); int secondShapeType = pair->getSecond()->getShapeType(); if (firstShapeType != secondShapeType && firstShapeType == shapeTypes.second && secondShapeType == shapeTypes.first) { pair->swapRepresentations(); std::swap(firstShapeType, secondShapeType); } if (shapeTypes.first != SurgSim::Math::SHAPE_TYPE_NONE) { SURGSIM_ASSERT(firstShapeType == shapeTypes.first) << "First Object, wrong type of object" << firstShapeType; } if (shapeTypes.second != SurgSim::Math::SHAPE_TYPE_NONE) { SURGSIM_ASSERT(secondShapeType == shapeTypes.second) << "Second Object, wrong type of object" << secondShapeType; } std::shared_ptr<Math::Shape> shape1 = pair->getFirst()->getShape(); if (shape1->isTransformable()) { shape1 = pair->getFirst()->getPosedShape(); } std::shared_ptr<Math::Shape> shape2 = pair->getSecond()->getShape(); if (shape2->isTransformable()) { shape2 = pair->getSecond()->getPosedShape(); } auto contacts = doCalculateContact(shape1, pair->getFirst()->getPose(), shape2, pair->getSecond()->getPose()); for (auto& contact : contacts) { pair->addContact(contact); } } void ContactCalculation::initializeTable() { for (int i = 0; i < SurgSim::Math::SHAPE_TYPE_COUNT; ++i) { for (int j = 0; j < SurgSim::Math::SHAPE_TYPE_COUNT; ++j) { m_contactCalculations[i][j].reset(new Collision::DefaultContactCalculation(false)); } } ContactCalculation::privateRegister(std::make_shared<Collision::BoxCapsuleDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::BoxDoubleSidedPlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::BoxPlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::BoxSphereDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::CapsuleSphereDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::OctreeCapsuleDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::OctreeDoubleSidedPlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::OctreePlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::OctreeSphereDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::SegmentMeshTriangleMeshDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::SphereSphereDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::SphereDoubleSidedPlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::SpherePlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::TriangleMeshParticlesDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::TriangleMeshPlaneDcdContact>()); ContactCalculation::privateRegister(std::make_shared<Collision::TriangleMeshTriangleMeshDcdContact>()); const std::array<int, Math::SHAPE_TYPE_COUNT> allshapes = { Math::SHAPE_TYPE_BOX, Math::SHAPE_TYPE_CAPSULE, Math::SHAPE_TYPE_CYLINDER, Math::SHAPE_TYPE_DOUBLESIDEDPLANE, Math::SHAPE_TYPE_MESH, Math::SHAPE_TYPE_OCTREE, Math::SHAPE_TYPE_PARTICLES, Math::SHAPE_TYPE_PLANE, Math::SHAPE_TYPE_SPHERE, Math::SHAPE_TYPE_SURFACEMESH, Math::SHAPE_TYPE_SEGMENTMESH, Math::SHAPE_TYPE_COMPOUNDSHAPE }; for (auto type : allshapes) { ContactCalculation::privateRegister(std::make_shared<Collision::CompoundShapeDcdContact>( std::make_pair(Math::SHAPE_TYPE_COMPOUNDSHAPE, type))); } } void ContactCalculation::privateRegister( const std::shared_ptr<ContactCalculation>& calculation) { privateRegister(calculation, calculation->getShapeTypes()); } void ContactCalculation::privateRegister( const std::shared_ptr<ContactCalculation>& calculation, const std::pair<int, int>& types) { m_contactCalculations[types.first][types.second] = calculation; m_contactCalculations[types.second][types.first] = calculation; } }; // namespace Collision }; // namespace SurgSim
Fix fallthrough case for default contact calculation
Fix fallthrough case for default contact calculation The default for missing contact calcuation is to report and optionally assert in the default contact calcualtion, this was broken as the assertion would happen unconditionally in the lines that are fixed here
C++
apache-2.0
simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim
586a8e0312836022aa9b162fabcb7fcd579c95dc
bots/cplusplus/TestRobot.cxx
bots/cplusplus/TestRobot.cxx
/* bzflag * Copyright (c) 1993 - 2009 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* BZRobots API Header */ #include "AdvancedRobot.h" using namespace BZRobots; /** * TestRobot: Testing basic stuff. */ class TestRobot : public AdvancedRobot { public: TestRobot() {} void run(); void onBattleEnded(const BattleEndedEvent &e); void onBulletHit(const BulletHitEvent &e); void onBulletMissed(const BulletMissedEvent &e); void onDeath(const DeathEvent &e); void onHitByBullet(const HitByBulletEvent &e); void onHitWall(const HitWallEvent &e); void onRobotDeath(const RobotDeathEvent &e); void onScannedRobot(const ScannedRobotEvent &e); void onSpawn(const SpawnEvent &e); void onStatus(const StatusEvent &e); void onWin(const WinEvent &e); }; extern "C" { AdvancedRobot *create() { return new TestRobot(); } void destroy(AdvancedRobot *robot) { delete robot; } } void TestRobot::run() { while(true) { printf("TestRobot: others: %d\n",getOthers()); printf("TestRobot: run\n"); ahead(10); fire(); /* setFire(); setAhead(200); do { double lastDistance = getDistanceRemaining(); execute(); if(lastDistance == getDistanceRemaining()) break; } while (getDistanceRemaining() > 0); setAhead(-20); do { double lastDistance = getDistanceRemaining(); execute(); if(lastDistance == getDistanceRemaining()) break; } while (getDistanceRemaining() > 0); setTurnLeft(90); do { double lastTurn = getTurnRemaining(); execute(); if(lastTurn == getTurnRemaining()) break; } while (getTurnRemaining() > 0); */ } } void TestRobot::onBattleEnded(const BattleEndedEvent &/*e*/) { //printf("TestRobot: BattleEndedEvent\n"); } void TestRobot::onBulletHit(const BulletHitEvent &e) { printf("TestRobot: BulletHitEvent (%s)\n",e.getName().c_str()); } void TestRobot::onBulletMissed(const BulletMissedEvent &/*e*/) { //printf("TestRobot: BulletMissedEvent\n"); } void TestRobot::onDeath(const DeathEvent &/*e*/) { printf("TestRobot: DeathEvent\n"); } void TestRobot::onHitByBullet(const HitByBulletEvent &/*e*/) { //printf("TestRobot: HitByBulletEvent\n"); } void TestRobot::onHitWall(const HitWallEvent &/*e*/) { printf("TestRobot: HitWallEvent\n"); back(100); turnLeft(90); } void TestRobot::onRobotDeath(const RobotDeathEvent &e) { printf("TestRobot: RobotDeathEvent (%s)\n",e.getName().c_str()); } void TestRobot::onScannedRobot(const ScannedRobotEvent &/*e*/) { printf("TestRobot: ScannedRobotEvent\n"); } void TestRobot::onSpawn(const SpawnEvent &/*e*/) { printf("TestRobot: SpawnEvent\n"); } void TestRobot::onStatus(const StatusEvent &/*e*/) { //printf("TestRobot: StatusEvent\n"); } void TestRobot::onWin(const WinEvent &/*e*/) { //printf("TestRobot: WinEvent\n"); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
/* bzflag * Copyright (c) 1993 - 2009 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* BZRobots API Header */ #include "AdvancedRobot.h" /* system headers */ #include <stdio.h> using namespace BZRobots; /** * TestRobot: Testing basic stuff. */ class TestRobot : public AdvancedRobot { public: TestRobot() {} void run(); void onBattleEnded(const BattleEndedEvent &e); void onBulletHit(const BulletHitEvent &e); void onBulletMissed(const BulletMissedEvent &e); void onDeath(const DeathEvent &e); void onHitByBullet(const HitByBulletEvent &e); void onHitWall(const HitWallEvent &e); void onRobotDeath(const RobotDeathEvent &e); void onScannedRobot(const ScannedRobotEvent &e); void onSpawn(const SpawnEvent &e); void onStatus(const StatusEvent &e); void onWin(const WinEvent &e); }; extern "C" { AdvancedRobot *create() { return new TestRobot(); } void destroy(AdvancedRobot *robot) { delete robot; } } void TestRobot::run() { while(true) { printf("TestRobot: others: %d\n",getOthers()); printf("TestRobot: run\n"); ahead(10); fire(); /* setFire(); setAhead(200); do { double lastDistance = getDistanceRemaining(); execute(); if(lastDistance == getDistanceRemaining()) break; } while (getDistanceRemaining() > 0); setAhead(-20); do { double lastDistance = getDistanceRemaining(); execute(); if(lastDistance == getDistanceRemaining()) break; } while (getDistanceRemaining() > 0); setTurnLeft(90); do { double lastTurn = getTurnRemaining(); execute(); if(lastTurn == getTurnRemaining()) break; } while (getTurnRemaining() > 0); */ } } void TestRobot::onBattleEnded(const BattleEndedEvent &/*e*/) { //printf("TestRobot: BattleEndedEvent\n"); } void TestRobot::onBulletHit(const BulletHitEvent &e) { printf("TestRobot: BulletHitEvent (%s)\n",e.getName().c_str()); } void TestRobot::onBulletMissed(const BulletMissedEvent &/*e*/) { //printf("TestRobot: BulletMissedEvent\n"); } void TestRobot::onDeath(const DeathEvent &/*e*/) { printf("TestRobot: DeathEvent\n"); } void TestRobot::onHitByBullet(const HitByBulletEvent &/*e*/) { //printf("TestRobot: HitByBulletEvent\n"); } void TestRobot::onHitWall(const HitWallEvent &/*e*/) { printf("TestRobot: HitWallEvent\n"); back(100); turnLeft(90); } void TestRobot::onRobotDeath(const RobotDeathEvent &e) { printf("TestRobot: RobotDeathEvent (%s)\n",e.getName().c_str()); } void TestRobot::onScannedRobot(const ScannedRobotEvent &/*e*/) { printf("TestRobot: ScannedRobotEvent\n"); } void TestRobot::onSpawn(const SpawnEvent &/*e*/) { printf("TestRobot: SpawnEvent\n"); } void TestRobot::onStatus(const StatusEvent &/*e*/) { //printf("TestRobot: StatusEvent\n"); } void TestRobot::onWin(const WinEvent &/*e*/) { //printf("TestRobot: WinEvent\n"); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8
Include stdio.h so gcc 4.4 can find the printf() declaration.
Include stdio.h so gcc 4.4 can find the printf() declaration.
C++
lgpl-2.1
kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1,kongr45gpen/bzflag-import-1
64f18c774b7260ec21919f0504610c201987889a
cpp/libjoynrclustercontroller/websocket/WebSocketCcMessagingSkeletonTLS.cpp
cpp/libjoynrclustercontroller/websocket/WebSocketCcMessagingSkeletonTLS.cpp
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "libjoynrclustercontroller/websocket/WebSocketCcMessagingSkeletonTLS.h" #include <mococrw/distinguished_name.h> #include <mococrw/openssl_lib.h> #include <mococrw/openssl_wrap.h> #include <openssl/ssl.h> namespace joynr { WebSocketCcMessagingSkeletonTLS::WebSocketCcMessagingSkeletonTLS( boost::asio::io_service& ioService, std::shared_ptr<IMessageRouter> messageRouter, std::shared_ptr<WebSocketMessagingStubFactory> messagingStubFactory, const system::RoutingTypes::WebSocketAddress& serverAddress, const std::string& caPemFile, const std::string& certPemFile, const std::string& privateKeyPemFile) : WebSocketCcMessagingSkeleton<websocketpp::config::asio_tls>(ioService, messageRouter, messagingStubFactory) { // ensure that OpenSSL is correctly initialized ::SSL_library_init(); ::SSL_load_error_strings(); ::OpenSSL_add_all_algorithms(); endpoint.set_tls_init_handler([this, caPemFile, certPemFile, privateKeyPemFile]( ConnectionHandle hdl) -> std::shared_ptr<SSLContext> { return createSSLContext(caPemFile, certPemFile, privateKeyPemFile, hdl); }); startAccept(serverAddress.getPort()); } std::shared_ptr<WebSocketCcMessagingSkeletonTLS::SSLContext> WebSocketCcMessagingSkeletonTLS:: createSSLContext(const std::string& caPemFile, const std::string& certPemFile, const std::string& privateKeyPemFile, ConnectionHandle hdl) { std::shared_ptr<SSLContext> sslContext; try { sslContext = std::make_shared<SSLContext>(SSLContext::tlsv12); sslContext->set_verify_mode(websocketpp::lib::asio::ssl::verify_peer | websocketpp::lib::asio::ssl::verify_fail_if_no_peer_cert); sslContext->set_options(SSLContext::single_dh_use | SSLContext::no_sslv2 | SSLContext::no_sslv3 | SSLContext::no_tlsv1 | SSLContext::no_tlsv1_1 | SSLContext::no_compression); sslContext->load_verify_file(caPemFile); sslContext->use_certificate_file(certPemFile, SSLContext::pem); sslContext->use_private_key_file(privateKeyPemFile, SSLContext::pem); using VerifyContext = websocketpp::lib::asio::ssl::verify_context; auto getCNFromCertificate = [this, hdl](bool preverified, VerifyContext& ctx) { // getting cert out of the verification context X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); // extracting ownerId out of cert X509_NAME* certSubName = mococrw::openssl::_X509_get_subject_name(cert); mococrw::DistinguishedName distinguishedName = mococrw::DistinguishedName::fromX509Name(certSubName); const std::string ownerId(distinguishedName.commonName()); if (ownerId.empty()) { JOYNR_LOG_ERROR(logger, "Rejecting secure websocket connection because the ownerId " "(common name) of the TLS client certificate is empty."); return false; } // mapping the connection handler to the ownerId in clients map joynr::system::RoutingTypes::WebSocketClientAddress clientAddress; auto certEntry = CertEntry(std::move(clientAddress), ownerId); std::lock_guard<std::mutex> lock(clientsMutex); clients.emplace(hdl, std::move(certEntry)); return preverified; }; // read ownerId of client's certificate and store it in clients map sslContext->set_verify_callback(getCNFromCertificate); } catch (boost::system::system_error& e) { JOYNR_LOG_ERROR(logger, "Failed to initialize TLS session {}", e.what()); return nullptr; } return sslContext; } } // namespace joynr
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "libjoynrclustercontroller/websocket/WebSocketCcMessagingSkeletonTLS.h" #include <mococrw/distinguished_name.h> #include <mococrw/openssl_lib.h> #include <mococrw/openssl_wrap.h> #include <openssl/ssl.h> namespace joynr { WebSocketCcMessagingSkeletonTLS::WebSocketCcMessagingSkeletonTLS( boost::asio::io_service& ioService, std::shared_ptr<IMessageRouter> messageRouter, std::shared_ptr<WebSocketMessagingStubFactory> messagingStubFactory, const system::RoutingTypes::WebSocketAddress& serverAddress, const std::string& caPemFile, const std::string& certPemFile, const std::string& privateKeyPemFile) : WebSocketCcMessagingSkeleton<websocketpp::config::asio_tls>(ioService, messageRouter, messagingStubFactory) { // ensure that OpenSSL is correctly initialized ::SSL_library_init(); ::SSL_load_error_strings(); ::OpenSSL_add_all_algorithms(); endpoint.set_tls_init_handler([this, caPemFile, certPemFile, privateKeyPemFile]( ConnectionHandle hdl) -> std::shared_ptr<SSLContext> { return createSSLContext(caPemFile, certPemFile, privateKeyPemFile, hdl); }); startAccept(serverAddress.getPort()); } std::shared_ptr<WebSocketCcMessagingSkeletonTLS::SSLContext> WebSocketCcMessagingSkeletonTLS:: createSSLContext(const std::string& caPemFile, const std::string& certPemFile, const std::string& privateKeyPemFile, ConnectionHandle hdl) { std::shared_ptr<SSLContext> sslContext; try { sslContext = std::make_shared<SSLContext>(SSLContext::tlsv12); sslContext->set_verify_mode(websocketpp::lib::asio::ssl::verify_peer | websocketpp::lib::asio::ssl::verify_fail_if_no_peer_cert); sslContext->set_options(SSLContext::single_dh_use | SSLContext::no_sslv2 | SSLContext::no_sslv3 | SSLContext::no_tlsv1 | SSLContext::no_tlsv1_1 | SSLContext::no_compression); sslContext->load_verify_file(caPemFile); sslContext->use_certificate_file(certPemFile, SSLContext::pem); sslContext->use_private_key_file(privateKeyPemFile, SSLContext::pem); using VerifyContext = websocketpp::lib::asio::ssl::verify_context; auto getCNFromCertificate = [this, hdl](bool preverified, VerifyContext& ctx) { // getting cert out of the verification context X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); // extracting ownerId out of cert X509_NAME* certSubName = mococrw::openssl::_X509_get_subject_name(cert); mococrw::DistinguishedName distinguishedName = mococrw::DistinguishedName::fromX509Name(certSubName); const std::string ownerId(distinguishedName.commonName()); if (ownerId.empty()) { JOYNR_LOG_ERROR(logger, "Rejecting secure websocket connection because the ownerId " "(common name) of the TLS client certificate is empty."); return false; } // mapping the connection handler to the ownerId in clients map joynr::system::RoutingTypes::WebSocketClientAddress clientAddress; auto certEntry = CertEntry(std::move(clientAddress), ownerId); std::lock_guard<std::mutex> lock(clientsMutex); clients[std::move(hdl)] = std::move(certEntry); return preverified; }; // read ownerId of client's certificate and store it in clients map sslContext->set_verify_callback(getCNFromCertificate); } catch (boost::system::system_error& e) { JOYNR_LOG_ERROR(logger, "Failed to initialize TLS session {}", e.what()); return nullptr; } return sslContext; } } // namespace joynr
fix mapping of websocket connection to ownerId of certificate
[C++] fix mapping of websocket connection to ownerId of certificate The ssl verify callback (getCNFromCertificate) which extracts the ownerId of the TLS certificate is called for every certificate of the certificate chain starting with the ca certificate. The ownerId of the last certifcate of the certificate chain (= client certificate) has to be stored in the clients map. Map::emplace does not work because the former former mapping has to be replaced. Change-Id: I5275aeeb8f3b4747308eca1f7b01140755d841fb
C++
apache-2.0
bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr
09d8e564ec5292fe575bcb61cb7b4783f348c0ae
src/DGLWrapper/wa-soctors.cpp
src/DGLWrapper/wa-soctors.cpp
/* Copyright (C) 2013 Slawomir Cygan <[email protected]> * * 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. */ #ifdef WA_ANDROID_SO_CONSTRUCTORS #include <DGLCommon/os.h> #include "wa-soctors.h" #include "dl-intercept.h" //redef dlopen #include <mutex> #include <vector> #include <elf.h> #include <dlfcn.h> class StaticInitializerTest { public: StaticInitializerTest() { // something not so trivial for the compiler: m_TestVector.resize(3); } bool passed() { return m_TestVector.size() == 3; } private: std::vector<int> m_TestVector; } g_Test; std::mutex* g_mutex = NULL; // this is from /bionic/linker/linker.h #define SOINFO_NAME_LEN 128 struct soinfo { const char name[SOINFO_NAME_LEN]; Elf32_Phdr *phdr; int phnum; unsigned entry; unsigned base; // some more interesting stuff is here, but // we want to compute these manually, as soinfo layout may change in future. }; #ifndef DT_INIT_ARRAY #define DT_INIT_ARRAY 25 #endif #ifndef DT_INIT_ARRAYSZ #define DT_INIT_ARRAYSZ 27 #endif DGLWASoCtors::DGLWASoCtors() { if (g_Test.passed()) { return; } if (!g_mutex) { //as initializers where not called, mutex must be constructed manually on the heap g_mutex = new std::mutex(); } { std::lock_guard<std::mutex> guard(*g_mutex); //check again, this is essential for threads that were waiting. //Otherwise will call ctors multiple times. if (g_Test.passed()) { return; } Os::info( "Failed shared library constructor test. This is typical on " "Android < " "4.2-r1"); Os::info("Will try to run constructors manually now."); soinfo *info = reinterpret_cast<soinfo *>(dlopen("libdglwrapper.so", RTLD_NOW)); if (!info) { Os::fatal("Cannot dlopen libdglwrapper.so library"); } unsigned *dynamic = nullptr; Elf32_Phdr *phdr = info->phdr; int phnum = info->phnum; Os::info( "Trying to get .dynamic of libdglwrapper.so: base = 0x%x, phnum = " "%d", info->base, info->phnum); for (; phnum > 0; --phnum, ++phdr) { if (phdr->p_type == PT_DYNAMIC) { dynamic = (unsigned *)(info->base + phdr->p_vaddr); } } if (!dynamic || dynamic == (unsigned *)-1) { Os::fatal("Cannot get .dynamic section of libdglwrapper.so."); } else { Os::info("Found .dynamic at 0x%x", dynamic); } void (*init_func)(void) = nullptr; unsigned *init_array = nullptr; unsigned init_array_count = 0; for (unsigned *d = dynamic; *d; d++) { switch (*d++) { case DT_INIT: init_func = (void (*)(void))(info->base + *d); break; case DT_INIT_ARRAYSZ: init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr); break; case DT_INIT_ARRAY: init_array = (unsigned *)(info->base + *d); break; } } if (init_func) { Os::info("Found DT_INIT pointing at address 0x%x, Calling it", init_func); init_func(); } if (init_array_count && init_array) { Os::info("Found DT_INIT_ARRAY of size %d", init_array_count); for (unsigned i = 0; i < init_array_count; i++) { if (init_array[i] && init_array[i] != (unsigned)-1) { void (*func)() = (void (*)())init_array[i]; func(); } else { Os::info("DT_INIT_ARRAY[%d] is empty", i); } } } else { Os::info("DT_INIT_ARRAY not found. (trouble ahead)"); } if (!g_Test.passed()) { Os::fatal( "Tried to call constructors, but shared library constructor " "test, still fails."); } } //we will never use this mutex again. delete g_mutex; g_mutex = NULL; } #endif
/* Copyright (C) 2013 Slawomir Cygan <[email protected]> * * 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. */ #ifdef WA_ANDROID_SO_CONSTRUCTORS #include <DGLCommon/os.h> #include "wa-soctors.h" #include "dl-intercept.h" //redef dlopen #include <mutex> #include <vector> #include <elf.h> #include <dlfcn.h> class StaticInitializerTest { public: StaticInitializerTest() { // something not so trivial for the compiler: m_TestVector.resize(3); } bool passed() { return m_TestVector.size() == 3; } private: std::vector<int> m_TestVector; } g_Test; std::mutex* g_mutex = NULL; // this is from /bionic/linker/linker.h #define SOINFO_NAME_LEN 128 struct soinfo { const char name[SOINFO_NAME_LEN]; Elf32_Phdr *phdr; int phnum; unsigned entry; unsigned base; // some more interesting stuff is here, but // we want to compute these manually, as soinfo layout may change in future. }; #ifndef DT_INIT_ARRAY #define DT_INIT_ARRAY 25 #endif #ifndef DT_INIT_ARRAYSZ #define DT_INIT_ARRAYSZ 27 #endif DGLWASoCtors::DGLWASoCtors() { if (g_Test.passed()) { return; } if (!g_mutex) { //as initializers where not called, mutex must be constructed manually on the heap g_mutex = new std::mutex(); } { std::lock_guard<std::mutex> guard(*g_mutex); //check again, this is essential for threads that were waiting. //Otherwise will call ctors multiple times. if (g_Test.passed()) { return; } Os::info( "Failed shared library constructor test. This is typical on " "Android < " "4.2-r1"); Os::info("Will try to run constructors manually now."); soinfo *info = reinterpret_cast<soinfo *>(dlopen("libdglwrapper.so", RTLD_NOW)); if (!info) { Os::fatal("Cannot dlopen libdglwrapper.so library"); } unsigned *dynamic = nullptr; Elf32_Phdr *phdr = info->phdr; int phnum = info->phnum; Os::info( "Trying to get .dynamic of libdglwrapper.so: base = 0x%x, phnum = " "%d", info->base, info->phnum); for (; phnum > 0; --phnum, ++phdr) { if (phdr->p_type == PT_DYNAMIC) { dynamic = (unsigned *)(info->base + phdr->p_vaddr); } } if (!dynamic || dynamic == (unsigned *)-1) { Os::fatal("Cannot get .dynamic section of libdglwrapper.so."); } else { Os::info("Found .dynamic at 0x%x", dynamic); } void (*init_func)(void) = nullptr; unsigned *init_array = nullptr; unsigned init_array_count = 0; for (unsigned *d = dynamic; *d; d++) { switch (*d++) { case DT_INIT: init_func = (void (*)(void))(info->base + *d); break; case DT_INIT_ARRAYSZ: init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr); break; case DT_INIT_ARRAY: init_array = (unsigned *)(info->base + *d); break; } } if (init_func) { Os::info("Found DT_INIT pointing at address 0x%x, Calling it", init_func); init_func(); } if (init_array_count && init_array) { Os::info("Found DT_INIT_ARRAY of size %d", init_array_count); for (unsigned i = 0; i < init_array_count; i++) { if (init_array[i] && init_array[i] != (unsigned)-1) { OS_DEBUG("Calling DT_INIT_ARRAY[%d] (%p)", i, init_array[i]); void (*func)() = (void (*)())init_array[i]; func(); } else { Os::info("DT_INIT_ARRAY[%d] is empty", i); } } OS_DEBUG("Calling DT_INIT_ARRAY finished."); } else { Os::info("DT_INIT_ARRAY not found. (trouble ahead)"); } if (!g_Test.passed()) { Os::fatal( "Tried to call constructors, but shared library constructor " "test, still fails."); } OS_DEBUG("Shared library constructor test passed, leaving WA code."); } //we will never use this mutex again. delete g_mutex; g_mutex = NULL; } #endif
Add some more debugging info on Debug build in wa-soctors.
AndroidL: Add some more debugging info on Debug build in wa-soctors.
C++
apache-2.0
scygan/debugler,scygan/debugler,scygan/debugler,scygan/debugler
67c9727525dc1c9954a5a6d4ef16ffe6af23c9bc
src/DbCorpusReaderPrivate.cpp
src/DbCorpusReaderPrivate.cpp
#include <list> #include <sstream> #include <stdexcept> #include <string> #include <typeinfo> #include <dbxml/DbXml.hpp> #include <AlpinoCorpus/CorpusReader.hh> #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/IterImpl.hh> #include "DbCorpusReaderPrivate.hh" #include "util/url.hh" namespace db = DbXml; namespace alpinocorpus { /* begin() */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlContainer &container) { try { r = container.getAllDocuments( db::DBXML_LAZY_DOCS | db::DBXML_WELL_FORMED_ONLY ); } catch (db::XmlException const &e) { throw Error(e.what()); } } /* query */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlResults const &r_) : r(r_) { } /* end() */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlManager &mgr) : r(mgr.createResults()) // builds empty XmlResults { } IterImpl *DbCorpusReaderPrivate::DbIter::copy() const { // XXX - Copy constructor of XmlResults copies handle but not body. // The copyResults() method returns an XmlResults instance that // is eagerly evaluated. Is there a way to copy XmlResults, // retain the iterator position, and have it lazy? // No pointer members return new DbIter(*this); } bool DbCorpusReaderPrivate::DbIter::hasNext() { try { return r.hasNext(); } catch (db::XmlException const &e) { if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED) throw IterationInterrupted(); else throw Error(e.what()); } } /* operator++ */ Entry DbCorpusReaderPrivate::DbIter::next(CorpusReader const &) { db::XmlValue v; try { r.next(v); } catch (db::XmlException const &e) { if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED) throw IterationInterrupted(); else throw Error(e.what()); } std::string name; std::string value; if (v.isNode()) { value = v.getNodeValue(); try { db::XmlDocument doc = v.asDocument(); name = doc.getName(); } catch (db::XmlException &) { // Could not use node as a document. Why is there no isDocument() // method? } } else if (v.isString()) value = v.asString(); Entry e = {name, value}; return e; } DbCorpusReaderPrivate::QueryIter::QueryIter(db::XmlResults const &r, db::XmlQueryContext const &ctx) : DbIter(r), context(ctx) { } void DbCorpusReaderPrivate::QueryIter::interrupt() { context.interruptQuery(); } IterImpl *DbCorpusReaderPrivate::QueryIter::copy() const { // XXX - See DbIter::copy() return new QueryIter(*this); } DbCorpusReaderPrivate::DbCorpusReaderPrivate(std::string const &path) : mgr(db::DBXML_ALLOW_EXTERNAL_ACCESS), container() { try { db::XmlContainerConfig config; config.setReadOnly(true); container = mgr.openContainer(path, config); // Nasty: using a hard-coded alias to work use in the xpath queries. container.addAlias("corpus"); setNameAndCollection(path); } catch (db::XmlException const &e) { throw OpenError(path, e.what()); } } DbCorpusReaderPrivate::~DbCorpusReaderPrivate() { } CorpusReader::EntryIterator DbCorpusReaderPrivate::getEntries() const { return EntryIterator(new DbIter(container)); } std::string DbCorpusReaderPrivate::getName() const { return container.getName(); } bool DbCorpusReaderPrivate::validQuery(QueryDialect d, bool variables, std::string const &query) const { try { db::XmlQueryContext ctx = mgr.createQueryContext(); mgr.prepare(query, ctx); } catch (db::XmlException const &e) { return false; } return true; } std::string DbCorpusReaderPrivate::readEntry(std::string const &filename) const { try { db::XmlDocument doc(container.getDocument(filename, db::DBXML_LAZY_DOCS)); std::string content; return doc.getContent(content); } catch (db::XmlException const &e) { std::ostringstream msg; msg << "entry \"" << filename << "\" cannot be read from \"" << container.getName() << "\" (" << e.what() << ")"; throw Error(msg.str()); } } CorpusReader::EntryIterator DbCorpusReaderPrivate::runXPath(std::string const &query) const { return runXQuery(std::string("collection('corpus')" + query)); } CorpusReader::EntryIterator DbCorpusReaderPrivate::runXQuery(std::string const &query) const { // XXX use DBXML_DOCUMENT_PROJECTION and return to whole-doc containers? try { db::XmlQueryContext ctx = mgr.createQueryContext(db::XmlQueryContext::LiveValues, db::XmlQueryContext::Lazy); ctx.setDefaultCollection(collection); db::XmlResults r(mgr.query(query, ctx, db::DBXML_LAZY_DOCS | db::DBXML_WELL_FORMED_ONLY )); return EntryIterator(new QueryIter(r, ctx)); } catch (db::XmlException const &e) { throw Error(e.what()); } } /* * Set corpus name to container name; set collection to a usable collection * name. * * The collection name is used for querying. We set it to the absolute path * so we can still run queries after a chdir(). * For some reason, DB XML strips off a leading slash in the filename, * so we prepend an extra one. */ void DbCorpusReaderPrivate::setNameAndCollection(std::string const &path) { std::string uri = "/" + name(); collection = util::toPercentEncoding(uri); } }
#include <list> #include <sstream> #include <stdexcept> #include <string> #include <typeinfo> #include <dbxml/DbXml.hpp> #include <AlpinoCorpus/CorpusReader.hh> #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/IterImpl.hh> #include "DbCorpusReaderPrivate.hh" #include "util/url.hh" namespace db = DbXml; namespace alpinocorpus { /* begin() */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlContainer &container) { try { r = container.getAllDocuments( db::DBXML_LAZY_DOCS | db::DBXML_WELL_FORMED_ONLY ); } catch (db::XmlException const &e) { throw Error(e.what()); } } /* query */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlResults const &r_) : r(r_) { } /* end() */ DbCorpusReaderPrivate::DbIter::DbIter(db::XmlManager &mgr) : r(mgr.createResults()) // builds empty XmlResults { } IterImpl *DbCorpusReaderPrivate::DbIter::copy() const { // XXX - Copy constructor of XmlResults copies handle but not body. // The copyResults() method returns an XmlResults instance that // is eagerly evaluated. Is there a way to copy XmlResults, // retain the iterator position, and have it lazy? // No pointer members return new DbIter(*this); } bool DbCorpusReaderPrivate::DbIter::hasNext() { try { return r.hasNext(); } catch (db::XmlException const &e) { if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED) throw IterationInterrupted(); else throw Error(e.what()); } } /* operator++ */ Entry DbCorpusReaderPrivate::DbIter::next(CorpusReader const &) { db::XmlValue v; try { r.next(v); } catch (db::XmlException const &e) { if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED) throw IterationInterrupted(); else throw Error(e.what()); } std::string name; std::string value; if (v.isNode()) { try { db::XmlDocument doc = v.asDocument(); name = doc.getName(); } catch (db::XmlException &) { // Could not use node as a document. Why is there no isDocument() // method? } } value = v.asString(); Entry e = {name, value}; return e; } DbCorpusReaderPrivate::QueryIter::QueryIter(db::XmlResults const &r, db::XmlQueryContext const &ctx) : DbIter(r), context(ctx) { } void DbCorpusReaderPrivate::QueryIter::interrupt() { context.interruptQuery(); } IterImpl *DbCorpusReaderPrivate::QueryIter::copy() const { // XXX - See DbIter::copy() return new QueryIter(*this); } DbCorpusReaderPrivate::DbCorpusReaderPrivate(std::string const &path) : mgr(db::DBXML_ALLOW_EXTERNAL_ACCESS), container() { try { db::XmlContainerConfig config; config.setReadOnly(true); container = mgr.openContainer(path, config); // Nasty: using a hard-coded alias to work use in the xpath queries. container.addAlias("corpus"); setNameAndCollection(path); } catch (db::XmlException const &e) { throw OpenError(path, e.what()); } } DbCorpusReaderPrivate::~DbCorpusReaderPrivate() { } CorpusReader::EntryIterator DbCorpusReaderPrivate::getEntries() const { return EntryIterator(new DbIter(container)); } std::string DbCorpusReaderPrivate::getName() const { return container.getName(); } bool DbCorpusReaderPrivate::validQuery(QueryDialect d, bool variables, std::string const &query) const { try { db::XmlQueryContext ctx = mgr.createQueryContext(); mgr.prepare(query, ctx); } catch (db::XmlException const &e) { return false; } return true; } std::string DbCorpusReaderPrivate::readEntry(std::string const &filename) const { try { db::XmlDocument doc(container.getDocument(filename, db::DBXML_LAZY_DOCS)); std::string content; return doc.getContent(content); } catch (db::XmlException const &e) { std::ostringstream msg; msg << "entry \"" << filename << "\" cannot be read from \"" << container.getName() << "\" (" << e.what() << ")"; throw Error(msg.str()); } } CorpusReader::EntryIterator DbCorpusReaderPrivate::runXPath(std::string const &query) const { return runXQuery(std::string("collection('corpus')" + query)); } CorpusReader::EntryIterator DbCorpusReaderPrivate::runXQuery(std::string const &query) const { // XXX use DBXML_DOCUMENT_PROJECTION and return to whole-doc containers? try { db::XmlQueryContext ctx = mgr.createQueryContext(db::XmlQueryContext::LiveValues, db::XmlQueryContext::Lazy); ctx.setDefaultCollection(collection); db::XmlResults r(mgr.query(query, ctx, db::DBXML_LAZY_DOCS | db::DBXML_WELL_FORMED_ONLY )); return EntryIterator(new QueryIter(r, ctx)); } catch (db::XmlException const &e) { throw Error(e.what()); } } /* * Set corpus name to container name; set collection to a usable collection * name. * * The collection name is used for querying. We set it to the absolute path * so we can still run queries after a chdir(). * For some reason, DB XML strips off a leading slash in the filename, * so we prepend an extra one. */ void DbCorpusReaderPrivate::setNameAndCollection(std::string const &path) { std::string uri = "/" + name(); collection = util::toPercentEncoding(uri); } }
Return string-ified version of non-string nodes.
Return string-ified version of non-string nodes.
C++
lgpl-2.1
rug-compling/alpinocorpus,evdmade01/alpinocorpus,rug-compling/alpinocorpus,rug-compling/alpinocorpus,evdmade01/alpinocorpus
440e30089d1e42488d0244727b00f48e95b0c540
src/api/wayfire/view-transform.hpp
src/api/wayfire/view-transform.hpp
#ifndef VIEW_TRANSFORM_HPP #define VIEW_TRANSFORM_HPP #include <wayfire/view.hpp> #include <wayfire/opengl.hpp> #include <wayfire/debug.hpp> namespace wf { enum transformer_z_order_t { /* Simple 2D transforms */ TRANSFORMER_2D = 1, /* 3D transforms */ TRANSFORMER_3D = 2, /* Highlevels transforms and above do special effects, for ex. wobbly or fire */ TRANSFORMER_HIGHLEVEL = 500, /* Do not use Z oder blur or more, * except if you are willing to break it */ TRANSFORMER_BLUR = 999, }; class view_transformer_t { public: /** * Get the Z ordering of the transformer, e.g the order in which it should * be applied relative to the other transformers on the same view. * Higher numbers indicate that the transform should be applied later. * * @return The Z order of the transformer. */ virtual uint32_t get_z_order() = 0; /** * Transform the opaque region of the view. * * It must be guaranteed that the pixels part of the returned region are * opaque. The default implementation simply returns an empty region. * * @param box The bounding box of the view up to this transformer. * @param region The opaque region to transform. * * @return The transformed opaque region. */ virtual wf::region_t transform_opaque_region( wf::geometry_t box, wf::region_t region); /** * Transform a single point. * * @param view The bounding box of the view, in output-local * coordinates. * @param point The point to transform, in output-local coordinates. * * @return The point after transforming it, in output-local coordinates. */ virtual wf::pointf_t transform_point( wf::geometry_t view, wf::pointf_t point) = 0; /** * Reverse the transformation of the point. * * @param view The bounding box of the view, in output-local * coordinates. * @param point The point to untransform, in output-local coordinates. * * @return The point before after transforming it, in output-local * coordinates. If a reversal of the transformation is not possible, * return NaN. */ virtual wf::pointf_t untransform_point( wf::geometry_t view, wf::pointf_t point) = 0; /** * Compute the bounding box of the given region after transforming it. * * @param view The bounding box of the view, in output-local * coordinates. * @param region The region whose bounding box should be computed, in * output-local coordinates. * * @return The bounding box of region after transforming it, in * output-local coordinates. */ virtual wlr_box get_bounding_box(wf::geometry_t view, wlr_box region); /** * Render the indicated parts of the view. * * @param src_tex The texture of the view. * @param src_box The geometry of the view in output-local coordinates. * @param damage The region to repaint, clipped to the view's bounds. * It is in the framebuffer's damage coordinate system. * @param target_fb The framebuffer to draw the view to. It's geometry * is in output-local coordinates. * * The default implementation of render_with_damage() will simply * iterate over all rectangles in the damage region, apply framebuffer * transform to it and then call render_box(). Plugins can override * either of the functions. */ virtual void render_with_damage(wf::texture_t src_tex, wlr_box src_box, const wf::region_t& damage, const wf::framebuffer_t& target_fb); /** Same as render_with_damage(), but for a single rectangle of damage */ virtual void render_box(wf::texture_t src_tex, wlr_box src_box, wlr_box scissor_box, const wf::framebuffer_t& target_fb) {} virtual ~view_transformer_t() {} }; /* 2D transforms operate with a coordinate system centered at the * center of the main surface(the wayfire_view_t) */ class view_2D : public view_transformer_t { protected: wayfire_view view; public: float angle = 0.0f; float scale_x = 1.0f, scale_y = 1.0f; float translation_x = 0.0f, translation_y = 0.0f; float alpha = 1.0f; public: view_2D(wayfire_view view); virtual uint32_t get_z_order() override { return TRANSFORMER_2D; } wf::pointf_t transform_point( wf::geometry_t view, wf::pointf_t point) override; wf::pointf_t untransform_point( wf::geometry_t view, wf::pointf_t point) override; void render_box(wf::texture_t src_tex, wlr_box src_box, wlr_box scissor_box, const wf::framebuffer_t& target_fb) override; }; /* Those are centered relative to the view's bounding box */ class view_3D : public view_transformer_t { protected: wayfire_view view; public: glm::mat4 view_proj{1.0}, translation{1.0}, rotation{1.0}, scaling{1.0}; glm::vec4 color{1, 1, 1, 1}; glm::mat4 calculate_total_transform(); public: view_3D(wayfire_view view); virtual uint32_t get_z_order() override { return TRANSFORMER_3D; } wf::pointf_t transform_point( wf::geometry_t view, wf::pointf_t point) override; wf::pointf_t untransform_point( wf::geometry_t view, wf::pointf_t point) override; void render_box(wf::texture_t src_tex, wlr_box src_box, wlr_box scissor_box, const wf::framebuffer_t& target_fb) override; static const float fov; // PI / 8 static glm::mat4 default_view_matrix(); static glm::mat4 default_proj_matrix(); }; /* create a matrix which corresponds to the inverse of the given transform */ glm::mat4 get_output_matrix_from_transform(wl_output_transform transform); /* a matrix which can be used to render wf::geometry_t directly */ glm::mat4 output_get_projection(wf::output_t *output); } #endif /* end of include guard: VIEW_TRANSFORM_HPP */
#ifndef VIEW_TRANSFORM_HPP #define VIEW_TRANSFORM_HPP #include <wayfire/view.hpp> #include <wayfire/opengl.hpp> #include <wayfire/debug.hpp> namespace wf { enum transformer_z_order_t { /* Simple 2D transforms */ TRANSFORMER_2D = 1, /* 3D transforms */ TRANSFORMER_3D = 2, /* Highlevels transforms and above do special effects, for ex. wobbly or fire */ TRANSFORMER_HIGHLEVEL = 500, /* Do not use Z oder blur or more, * except if you are willing to break it */ TRANSFORMER_BLUR = 999, }; class view_transformer_t { public: /** * Get the Z ordering of the transformer, e.g the order in which it should * be applied relative to the other transformers on the same view. * Higher numbers indicate that the transform should be applied later. * * @return The Z order of the transformer. */ virtual uint32_t get_z_order() = 0; /** * Transform the opaque region of the view. * * It must be guaranteed that the pixels part of the returned region are * opaque. The default implementation simply returns an empty region. * * @param box The bounding box of the view up to this transformer. * @param region The opaque region to transform. * * @return The transformed opaque region. */ virtual wf::region_t transform_opaque_region( wf::geometry_t box, wf::region_t region); /** * Transform a single point. * * @param view The bounding box of the view, in output-local * coordinates. * @param point The point to transform, in output-local coordinates. * * @return The point after transforming it, in output-local coordinates. */ virtual wf::pointf_t transform_point( wf::geometry_t view, wf::pointf_t point) = 0; /** * Reverse the transformation of the point. * * @param view The bounding box of the view, in output-local * coordinates. * @param point The point to untransform, in output-local coordinates. * * @return The point before after transforming it, in output-local * coordinates. If a reversal of the transformation is not possible, * return NaN. */ virtual wf::pointf_t untransform_point( wf::geometry_t view, wf::pointf_t point) = 0; /** * Compute the bounding box of the given region after transforming it. * * @param view The bounding box of the view, in output-local * coordinates. * @param region The region whose bounding box should be computed, in * output-local coordinates. * * @return The bounding box of region after transforming it, in * output-local coordinates. */ virtual wlr_box get_bounding_box(wf::geometry_t view, wlr_box region); /** * Render the indicated parts of the view. * * @param src_tex The texture of the view. * @param src_box The bounding box of the view in output-local coordinates. * @param damage The region to repaint, clipped to the view's bounds. * It is in the framebuffer's damage coordinate system. * @param target_fb The framebuffer to draw the view to. It's geometry * is in output-local coordinates. * * The default implementation of render_with_damage() will simply * iterate over all rectangles in the damage region, apply framebuffer * transform to it and then call render_box(). Plugins can override * either of the functions. */ virtual void render_with_damage(wf::texture_t src_tex, wlr_box src_box, const wf::region_t& damage, const wf::framebuffer_t& target_fb); /** Same as render_with_damage(), but for a single rectangle of damage */ virtual void render_box(wf::texture_t src_tex, wlr_box src_box, wlr_box scissor_box, const wf::framebuffer_t& target_fb) {} virtual ~view_transformer_t() {} }; /* 2D transforms operate with a coordinate system centered at the * center of the main surface(the wayfire_view_t) */ class view_2D : public view_transformer_t { protected: wayfire_view view; public: float angle = 0.0f; float scale_x = 1.0f, scale_y = 1.0f; float translation_x = 0.0f, translation_y = 0.0f; float alpha = 1.0f; public: view_2D(wayfire_view view); virtual uint32_t get_z_order() override { return TRANSFORMER_2D; } wf::pointf_t transform_point( wf::geometry_t view, wf::pointf_t point) override; wf::pointf_t untransform_point( wf::geometry_t view, wf::pointf_t point) override; void render_box(wf::texture_t src_tex, wlr_box src_box, wlr_box scissor_box, const wf::framebuffer_t& target_fb) override; }; /* Those are centered relative to the view's bounding box */ class view_3D : public view_transformer_t { protected: wayfire_view view; public: glm::mat4 view_proj{1.0}, translation{1.0}, rotation{1.0}, scaling{1.0}; glm::vec4 color{1, 1, 1, 1}; glm::mat4 calculate_total_transform(); public: view_3D(wayfire_view view); virtual uint32_t get_z_order() override { return TRANSFORMER_3D; } wf::pointf_t transform_point( wf::geometry_t view, wf::pointf_t point) override; wf::pointf_t untransform_point( wf::geometry_t view, wf::pointf_t point) override; void render_box(wf::texture_t src_tex, wlr_box src_box, wlr_box scissor_box, const wf::framebuffer_t& target_fb) override; static const float fov; // PI / 8 static glm::mat4 default_view_matrix(); static glm::mat4 default_proj_matrix(); }; /* create a matrix which corresponds to the inverse of the given transform */ glm::mat4 get_output_matrix_from_transform(wl_output_transform transform); /* a matrix which can be used to render wf::geometry_t directly */ glm::mat4 output_get_projection(wf::output_t *output); } #endif /* end of include guard: VIEW_TRANSFORM_HPP */
fix view_transformer_t::render_with_damage docstring
api: fix view_transformer_t::render_with_damage docstring
C++
mit
ammen99/wayfire,ammen99/wayfire
13e123f4910040a5fff0f71e23c80997a83e43be
src/logjoin/LogJoin.cc
src/logjoin/LogJoin.cc
/* * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <assert.h> #include <fnord-base/exception.h> #include <fnord-base/inspect.h> #include <fnord-base/logging.h> #include <fnord-base/stringutil.h> #include <fnord-base/uri.h> #include <fnord-base/wallclock.h> #include <fnord-rpc/RPC.h> #include <fnord-json/json.h> #include <fnord-feeds/RemoteFeedFactory.h> #include <fnord-feeds/RemoteFeedWriter.h> #include "ItemRef.h" #include "JoinedQuery.h" #include "JoinedItemVisit.h" #include "CustomerNamespace.h" #include "logjoin/LogJoin.h" using namespace fnord; namespace cm { LogJoin::LogJoin( LogJoinShard shard, bool dry_run, bool enable_cache, LogJoinTarget* target) : shard_(shard), dry_run_(dry_run), target_(target), turbo_(false), enable_cache_(enable_cache) { addPixelParamID("dw_ab", 1); addPixelParamID("l", 2); addPixelParamID("u_x", 3); addPixelParamID("u_y", 4); addPixelParamID("is", 5); addPixelParamID("pg", 6); addPixelParamID("q_cat1", 7); addPixelParamID("q_cat2", 8); addPixelParamID("q_cat3", 9); addPixelParamID("slrid", 10); addPixelParamID("i", 11); addPixelParamID("s", 12); addPixelParamID("ml", 13); addPixelParamID("adm", 14); addPixelParamID("lgn", 15); addPixelParamID("slr", 16); addPixelParamID("lng", 17); addPixelParamID("dwnid", 18); addPixelParamID("fnm", 19); addPixelParamID("qstr~de", 100); addPixelParamID("qstr~pl", 101); addPixelParamID("qstr~en", 102); addPixelParamID("qstr~fr", 103); addPixelParamID("qstr~it", 104); addPixelParamID("qstr~nl", 105); addPixelParamID("qstr~es", 106); } size_t LogJoin::numSessions() const { return sessions_flush_times_.size(); } size_t LogJoin::cacheSize() const { return session_cache_.size(); } void LogJoin::insertLogline( const std::string& log_line, mdb::MDBTransaction* txn) { auto c_end = log_line.find("|"); if (c_end == std::string::npos) { RAISEF(kRuntimeError, "invalid logline: $0", log_line); } auto t_end = log_line.find("|", c_end + 1); if (t_end == std::string::npos) { RAISEF(kRuntimeError, "invalid logline: $0", log_line); } auto customer_key = log_line.substr(0, c_end); auto body = log_line.substr(t_end + 1); auto timestr = log_line.substr(c_end + 1, t_end - c_end - 1); fnord::DateTime time(std::stoul(timestr) * fnord::kMicrosPerSecond); insertLogline(customer_key, time, body, txn); } void LogJoin::insertLogline( const std::string& customer_key, const fnord::DateTime& time, const std::string& log_line, mdb::MDBTransaction* txn) { fnord::URI::ParamList params; fnord::URI::parseQueryString(log_line, &params); stat_loglines_total_.incr(1); try { /* extract uid (userid) and eid (eventid) */ std::string c; if (!fnord::URI::getParam(params, "c", &c)) { RAISE(kParseError, "c param is missing"); } auto c_s = c.find("~"); if (c_s == std::string::npos) { RAISE(kParseError, "c param is invalid"); } std::string uid = c.substr(0, c_s); std::string eid = c.substr(c_s + 1, c.length() - c_s - 1); if (uid.length() == 0 || eid.length() == 0) { RAISE(kParseError, "c param is invalid"); } if (!shard_.testUID(uid)) { #ifndef NDEBUG fnord::logTrace( "cm.logjoin", "dropping logline with uid=$0 because it does not match my shard", uid); #endif return; } std::string evtype; if (!fnord::URI::getParam(params, "e", &evtype) || evtype.length() != 1) { RAISE(kParseError, "e param is missing"); } if (evtype.length() != 1) { RAISE(kParseError, "e param invalid"); } /* process event */ switch (evtype[0]) { case 'q': case 'v': case 'c': case 'u': break; default: RAISE(kParseError, "invalid e param"); }; URI::ParamList stored_params; for (const auto& p : params) { if (p.first == "c" || p.first == "e" || p.first == "v") { continue; } stored_params.emplace_back(p); } appendToSession(customer_key, time, uid, eid, evtype, stored_params, txn); } catch (...) { stat_loglines_invalid_.incr(1); throw; } } void LogJoin::appendToSession( const std::string& customer_key, const fnord::DateTime& time, const std::string& uid, const std::string& evid, const std::string& evtype, const Vector<Pair<String, String>>& logline, mdb::MDBTransaction* txn) { auto flush_at = time.unixMicros() + kSessionIdleTimeoutSeconds * fnord::kMicrosPerSecond; bool new_session = sessions_flush_times_.count(uid) == 0; sessions_flush_times_.emplace(uid, flush_at); util::BinaryMessageWriter buf; buf.appendVarUInt(time.unixMicros() / kMicrosPerSecond); buf.appendVarUInt(evid.length()); buf.append(evid.data(), evid.length()); for (const auto& p : logline) { buf.appendVarUInt(getPixelParamID(p.first)); buf.appendVarUInt(p.second.size()); buf.append(p.second.data(), p.second.size()); } auto evkey = uid + "~" + evtype; txn->insert(evkey.data(), evkey.size(), buf.data(), buf.size()); if (new_session) { txn->insert(uid + "~cust", customer_key); } } void LogJoin::flush(mdb::MDBTransaction* txn, DateTime stream_time_) { auto stream_time = stream_time_.unixMicros(); for (auto iter = sessions_flush_times_.begin(); iter != sessions_flush_times_.end();) { if (iter->second.unixMicros() < stream_time) { flushSession(iter->first, stream_time, txn); iter = sessions_flush_times_.erase(iter); } else { ++iter; } } } void LogJoin::flushSession( const std::string uid, DateTime stream_time, mdb::MDBTransaction* txn) { auto cursor = txn->getCursor(); TrackedSession session; session.uid = uid; Buffer key; Buffer value; bool eof = false; for (int i = 0; ; ++i) { if (i == 0) { key.append(uid); if (!cursor->getFirstOrGreater(&key, &value)) { break; } } else { if (!cursor->getNext(&key, &value)) { break; } } auto key_str = key.toString(); if (!StringUtil::beginsWith(key_str, uid)) { break; } if (StringUtil::endsWith(key_str, "~cust")) { session.customer_key = value.toString(); } else { auto evtype = key_str.substr(uid.length() + 1); util::BinaryMessageReader reader(value.data(), value.size()); auto time = reader.readVarUInt(); auto evid_len = reader.readVarUInt(); auto evid = String((char*) reader.read(evid_len), evid_len); try { URI::ParamList logline; while (reader.remaining() > 0) { auto key = getPixelParamName(reader.readVarUInt()); auto len = reader.readVarUInt(); logline.emplace_back(key, String((char*) reader.read(len), len)); } session.insertLogline(time, evtype, evid, logline); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "invalid logline"); stat_loglines_invalid_.incr(1); } } txn->del(key); } cursor->close(); if (session.customer_key.length() == 0) { fnord::logError("cm.logjoin", "missing customer key for: $0", uid); return; } try { target_->onSession(txn, session); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "LogJoinTarget::onSession crashed"); } stat_joined_sessions_.incr(1); } void LogJoin::importTimeoutList(mdb::MDBTransaction* txn) { Buffer key; Buffer value; int n = 0; auto cursor = txn->getCursor(); for (;;) { bool eof; if (n++ == 0) { eof = !cursor->getFirst(&key, &value); } else { eof = !cursor->getNext(&key, &value); } if (eof) { break; } if (StringUtil::beginsWith(key.toString(), "__")) { continue; } auto sid = key.toString(); if (StringUtil::endsWith(sid, "~cust")) { continue; } auto evtype = sid.substr(sid.find("~") + 1); sid.erase(sid.end() - evtype.size() - 1, sid.end()); util::BinaryMessageReader reader(value.data(), value.size()); auto time = reader.readVarUInt(); auto ftime = (time + kSessionIdleTimeoutSeconds) * fnord::kMicrosPerSecond; auto old_ftime = sessions_flush_times_.find(sid); if (old_ftime == sessions_flush_times_.end() || old_ftime->second.unixMicros() < ftime) { sessions_flush_times_.emplace(sid, ftime); } } cursor->close(); } void LogJoin::addPixelParamID(const String& param, uint32_t id) { pixel_param_ids_[param] = id; pixel_param_names_[id] = param; } uint32_t LogJoin::getPixelParamID(const String& param) const { auto p = pixel_param_ids_.find(param); if (p == pixel_param_ids_.end()) { RAISEF(kIndexError, "invalid pixel param: $0", param); } return p->second; } const String& LogJoin::getPixelParamName(uint32_t id) const { auto p = pixel_param_names_.find(id); if (p == pixel_param_names_.end()) { RAISEF(kIndexError, "invalid pixel param: $0", id); } return p->second; } void LogJoin::exportStats(const std::string& prefix) { exportStat( StringUtil::format("$0/$1", prefix, "loglines_total"), &stat_loglines_total_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/$1", prefix, "loglines_invalid"), &stat_loglines_invalid_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/$1", prefix, "joined_sessions"), &stat_joined_sessions_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/$1", prefix, "joined_queries"), &stat_joined_queries_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/$1", prefix, "joined_item_visits"), &stat_joined_item_visits_, fnord::stats::ExportMode::EXPORT_DELTA); } void LogJoin::setTurbo(bool turbo) { turbo_ = turbo; } } // namespace cm
/* * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <assert.h> #include <fnord-base/exception.h> #include <fnord-base/inspect.h> #include <fnord-base/logging.h> #include <fnord-base/stringutil.h> #include <fnord-base/uri.h> #include <fnord-base/wallclock.h> #include <fnord-rpc/RPC.h> #include <fnord-json/json.h> #include <fnord-feeds/RemoteFeedFactory.h> #include <fnord-feeds/RemoteFeedWriter.h> #include "ItemRef.h" #include "JoinedQuery.h" #include "JoinedItemVisit.h" #include "CustomerNamespace.h" #include "logjoin/LogJoin.h" using namespace fnord; namespace cm { LogJoin::LogJoin( LogJoinShard shard, bool dry_run, bool enable_cache, LogJoinTarget* target) : shard_(shard), dry_run_(dry_run), target_(target), turbo_(false), enable_cache_(enable_cache) { addPixelParamID("dw_ab", 1); addPixelParamID("l", 2); addPixelParamID("u_x", 3); addPixelParamID("u_y", 4); addPixelParamID("is", 5); addPixelParamID("pg", 6); addPixelParamID("q_cat1", 7); addPixelParamID("q_cat2", 8); addPixelParamID("q_cat3", 9); addPixelParamID("slrid", 10); addPixelParamID("i", 11); addPixelParamID("s", 12); addPixelParamID("ml", 13); addPixelParamID("adm", 14); addPixelParamID("lgn", 15); addPixelParamID("slr", 16); addPixelParamID("lng", 17); addPixelParamID("dwnid", 18); addPixelParamID("fnm", 19); addPixelParamID("qstr~de", 100); addPixelParamID("qstr~pl", 101); addPixelParamID("qstr~en", 102); addPixelParamID("qstr~fr", 103); addPixelParamID("qstr~it", 104); addPixelParamID("qstr~nl", 105); addPixelParamID("qstr~es", 106); } size_t LogJoin::numSessions() const { return sessions_flush_times_.size(); } size_t LogJoin::cacheSize() const { return session_cache_.size(); } void LogJoin::insertLogline( const std::string& log_line, mdb::MDBTransaction* txn) { auto c_end = log_line.find("|"); if (c_end == std::string::npos) { RAISEF(kRuntimeError, "invalid logline: $0", log_line); } auto t_end = log_line.find("|", c_end + 1); if (t_end == std::string::npos) { RAISEF(kRuntimeError, "invalid logline: $0", log_line); } auto customer_key = log_line.substr(0, c_end); auto body = log_line.substr(t_end + 1); auto timestr = log_line.substr(c_end + 1, t_end - c_end - 1); fnord::DateTime time(std::stoul(timestr) * fnord::kMicrosPerSecond); insertLogline(customer_key, time, body, txn); } void LogJoin::insertLogline( const std::string& customer_key, const fnord::DateTime& time, const std::string& log_line, mdb::MDBTransaction* txn) { fnord::URI::ParamList params; fnord::URI::parseQueryString(log_line, &params); stat_loglines_total_.incr(1); try { /* extract uid (userid) and eid (eventid) */ std::string c; if (!fnord::URI::getParam(params, "c", &c)) { RAISE(kParseError, "c param is missing"); } auto c_s = c.find("~"); if (c_s == std::string::npos) { RAISE(kParseError, "c param is invalid"); } std::string uid = c.substr(0, c_s); std::string eid = c.substr(c_s + 1, c.length() - c_s - 1); if (uid.length() == 0 || eid.length() == 0) { RAISE(kParseError, "c param is invalid"); } if (!shard_.testUID(uid)) { #ifndef NDEBUG fnord::logTrace( "cm.logjoin", "dropping logline with uid=$0 because it does not match my shard", uid); #endif return; } std::string evtype; if (!fnord::URI::getParam(params, "e", &evtype) || evtype.length() != 1) { RAISE(kParseError, "e param is missing"); } if (evtype.length() != 1) { RAISE(kParseError, "e param invalid"); } /* process event */ switch (evtype[0]) { case 'q': case 'v': case 'c': case 'u': break; default: RAISE(kParseError, "invalid e param"); }; URI::ParamList stored_params; for (const auto& p : params) { if (p.first == "c" || p.first == "e" || p.first == "v") { continue; } stored_params.emplace_back(p); } appendToSession(customer_key, time, uid, eid, evtype, stored_params, txn); } catch (...) { stat_loglines_invalid_.incr(1); throw; } } void LogJoin::appendToSession( const std::string& customer_key, const fnord::DateTime& time, const std::string& uid, const std::string& evid, const std::string& evtype, const Vector<Pair<String, String>>& logline, mdb::MDBTransaction* txn) { auto flush_at = time.unixMicros() + kSessionIdleTimeoutSeconds * fnord::kMicrosPerSecond; bool new_session = sessions_flush_times_.count(uid) == 0; sessions_flush_times_.emplace(uid, flush_at); util::BinaryMessageWriter buf; buf.appendVarUInt(time.unixMicros() / kMicrosPerSecond); buf.appendVarUInt(evid.length()); buf.append(evid.data(), evid.length()); for (const auto& p : logline) { buf.appendVarUInt(getPixelParamID(p.first)); buf.appendVarUInt(p.second.size()); buf.append(p.second.data(), p.second.size()); } auto evkey = uid + "~" + evtype; txn->insert(evkey.data(), evkey.size(), buf.data(), buf.size()); txn->update(uid + "~cust", customer_key); } void LogJoin::flush(mdb::MDBTransaction* txn, DateTime stream_time_) { auto stream_time = stream_time_.unixMicros(); for (auto iter = sessions_flush_times_.begin(); iter != sessions_flush_times_.end();) { if (iter->second.unixMicros() < stream_time) { flushSession(iter->first, stream_time, txn); iter = sessions_flush_times_.erase(iter); } else { ++iter; } } } void LogJoin::flushSession( const std::string uid, DateTime stream_time, mdb::MDBTransaction* txn) { auto cursor = txn->getCursor(); TrackedSession session; session.uid = uid; Buffer key; Buffer value; bool eof = false; for (int i = 0; ; ++i) { if (i == 0) { key.append(uid); if (!cursor->getFirstOrGreater(&key, &value)) { break; } } else { if (!cursor->getNext(&key, &value)) { break; } } auto key_str = key.toString(); if (!StringUtil::beginsWith(key_str, uid)) { break; } if (StringUtil::endsWith(key_str, "~cust")) { session.customer_key = value.toString(); } else { auto evtype = key_str.substr(uid.length() + 1); util::BinaryMessageReader reader(value.data(), value.size()); auto time = reader.readVarUInt(); auto evid_len = reader.readVarUInt(); auto evid = String((char*) reader.read(evid_len), evid_len); try { URI::ParamList logline; while (reader.remaining() > 0) { auto key = getPixelParamName(reader.readVarUInt()); auto len = reader.readVarUInt(); logline.emplace_back(key, String((char*) reader.read(len), len)); } session.insertLogline(time, evtype, evid, logline); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "invalid logline"); stat_loglines_invalid_.incr(1); } } txn->del(key); } cursor->close(); if (session.customer_key.length() == 0) { fnord::logError("cm.logjoin", "missing customer key for: $0", uid); return; } try { target_->onSession(txn, session); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "LogJoinTarget::onSession crashed"); } stat_joined_sessions_.incr(1); } void LogJoin::importTimeoutList(mdb::MDBTransaction* txn) { Buffer key; Buffer value; int n = 0; auto cursor = txn->getCursor(); for (;;) { bool eof; if (n++ == 0) { eof = !cursor->getFirst(&key, &value); } else { eof = !cursor->getNext(&key, &value); } if (eof) { break; } if (StringUtil::beginsWith(key.toString(), "__")) { continue; } auto sid = key.toString(); if (StringUtil::endsWith(sid, "~cust")) { continue; } auto evtype = sid.substr(sid.find("~") + 1); sid.erase(sid.end() - evtype.size() - 1, sid.end()); util::BinaryMessageReader reader(value.data(), value.size()); auto time = reader.readVarUInt(); auto ftime = (time + kSessionIdleTimeoutSeconds) * fnord::kMicrosPerSecond; auto old_ftime = sessions_flush_times_.find(sid); if (old_ftime == sessions_flush_times_.end() || old_ftime->second.unixMicros() < ftime) { sessions_flush_times_.emplace(sid, ftime); } } cursor->close(); } void LogJoin::addPixelParamID(const String& param, uint32_t id) { pixel_param_ids_[param] = id; pixel_param_names_[id] = param; } uint32_t LogJoin::getPixelParamID(const String& param) const { auto p = pixel_param_ids_.find(param); if (p == pixel_param_ids_.end()) { RAISEF(kIndexError, "invalid pixel param: $0", param); } return p->second; } const String& LogJoin::getPixelParamName(uint32_t id) const { auto p = pixel_param_names_.find(id); if (p == pixel_param_names_.end()) { RAISEF(kIndexError, "invalid pixel param: $0", id); } return p->second; } void LogJoin::exportStats(const std::string& prefix) { exportStat( StringUtil::format("$0/$1", prefix, "loglines_total"), &stat_loglines_total_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/$1", prefix, "loglines_invalid"), &stat_loglines_invalid_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/$1", prefix, "joined_sessions"), &stat_joined_sessions_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/$1", prefix, "joined_queries"), &stat_joined_queries_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/$1", prefix, "joined_item_visits"), &stat_joined_item_visits_, fnord::stats::ExportMode::EXPORT_DELTA); } void LogJoin::setTurbo(bool turbo) { turbo_ = turbo; } } // namespace cm
update cust on every logline
update cust on every logline
C++
agpl-3.0
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
0f17edb12ed9a17fa4a0e56774ea708507b99057
RawSpeed/CiffIFD.cpp
RawSpeed/CiffIFD.cpp
#include "StdAfx.h" #include "CiffIFD.h" #include "CiffParser.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2014 Pedro Côrte-Real This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { CiffIFD::CiffIFD(FileMap* f, uint32 start, uint32 end) { mFile = f; uint32 size = f->getSize(); uint32 valuedata_size = *(uint32 *) f->getData(end-4, 4); ushort16 dircount = *(ushort16 *) f->getData(start+valuedata_size, 2); // fprintf(stderr, "Found %d entries between %d and %d after %d data bytes\n", // dircount, start, end, valuedata_size); for (uint32 i = 0; i < dircount; i++) { CiffEntry *t = new CiffEntry(f, start, start+valuedata_size+2+i*10); if (t->type == CIFF_SUB1 || t->type == CIFF_SUB2) { try { mSubIFD.push_back(new CiffIFD(f, t->data_offset, t->data_offset+t->count)); delete(t); } catch (CiffParserException) { // Unparsable subifds are added as entries mEntry[t->tag] = t; } } else { mEntry[t->tag] = t; } } } CiffIFD::~CiffIFD(void) { for (map<CiffTag, CiffEntry*>::iterator i = mEntry.begin(); i != mEntry.end(); ++i) { delete((*i).second); } mEntry.clear(); for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { delete(*i); } mSubIFD.clear(); } bool CiffIFD::hasEntryRecursive(CiffTag tag) { if (mEntry.find(tag) != mEntry.end()) return TRUE; for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { if ((*i)->hasEntryRecursive(tag)) return TRUE; } return false; } vector<CiffIFD*> CiffIFD::getIFDsWithTag(CiffTag tag) { vector<CiffIFD*> matchingIFDs; if (mEntry.find(tag) != mEntry.end()) { matchingIFDs.push_back(this); } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { vector<CiffIFD*> t = (*i)->getIFDsWithTag(tag); for (uint32 j = 0; j < t.size(); j++) { matchingIFDs.push_back(t[j]); } } return matchingIFDs; } vector<CiffIFD*> CiffIFD::getIFDsWithTagWhere(CiffTag tag, uint32 isValue) { vector<CiffIFD*> matchingIFDs; if (mEntry.find(tag) != mEntry.end()) { CiffEntry* entry = mEntry[tag]; if (entry->isInt() && entry->getInt() == isValue) matchingIFDs.push_back(this); } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { vector<CiffIFD*> t = (*i)->getIFDsWithTag(tag); for (uint32 j = 0; j < t.size(); j++) { matchingIFDs.push_back(t[j]); } } return matchingIFDs; } vector<CiffIFD*> CiffIFD::getIFDsWithTagWhere(CiffTag tag, string isValue) { vector<CiffIFD*> matchingIFDs; if (mEntry.find(tag) != mEntry.end()) { CiffEntry* entry = mEntry[tag]; if (entry->isString() && 0 == entry->getString().compare(isValue)) matchingIFDs.push_back(this); } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { vector<CiffIFD*> t = (*i)->getIFDsWithTag(tag); for (uint32 j = 0; j < t.size(); j++) { matchingIFDs.push_back(t[j]); } } return matchingIFDs; } CiffEntry* CiffIFD::getEntryRecursive(CiffTag tag) { if (mEntry.find(tag) != mEntry.end()) { return mEntry[tag]; } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { CiffEntry* entry = (*i)->getEntryRecursive(tag); if (entry) return entry; } return NULL; } CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag, uint32 isValue) { if (mEntry.find(tag) != mEntry.end()) { CiffEntry* entry = mEntry[tag]; if (entry->isInt() && entry->getInt() == isValue) return entry; } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { CiffEntry* entry = (*i)->getEntryRecursive(tag); if (entry) return entry; } return NULL; } CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag, string isValue) { if (mEntry.find(tag) != mEntry.end()) { CiffEntry* entry = mEntry[tag]; if (entry->isString() && 0 == entry->getString().compare(isValue)) return entry; } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { CiffEntry* entry = (*i)->getEntryRecursive(tag); if (entry) return entry; } return NULL; } CiffEntry* CiffIFD::getEntry(CiffTag tag) { if (mEntry.find(tag) != mEntry.end()) { return mEntry[tag]; } ThrowCPE("CiffIFD: CIFF Parser entry 0x%x not found.", tag); return 0; } bool CiffIFD::hasEntry(CiffTag tag) { return mEntry.find(tag) != mEntry.end(); } } // namespace RawSpeed
#include "StdAfx.h" #include "CiffIFD.h" #include "CiffParser.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2014 Pedro Côrte-Real This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { CiffIFD::CiffIFD(FileMap* f, uint32 start, uint32 end) { mFile = f; uint32 valuedata_size = *(uint32 *) f->getData(end-4, 4); ushort16 dircount = *(ushort16 *) f->getData(start+valuedata_size, 2); // fprintf(stderr, "Found %d entries between %d and %d after %d data bytes\n", // dircount, start, end, valuedata_size); for (uint32 i = 0; i < dircount; i++) { CiffEntry *t = new CiffEntry(f, start, start+valuedata_size+2+i*10); if (t->type == CIFF_SUB1 || t->type == CIFF_SUB2) { try { mSubIFD.push_back(new CiffIFD(f, t->data_offset, t->data_offset+t->count)); delete(t); } catch (CiffParserException) { // Unparsable subifds are added as entries mEntry[t->tag] = t; } } else { mEntry[t->tag] = t; } } } CiffIFD::~CiffIFD(void) { for (map<CiffTag, CiffEntry*>::iterator i = mEntry.begin(); i != mEntry.end(); ++i) { delete((*i).second); } mEntry.clear(); for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { delete(*i); } mSubIFD.clear(); } bool CiffIFD::hasEntryRecursive(CiffTag tag) { if (mEntry.find(tag) != mEntry.end()) return TRUE; for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { if ((*i)->hasEntryRecursive(tag)) return TRUE; } return false; } vector<CiffIFD*> CiffIFD::getIFDsWithTag(CiffTag tag) { vector<CiffIFD*> matchingIFDs; if (mEntry.find(tag) != mEntry.end()) { matchingIFDs.push_back(this); } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { vector<CiffIFD*> t = (*i)->getIFDsWithTag(tag); for (uint32 j = 0; j < t.size(); j++) { matchingIFDs.push_back(t[j]); } } return matchingIFDs; } vector<CiffIFD*> CiffIFD::getIFDsWithTagWhere(CiffTag tag, uint32 isValue) { vector<CiffIFD*> matchingIFDs; if (mEntry.find(tag) != mEntry.end()) { CiffEntry* entry = mEntry[tag]; if (entry->isInt() && entry->getInt() == isValue) matchingIFDs.push_back(this); } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { vector<CiffIFD*> t = (*i)->getIFDsWithTag(tag); for (uint32 j = 0; j < t.size(); j++) { matchingIFDs.push_back(t[j]); } } return matchingIFDs; } vector<CiffIFD*> CiffIFD::getIFDsWithTagWhere(CiffTag tag, string isValue) { vector<CiffIFD*> matchingIFDs; if (mEntry.find(tag) != mEntry.end()) { CiffEntry* entry = mEntry[tag]; if (entry->isString() && 0 == entry->getString().compare(isValue)) matchingIFDs.push_back(this); } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { vector<CiffIFD*> t = (*i)->getIFDsWithTag(tag); for (uint32 j = 0; j < t.size(); j++) { matchingIFDs.push_back(t[j]); } } return matchingIFDs; } CiffEntry* CiffIFD::getEntryRecursive(CiffTag tag) { if (mEntry.find(tag) != mEntry.end()) { return mEntry[tag]; } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { CiffEntry* entry = (*i)->getEntryRecursive(tag); if (entry) return entry; } return NULL; } CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag, uint32 isValue) { if (mEntry.find(tag) != mEntry.end()) { CiffEntry* entry = mEntry[tag]; if (entry->isInt() && entry->getInt() == isValue) return entry; } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { CiffEntry* entry = (*i)->getEntryRecursive(tag); if (entry) return entry; } return NULL; } CiffEntry* CiffIFD::getEntryRecursiveWhere(CiffTag tag, string isValue) { if (mEntry.find(tag) != mEntry.end()) { CiffEntry* entry = mEntry[tag]; if (entry->isString() && 0 == entry->getString().compare(isValue)) return entry; } for (vector<CiffIFD*>::iterator i = mSubIFD.begin(); i != mSubIFD.end(); ++i) { CiffEntry* entry = (*i)->getEntryRecursive(tag); if (entry) return entry; } return NULL; } CiffEntry* CiffIFD::getEntry(CiffTag tag) { if (mEntry.find(tag) != mEntry.end()) { return mEntry[tag]; } ThrowCPE("CiffIFD: CIFF Parser entry 0x%x not found.", tag); return 0; } bool CiffIFD::hasEntry(CiffTag tag) { return mEntry.find(tag) != mEntry.end(); } } // namespace RawSpeed
Remove now unused variable
Remove now unused variable
C++
lgpl-2.1
LebedevRI/rawspeed,darktable-org/rawspeed,klauspost/rawspeed,darktable-org/rawspeed,anarsoul/rawspeed,anarsoul/rawspeed,anarsoul/rawspeed,LebedevRI/rawspeed,darktable-org/rawspeed,LebedevRI/rawspeed,klauspost/rawspeed,LebedevRI/rawspeed,darktable-org/rawspeed,LebedevRI/rawspeed,darktable-org/rawspeed
1cddd7817d0ec3e1e13aafc4fee30f8049de92b5
src/system/OS_info/os_info_windows.cpp
src/system/OS_info/os_info_windows.cpp
// infoware - C++ System information Library // // Written in 2016-2019 by nabijaczleweli <[email protected]> and ThePhD <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/> #ifdef _WIN32 #include "infoware/detail/memory.hpp" #include "infoware/detail/scope.hpp" #include "infoware/system.hpp" #include <codecvt> #include <locale> #include <memory> #include <string> #define WIN32_LEAN_AND_MEAN #include <wbemidl.h> #include <windows.h> static std::string ConvertBSTRToString(BSTR pSrc) { if(!pSrc) return {}; // convert even embeded NUL const auto src_len = SysStringLen(pSrc); return std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>{}.to_bytes(pSrc, pSrc + src_len); } // Use WIM to acquire Win32_OperatingSystem.Name // https://msdn.microsoft.com/en-us/library/aa390423(v=vs.85).aspx static std::string version_name() { if(FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return {}; iware::detail::quickscope_wrapper com_uninitialiser{CoUninitialize}; const auto init_result = CoInitializeSecurity(nullptr, -1, nullptr, nullptr, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE, nullptr); if(FAILED(init_result) && init_result != RPC_E_TOO_LATE) return {}; IWbemLocator* wbem_loc_raw; if(FAILED(CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast<void**>(&wbem_loc_raw)))) return {}; std::unique_ptr<IWbemLocator, iware::detail::release_deleter> wbem_loc(wbem_loc_raw); IWbemServices* wbem_services_raw; wchar_t network_resource[] = LR"(ROOT\CIMV2)"; if(FAILED(wbem_loc->ConnectServer(network_resource, nullptr, nullptr, 0, 0, 0, 0, &wbem_services_raw))) return {}; std::unique_ptr<IWbemServices, iware::detail::release_deleter> wbem_services(wbem_services_raw); if(FAILED(CoSetProxyBlanket(wbem_services.get(), RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, nullptr, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE))) return {}; IEnumWbemClassObject* query_iterator_raw; wchar_t query_lang[] = L"WQL"; wchar_t query[] = L"SELECT Name FROM Win32_OperatingSystem"; if(FAILED(wbem_services->ExecQuery(query_lang, query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, nullptr, &query_iterator_raw))) return {}; std::unique_ptr<IEnumWbemClassObject, iware::detail::release_deleter> query_iterator(query_iterator_raw); std::string ret; while(query_iterator) { IWbemClassObject* value_raw; unsigned long iter_result; query_iterator->Next(static_cast<LONG>(WBEM_INFINITE), 1, &value_raw, &iter_result); if(!iter_result) break; std::unique_ptr<IWbemClassObject, iware::detail::release_deleter> value(value_raw); VARIANT val; value->Get(L"Name", 0, &val, 0, 0); iware::detail::quickscope_wrapper val_destructor{[&] { VariantClear(&val); }}; ret = ConvertBSTRToString(val.bstrVal); } return ret.substr(0, ret.find('|')); } iware::system::OS_info_t iware::system::OS_info() { const auto kernel_version = iware::system::kernel_info(); return {"Windows NT", version_name(), kernel_version.major, kernel_version.minor, kernel_version.patch, kernel_version.build_number}; } #endif
// infoware - C++ System information Library // // Written in 2016-2019 by nabijaczleweli <[email protected]> and ThePhD <[email protected]> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/> #ifdef _WIN32 #include "infoware/detail/memory.hpp" #include "infoware/detail/scope.hpp" #include "infoware/system.hpp" #include <memory> #include <string> #define WIN32_LEAN_AND_MEAN #include <wbemidl.h> #include <windows.h> static std::string ConvertBSTRToString(BSTR pSrc) { if(!pSrc) return {}; const UINT src_len = SysStringLen(pSrc); std::string ret; if(const int len = WideCharToMultiByte(CP_ACP, 0, pSrc, static_cast<int>(src_len), NULL, 0, 0, 0)) { ret.resize(static_cast<size_t>(len), '\0'); const int err = WideCharToMultiByte(CP_ACP, 0, pSrc, static_cast<int>(src_len), &ret[0], len, 0, 0); if(err == 0) { ret.clear(); } } return ret; } // Use WIM to acquire Win32_OperatingSystem.Name // https://msdn.microsoft.com/en-us/library/aa390423(v=vs.85).aspx static std::string version_name() { if(FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return {}; iware::detail::quickscope_wrapper com_uninitialiser{CoUninitialize}; const auto init_result = CoInitializeSecurity(nullptr, -1, nullptr, nullptr, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE, nullptr); if(FAILED(init_result) && init_result != RPC_E_TOO_LATE) return {}; IWbemLocator* wbem_loc_raw; if(FAILED(CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast<void**>(&wbem_loc_raw)))) return {}; std::unique_ptr<IWbemLocator, iware::detail::release_deleter> wbem_loc(wbem_loc_raw); IWbemServices* wbem_services_raw; wchar_t network_resource[] = LR"(ROOT\CIMV2)"; if(FAILED(wbem_loc->ConnectServer(network_resource, nullptr, nullptr, 0, 0, 0, 0, &wbem_services_raw))) return {}; std::unique_ptr<IWbemServices, iware::detail::release_deleter> wbem_services(wbem_services_raw); if(FAILED(CoSetProxyBlanket(wbem_services.get(), RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, nullptr, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE))) return {}; IEnumWbemClassObject* query_iterator_raw; wchar_t query_lang[] = L"WQL"; wchar_t query[] = L"SELECT Name FROM Win32_OperatingSystem"; if(FAILED(wbem_services->ExecQuery(query_lang, query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, nullptr, &query_iterator_raw))) return {}; std::unique_ptr<IEnumWbemClassObject, iware::detail::release_deleter> query_iterator(query_iterator_raw); std::string ret; while(query_iterator) { IWbemClassObject* value_raw; unsigned long iter_result; query_iterator->Next(static_cast<LONG>(WBEM_INFINITE), 1, &value_raw, &iter_result); if(!iter_result) break; std::unique_ptr<IWbemClassObject, iware::detail::release_deleter> value(value_raw); VARIANT val; value->Get(L"Name", 0, &val, 0, 0); iware::detail::quickscope_wrapper val_destructor{[&] { VariantClear(&val); }}; ret = ConvertBSTRToString(val.bstrVal); } return ret.substr(0, ret.find('|')); } iware::system::OS_info_t iware::system::OS_info() { const auto kernel_version = iware::system::kernel_info(); return {"Windows NT", version_name(), kernel_version.major, kernel_version.minor, kernel_version.patch, kernel_version.build_number}; } #endif
purge deprecated wstring_convert and stick with WideCharToMultiByte
purge deprecated wstring_convert and stick with WideCharToMultiByte
C++
cc0-1.0
ThePhD/infoware
4c580629a7edff9e0f8c183cb1d6c93204fe0e15
nta/engine/Input.hpp
nta/engine/Input.hpp
/* * --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have purchased from * Numenta, Inc. a separate commercial license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU 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. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ /** @file * Definition of the Input class * This class is internal, and is not wrapped. * */ #ifndef NTA_INPUT_HPP #define NTA_INPUT_HPP #ifdef SWIG #error "Input class should not be wrapped" #endif #include <vector> #include <nta/types/types.hpp> #include <nta/ntypes/Array.hpp> namespace nta { class Link; class Region; class Output; /** * Input represents a named input to a region (e.g. bottomUpIn) * * Input is not available in the public API, but is visible by * the RegionImpl * * TBD: identify methods that may be called by RegionImpl -- this * is the internal "public interface" */ class Input { public: Input(Region& region, NTA_BasicType type, bool isRegionLevel); ~Input(); /* * Inputs need to know their own name for error messages */ void setName(const std::string& name); const std::string& getName() const; /* * Create a new link and add it to this input * Also adds the link to the list of links on the output */ void addLink(const std::string& linkType, const std::string& linkParams, Output* srcOutput); /* * Locate an existing link. Returns NULL if no link exists * Called by Network::unlink and internally when adding a link */ Link* findLink(const std::string& srcRegionName, const std::string& srcOutputName); /* * Removing an existing link * Called in four cases * 1. Network::unlink() * 2. Network::removeRegion(srcRegion) * 3. Network::removeRegion(destRegion) * 4. Network::~Network() * * It is an error to call this if our containing region * is unitialized. * * Sets the link pointer to NULL on return (to avoid a dangling reference) */ void removeLink(Link*& link); // Make input data available. Called by Region::prepareInputs() void prepare(); const Array & getData() const; Region& getRegion(); const std::vector<Link*>& getLinks(); bool isRegionLevel(); /* * Called by Region::evaluateLinks() as part * of network initialization. * * 1. Tries to make sure that dimensions at both ends * of a link are specified by calling setSourceDimensions() * if possible, and then calling getDestDimensions() * 2. Ensures that region dimensions are consistent with * either by setting destination region dimensions (this is * where links "induce" dimensions) or by raising an exception * if they are inconsistent. * */ size_t evaluateLinks(); // After the input has all the information it needs, // it is initialized by this method. Sets up volatile data // structures (e.g. the input buffer) are set up // void initialize(); bool isInitialized(); /* ------------ Methods normally called by the RegionImpl ------------- */ // Get splitter map from an initialized input // See documentation for Link::getSplitterMap for // description of splitter map. typedef std::vector< std::vector<size_t> > SplitterMap; const SplitterMap& getSplitterMap() const; // explicitly instantiated for various types template <typename T> void getInputForNode(size_t nodeIndex, std::vector<T>& input) const; private: Region& region_; // buffer is concatenation of input buffers (after prepare), or, // if zeroCopyEnabled it points to the connected output bool isRegionLevel_; // Use a vector of links because order is // important. std::vector<Link*> links_; bool zeroCopyEnabled_; // volatile (non-serialized) state bool initialized_; Array data_; /* * cached splitter map -- only created if requested * mutable because getSplitterMap() is const and logically * getting the splitter map doesn't change the Input */ mutable SplitterMap splitterMap_; /* * Cache of information about link offsets so we can * easily copy data from each link. * the first link starts at offset 0 * the next link starts at offset 0 + size(link[0]) */ std::vector<size_t> linkOffsets_; size_t size_; // computed from links // Useful for us to know our own name std::string name_; // Internal methods /* * uninitialize is called by removeLink * and in our destructor. It is an error * to call it if our region is initialized. * It frees the input buffer and the splitter map * but does not affect the links. */ void uninitialize(); }; } #endif // NTA_INPUT_HPP
/* * --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have purchased from * Numenta, Inc. a separate commercial license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU 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. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ /** @file * Definition of the Input class * This class is internal, and is not wrapped. * */ #ifndef NTA_INPUT_HPP #define NTA_INPUT_HPP #ifdef SWIG #error "Input class should not be wrapped" #endif #include <vector> #include <nta/types/types.hpp> #include <nta/ntypes/Array.hpp> namespace nta { class Link; class Region; class Output; /** * Input represents a named input to a region (e.g. bottomUpIn) * * Input is not available in the public API, but is visible by * the RegionImpl * * TBD: identify methods that may be called by RegionImpl -- this * is the internal "public interface" */ class Input { public: Input(Region& region, NTA_BasicType type, bool isRegionLevel); ~Input(); /* * Inputs need to know their own name for error messages */ void setName(const std::string& name); const std::string& getName() const; /* * Create a new link and add it to this input * Also adds the link to the list of links on the output */ void addLink(const std::string& linkType, const std::string& linkParams, Output* srcOutput); /* * Locate an existing link. Returns NULL if no link exists * Called by Network::unlink and internally when adding a link */ Link* findLink(const std::string& srcRegionName, const std::string& srcOutputName); /* * Removing an existing link * Called in four cases * 1. Network::unlink() * 2. Network::removeRegion(srcRegion) * 3. Network::removeRegion(destRegion) * 4. Network::~Network() * * It is an error to call this if our containing region * is unitialized. * * Sets the link pointer to NULL on return (to avoid a dangling reference) */ void removeLink(Link*& link); // Make input data available. Called by Region::prepareInputs() void prepare(); const Array & getData() const; Region& getRegion(); const std::vector<Link*>& getLinks(); bool isRegionLevel(); /* * Called by Region::evaluateLinks() as part * of network initialization. * * 1. Tries to make sure that dimensions at both ends * of a link are specified by calling setSourceDimensions() * if possible, and then calling getDestDimensions() * 2. Ensures that region dimensions are consistent with * either by setting destination region dimensions (this is * where links "induce" dimensions) or by raising an exception * if they are inconsistent. * */ size_t evaluateLinks(); // After the input has all the information it needs, // it is initialized by this method. Sets up volatile data // structures (e.g. the input buffer) are set up // void initialize(); bool isInitialized(); /* ------------ Methods normally called by the RegionImpl ------------- */ // Get splitter map from an initialized input // See documentation for Link::getSplitterMap for // description of splitter map. typedef std::vector< std::vector<size_t> > SplitterMap; const SplitterMap& getSplitterMap() const; // explicitly instantiated for various types template <typename T> void getInputForNode(size_t nodeIndex, std::vector<T>& input) const; private: Region& region_; // buffer is concatenation of input buffers (after prepare), or, // if zeroCopyEnabled it points to the connected output bool isRegionLevel_; // Use a vector of links because order is important. std::vector<Link*> links_; bool zeroCopyEnabled_; // TODO implement optimizations for zero-copy // volatile (non-serialized) state bool initialized_; Array data_; /* * cached splitter map -- only created if requested * mutable because getSplitterMap() is const and logically * getting the splitter map doesn't change the Input */ mutable SplitterMap splitterMap_; /* * Cache of information about link offsets so we can * easily copy data from each link. * the first link starts at offset 0 * the next link starts at offset 0 + size(link[0]) */ std::vector<size_t> linkOffsets_; // Useful for us to know our own name std::string name_; // Internal methods /* * uninitialize is called by removeLink * and in our destructor. It is an error * to call it if our region is initialized. * It frees the input buffer and the splitter map * but does not affect the links. */ void uninitialize(); }; } #endif // NTA_INPUT_HPP
fix warning: unused variable size_
fix warning: unused variable size_
C++
agpl-3.0
scottpurdy/nupic,passiweinberger/nupic,virneo/nupic,metaml/nupic,badlogicmanpreet/nupic,scottpurdy/nupic,breznak/nupic,rcrowder/nupic,akhilaananthram/nupic,vamsirajendra/nupic,subutai/nupic,lscheinkman/nupic,GeraldLoeffler/nupic,EricSB/nupic,badlogicmanpreet/nupic,marionleborgne/nupic,darshanthaker/nupic,go-bears/nupic,elkingtonmcb/nupic,arhik/nupic,alfonsokim/nupic,loretoparisi/nupic,pap/nupic,neuroidss/nupic,loretoparisi/nupic,EricSB/nupic,brev/nupic,go-bears/nupic,SaganBolliger/nupic,allanino/nupic,ben-hopps/nupic,glorizen/nupic,SaganBolliger/nupic,elkingtonmcb/nupic,wanghaven/nupic,brev/nupic,go-bears/nupic,allanino/nupic,runt18/nupic,vitaly-krugl/nupic,markneville/nupic,darshanthaker/nupic,chanceraine/nupic,rayNymous/nupic,vitaly-krugl/nupic,sambitgaan/nupic,breznak/nupic,chen0031/nupic,BoltzmannBrain/nupic,rcrowder/nupic,SaganBolliger/nupic,metaml/nupic,rayNymous/nupic,pap/nupic,vamsirajendra/nupic,metaml/nupic,blueburningcoder/nupic,rhyolight/nupic,wanghaven/nupic,BoltzmannBrain/nupic,ywcui1990/nupic,cogmission/nupic,GeraldLoeffler/nupic,chanceraine/nupic,fergalbyrne/nupic,BoltzmannBrain/nupic,rhyolight/nupic,marionleborgne/nupic,ben-hopps/nupic,cogmission/nupic,numenta-ci/nupic,ywcui1990/nupic,ywcui1990/nupic,pulinagrawal/nupic,sambitgaan/nupic,neuroidss/nupic,alfonsokim/nupic,EricSB/nupic,jcasner/nupic,GeraldLoeffler/nupic,virneo/nupic,brev/nupic,marionleborgne/nupic,vamsirajendra/nupic,lscheinkman/nupic,runt18/nupic,neuroidss/nupic,markneville/nupic,akhilaananthram/nupic,breznak/nupic,mcanthony/nupic,glorizen/nupic,cogmission/nupic,fergalbyrne/nupic,chanceraine/nupic,rhyolight/nupic,jcasner/nupic,cngo-github/nupic,subutai/nupic,rcrowder/nupic,numenta/nupic,sambitgaan/nupic,lscheinkman/nupic,passiweinberger/nupic,badlogicmanpreet/nupic,BeiLuoShiMen/nupic,rayNymous/nupic,ben-hopps/nupic,runt18/nupic,pulinagrawal/nupic,numenta-ci/nupic,pulinagrawal/nupic,blueburningcoder/nupic,blueburningcoder/nupic,cngo-github/nupic,virneo/nupic,markneville/nupic,numenta/nupic,BeiLuoShiMen/nupic,jcasner/nupic,arhik/nupic,glorizen/nupic,arhik/nupic,pap/nupic,mcanthony/nupic,numenta-ci/nupic,eranchetz/nupic,darshanthaker/nupic,fergalbyrne/nupic,loretoparisi/nupic,chen0031/nupic,scottpurdy/nupic,akhilaananthram/nupic,vitaly-krugl/nupic,passiweinberger/nupic,subutai/nupic,eranchetz/nupic,BeiLuoShiMen/nupic,allanino/nupic,cngo-github/nupic,eranchetz/nupic,wanghaven/nupic,mcanthony/nupic,numenta/nupic,alfonsokim/nupic,chen0031/nupic,elkingtonmcb/nupic
98de77b7c2cc7846494c1c8e9ffe9fc47bcbcbf3
src/volumebarplugin/volumebarlogic.cpp
src/volumebarplugin/volumebarlogic.cpp
/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */ /* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */ #include "volumebarlogic.h" #include <stdlib.h> #include <string.h> #include <QVariant> #include <QString> #define DEBUG #define WARNING #include "../debug.h" #define DBUS_ERR_CHECK(err) \ if (dbus_error_is_set (&err)) \ { \ SYS_WARNING (err.message); \ dbus_error_free (&err); \ } static void stepsUpdatedSignal (DBusConnection *conn, DBusMessage *message, VolumeBarLogic *logic); #define DEFAULT_ADDRESS "unix:path=/var/run/pulse/dbus-socket" #define VOLUME_SV "com.Nokia.MainVolume1" #define VOLUME_PATH "/com/nokia/mainvolume1" #define VOLUME_IF "com.Nokia.MainVolume1" VolumeBarLogic::VolumeBarLogic () : QObject (), m_dbus_conn (NULL), m_eventloop (0), m_currentvolume (0), m_currentmax (0) { qInstallMsgHandler (0); DBusError dbus_err; char *pa_bus_address = getenv ("PULSE_DBUS_SERVER"); if (pa_bus_address == NULL) pa_bus_address = (char *) DEFAULT_ADDRESS; dbus_error_init (&dbus_err); m_dbus_conn = dbus_connection_open (pa_bus_address, &dbus_err); DBUS_ERR_CHECK (dbus_err); if ((m_dbus_conn != NULL) && (m_eventloop = new DBUSConnectionEventLoop) && (m_eventloop->addConnection (m_dbus_conn))) { dbus_connection_add_filter ( m_dbus_conn, (DBusHandleMessageFunction) stepsUpdatedSignal, (void *) this, NULL); initValues (); //XXX: FIXME: TODO: This causes crash in DBusConnectionEventLoop: addSignalMatch (); } } VolumeBarLogic::~VolumeBarLogic () { if (m_dbus_conn) { dbus_connection_unref (m_dbus_conn); m_dbus_conn = 0; if (m_eventloop) { delete m_eventloop; m_eventloop = 0; } } } void VolumeBarLogic::initValues () { DBusMessage *msg; DBusMessage *reply; DBusError error; dbus_error_init (&error); msg = dbus_message_new_method_call (VOLUME_SV, VOLUME_PATH, "org.freedesktop.DBus.Properties", "GetAll"); const char *volume_if = VOLUME_IF; dbus_message_append_args (msg, DBUS_TYPE_STRING, &volume_if, DBUS_TYPE_INVALID); reply = dbus_connection_send_with_reply_and_block ( m_dbus_conn, msg, -1, &error); DBUS_ERR_CHECK (error); dbus_message_unref (msg); if (reply && (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_METHOD_RETURN)) { DBusMessageIter iter; dbus_message_iter_init (reply, &iter); // Recurse into the array [array of dicts] while (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_INVALID) { DBusMessageIter dict_entry; dbus_message_iter_recurse (&iter, &dict_entry); // Recurse into the dict [ dict_entry (string, variant(int)) ] while (dbus_message_iter_get_arg_type (&dict_entry) != DBUS_TYPE_INVALID) { DBusMessageIter in_dict; // Recurse into the dict_entry [ string, variant(int) ] dbus_message_iter_recurse (&dict_entry, &in_dict); { char *prop_name; // Get the string value, "property name" dbus_message_iter_get_basic (&in_dict, &prop_name); dbus_message_iter_next (&in_dict); DBusMessageIter variant; // Recurese into the variant [ variant(int) ] dbus_message_iter_recurse (&in_dict, &variant); quint32 value; // Get the variant value which is uint32 dbus_message_iter_get_basic (&variant, &value); if (prop_name && strcmp (prop_name, "StepCount") == 0) m_currentmax = value; else if (prop_name && strcmp (prop_name, "CurrentStep") == 0) m_currentvolume = value; SYS_DEBUG ("%s: %d", prop_name, value); } dbus_message_iter_next (&dict_entry); } dbus_message_iter_next (&iter); } } if (reply) dbus_message_unref (reply); } void VolumeBarLogic::addSignalMatch () { SYS_DEBUG (""); DBusMessage *message = NULL; char *signal = (char *) "com.Nokia.MainVolume1.StepsUpdated"; message = dbus_message_new_method_call ("org.PulseAudio.Core1", "/org/pulseaudio/core1", "org.PulseAudio.Core1", "ListenForSignal"); if (message != NULL) { dbus_message_append_args (message, DBUS_TYPE_STRING, &signal, DBUS_TYPE_INVALID); dbus_connection_send (m_dbus_conn, message, NULL); dbus_connection_flush (m_dbus_conn); } else SYS_WARNING ("Cannot listen for PulseAudio signals [out of memory]"); if (message) dbus_message_unref (message); } #define DBUS_ARG_TYPE(type) \ switch (type) { \ case DBUS_TYPE_INVALID: \ SYS_DEBUG ("invalid"); \ break; \ case DBUS_TYPE_STRING: \ SYS_DEBUG ("string"); \ break; \ case DBUS_TYPE_UINT32: \ SYS_DEBUG ("uint32"); \ break; \ case DBUS_TYPE_ARRAY: \ SYS_DEBUG ("array"); \ break; \ case DBUS_TYPE_STRUCT: \ SYS_DEBUG ("stuct"); \ break; \ case DBUS_TYPE_DICT_ENTRY: \ SYS_DEBUG ("dict_entry"); \ break; \ default: \ SYS_DEBUG ("type_code %d", type); \ break; \ } #define DBUS_ITER_TYPE(iter) \ DBUS_ARG_TYPE(dbus_message_iter_get_arg_type (&iter)) static void stepsUpdatedSignal (DBusConnection *conn, DBusMessage *message, VolumeBarLogic *logic) { SYS_DEBUG ("message address: %p", message); if (message) { SYS_DEBUG ("message signature, interface, member: %s, %s, %s", dbus_message_get_signature (message), dbus_message_get_interface (message), dbus_message_get_member (message)); SYS_DEBUG ("message tpye: %s", dbus_message_type_to_string ( dbus_message_get_type (message))); } Q_UNUSED (conn); Q_UNUSED (logic); // quint32 value = 0; // quint32 maxvalue = 0; DBusMessageIter iter; dbus_message_iter_init (message, &iter); // Recurse into the array [array of dicts] while (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_INVALID) { DBUS_ITER_TYPE (iter); if (dbus_message_iter_get_arg_type (&iter) == DBUS_TYPE_STRING) { char *val = NULL; dbus_message_iter_get_basic (&iter, &val); SYS_DEBUG ("msg: %s", val); } #if 0 DBusMessageIter dict_entry; dbus_message_iter_recurse (&iter, &dict_entry); while (dbus_message_iter_get_arg_type (&dict_entry) != DBUS_TYPE_INVALID) { DBUS_ITER_TYPE (dict_entry); dbus_message_iter_next (&dict_entry); } #endif dbus_message_iter_next (&iter); } #if 0 // Forward the data to the BusinessLogic logic->stepsUpdated (value, maxvalue); #endif } void VolumeBarLogic::stepsUpdated (quint32 value, quint32 maxvalue) { SYS_DEBUG ("val = %d [max = %d]", value, maxvalue); m_currentvolume = value; m_currentmax = maxvalue; emit volumeChanged (value, maxvalue); } void VolumeBarLogic::setVolume (quint32 value) { DBusMessage *message; char *volume_if = (char *) VOLUME_IF; char *method = (char *) "CurrentStep"; message = dbus_message_new_method_call (VOLUME_SV, VOLUME_PATH, "org.freedesktop.DBus.Properties", "Set"); if (message && dbus_message_append_args (message, DBUS_TYPE_STRING, &volume_if, DBUS_TYPE_STRING, &method, DBUS_TYPE_INVALID)) { dbus_uint32_t serial = 0; DBusMessageIter append; DBusMessageIter sub; // Create and append the variant argument ... dbus_message_iter_init_append (message, &append); dbus_message_iter_open_container (&append, DBUS_TYPE_VARIANT, DBUS_TYPE_UINT32_AS_STRING, &sub); // Set the variant argument value: dbus_message_iter_append_basic (&sub, DBUS_TYPE_UINT32, &value); // Close the append iterator dbus_message_iter_close_container (&append, &sub); // Send/flush the message immediately: dbus_connection_send (m_dbus_conn, message, &serial); dbus_connection_flush (m_dbus_conn); // SYS_DEBUG ("volume set to %d [d-bus msg serial: %u]", value, serial); // ^ Warning: this debug message can produce too many output } else SYS_WARNING ("Cannot set volume! [not enough memory]"); if (message) dbus_message_unref (message); m_currentvolume = value; } quint32 VolumeBarLogic::getVolume () { SYS_DEBUG ("volume = %d", m_currentvolume); return m_currentvolume; } quint32 VolumeBarLogic::getMaxVolume () { SYS_DEBUG ("max = %d", m_currentmax); return m_currentmax; }
/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */ /* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */ #include "volumebarlogic.h" #include <stdlib.h> #include <string.h> #include <QVariant> #include <QString> #define DEBUG #define WARNING #include "../debug.h" #define DBUS_ERR_CHECK(err) \ if (dbus_error_is_set (&err)) \ { \ SYS_WARNING (err.message); \ dbus_error_free (&err); \ } static void stepsUpdatedSignal (DBusConnection *conn, DBusMessage *message, VolumeBarLogic *logic); #define DEFAULT_ADDRESS "unix:path=/var/run/pulse/dbus-socket" #define VOLUME_SV "com.Nokia.MainVolume1" #define VOLUME_PATH "/com/nokia/mainvolume1" #define VOLUME_IF "com.Nokia.MainVolume1" VolumeBarLogic::VolumeBarLogic () : QObject (), m_dbus_conn (NULL), m_eventloop (0), m_currentvolume (0), m_currentmax (0) { qInstallMsgHandler (0); DBusError dbus_err; char *pa_bus_address = getenv ("PULSE_DBUS_SERVER"); if (pa_bus_address == NULL) pa_bus_address = (char *) DEFAULT_ADDRESS; dbus_error_init (&dbus_err); m_dbus_conn = dbus_connection_open (pa_bus_address, &dbus_err); DBUS_ERR_CHECK (dbus_err); if ((m_dbus_conn != NULL) && (m_eventloop = new DBUSConnectionEventLoop) && (m_eventloop->addConnection (m_dbus_conn))) { dbus_connection_add_filter ( m_dbus_conn, (DBusHandleMessageFunction) stepsUpdatedSignal, (void *) this, NULL); initValues (); //XXX: FIXME: TODO: This causes crash in DBusConnectionEventLoop: // addSignalMatch (); } } VolumeBarLogic::~VolumeBarLogic () { if (m_dbus_conn) { dbus_connection_unref (m_dbus_conn); m_dbus_conn = 0; if (m_eventloop) { delete m_eventloop; m_eventloop = 0; } } } void VolumeBarLogic::initValues () { DBusMessage *msg; DBusMessage *reply; DBusError error; dbus_error_init (&error); msg = dbus_message_new_method_call (VOLUME_SV, VOLUME_PATH, "org.freedesktop.DBus.Properties", "GetAll"); const char *volume_if = VOLUME_IF; dbus_message_append_args (msg, DBUS_TYPE_STRING, &volume_if, DBUS_TYPE_INVALID); reply = dbus_connection_send_with_reply_and_block ( m_dbus_conn, msg, -1, &error); DBUS_ERR_CHECK (error); dbus_message_unref (msg); if (reply && (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_METHOD_RETURN)) { DBusMessageIter iter; dbus_message_iter_init (reply, &iter); // Recurse into the array [array of dicts] while (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_INVALID) { DBusMessageIter dict_entry; dbus_message_iter_recurse (&iter, &dict_entry); // Recurse into the dict [ dict_entry (string, variant(int)) ] while (dbus_message_iter_get_arg_type (&dict_entry) != DBUS_TYPE_INVALID) { DBusMessageIter in_dict; // Recurse into the dict_entry [ string, variant(int) ] dbus_message_iter_recurse (&dict_entry, &in_dict); { char *prop_name; // Get the string value, "property name" dbus_message_iter_get_basic (&in_dict, &prop_name); dbus_message_iter_next (&in_dict); DBusMessageIter variant; // Recurese into the variant [ variant(int) ] dbus_message_iter_recurse (&in_dict, &variant); quint32 value; // Get the variant value which is uint32 dbus_message_iter_get_basic (&variant, &value); if (prop_name && strcmp (prop_name, "StepCount") == 0) m_currentmax = value; else if (prop_name && strcmp (prop_name, "CurrentStep") == 0) m_currentvolume = value; SYS_DEBUG ("%s: %d", prop_name, value); } dbus_message_iter_next (&dict_entry); } dbus_message_iter_next (&iter); } } if (reply) dbus_message_unref (reply); } void VolumeBarLogic::addSignalMatch () { SYS_DEBUG (""); DBusMessage *message = NULL; char *signal = (char *) "com.Nokia.MainVolume1.StepsUpdated"; message = dbus_message_new_method_call ("org.PulseAudio.Core1", "/org/pulseaudio/core1", "org.PulseAudio.Core1", "ListenForSignal"); if (message != NULL) { dbus_message_append_args (message, DBUS_TYPE_STRING, &signal, DBUS_TYPE_INVALID); dbus_connection_send (m_dbus_conn, message, NULL); dbus_connection_flush (m_dbus_conn); } else SYS_WARNING ("Cannot listen for PulseAudio signals [out of memory]"); if (message) dbus_message_unref (message); } #define DBUS_ARG_TYPE(type) \ switch (type) { \ case DBUS_TYPE_INVALID: \ SYS_DEBUG ("invalid"); \ break; \ case DBUS_TYPE_STRING: \ SYS_DEBUG ("string"); \ break; \ case DBUS_TYPE_UINT32: \ SYS_DEBUG ("uint32"); \ break; \ case DBUS_TYPE_ARRAY: \ SYS_DEBUG ("array"); \ break; \ case DBUS_TYPE_STRUCT: \ SYS_DEBUG ("stuct"); \ break; \ case DBUS_TYPE_DICT_ENTRY: \ SYS_DEBUG ("dict_entry"); \ break; \ default: \ SYS_DEBUG ("type_code %d", type); \ break; \ } #define DBUS_ITER_TYPE(iter) \ DBUS_ARG_TYPE(dbus_message_iter_get_arg_type (&iter)) static void stepsUpdatedSignal (DBusConnection *conn, DBusMessage *message, VolumeBarLogic *logic) { SYS_DEBUG ("message address: %p", message); if (message) { SYS_DEBUG ("message signature, interface, member: %s, %s, %s", dbus_message_get_signature (message), dbus_message_get_interface (message), dbus_message_get_member (message)); SYS_DEBUG ("message tpye: %s", dbus_message_type_to_string ( dbus_message_get_type (message))); } Q_UNUSED (conn); Q_UNUSED (logic); // quint32 value = 0; // quint32 maxvalue = 0; DBusMessageIter iter; dbus_message_iter_init (message, &iter); // Recurse into the array [array of dicts] while (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_INVALID) { DBUS_ITER_TYPE (iter); if (dbus_message_iter_get_arg_type (&iter) == DBUS_TYPE_STRING) { char *val = NULL; dbus_message_iter_get_basic (&iter, &val); SYS_DEBUG ("msg: %s", val); } #if 0 DBusMessageIter dict_entry; dbus_message_iter_recurse (&iter, &dict_entry); while (dbus_message_iter_get_arg_type (&dict_entry) != DBUS_TYPE_INVALID) { DBUS_ITER_TYPE (dict_entry); dbus_message_iter_next (&dict_entry); } #endif dbus_message_iter_next (&iter); } #if 0 // Forward the data to the BusinessLogic logic->stepsUpdated (value, maxvalue); #endif } void VolumeBarLogic::stepsUpdated (quint32 value, quint32 maxvalue) { SYS_DEBUG ("val = %d [max = %d]", value, maxvalue); m_currentvolume = value; m_currentmax = maxvalue; emit volumeChanged (value, maxvalue); } void VolumeBarLogic::setVolume (quint32 value) { DBusMessage *message; char *volume_if = (char *) VOLUME_IF; char *method = (char *) "CurrentStep"; message = dbus_message_new_method_call (VOLUME_SV, VOLUME_PATH, "org.freedesktop.DBus.Properties", "Set"); if (message && dbus_message_append_args (message, DBUS_TYPE_STRING, &volume_if, DBUS_TYPE_STRING, &method, DBUS_TYPE_INVALID)) { dbus_uint32_t serial = 0; DBusMessageIter append; DBusMessageIter sub; // Create and append the variant argument ... dbus_message_iter_init_append (message, &append); dbus_message_iter_open_container (&append, DBUS_TYPE_VARIANT, DBUS_TYPE_UINT32_AS_STRING, &sub); // Set the variant argument value: dbus_message_iter_append_basic (&sub, DBUS_TYPE_UINT32, &value); // Close the append iterator dbus_message_iter_close_container (&append, &sub); // Send/flush the message immediately: dbus_connection_send (m_dbus_conn, message, &serial); dbus_connection_flush (m_dbus_conn); // SYS_DEBUG ("volume set to %d [d-bus msg serial: %u]", value, serial); // ^ Warning: this debug message can produce too many output } else SYS_WARNING ("Cannot set volume! [not enough memory]"); if (message) dbus_message_unref (message); m_currentvolume = value; } quint32 VolumeBarLogic::getVolume () { SYS_DEBUG ("volume = %d", m_currentvolume); return m_currentvolume; } quint32 VolumeBarLogic::getMaxVolume () { SYS_DEBUG ("max = %d", m_currentmax); return m_currentmax; }
comment out signal matching as it crashes the sysuid
VolumeBarLogic: comment out signal matching as it crashes the sysuid
C++
lgpl-2.1
deztructor/meegotouch-controlpanelapplets,nemomobile-graveyard/meegotouch-controlpanelapplets,nemomobile-graveyard/meegotouch-controlpanelapplets,deztructor/meegotouch-controlpanelapplets,deztructor/meegotouch-controlpanelapplets,nemomobile-graveyard/meegotouch-controlpanelapplets
66b97d5d635340d483bbaf78d4ec71e002b73551
src/mesh/animation.cpp
src/mesh/animation.cpp
#pragma warning(disable: 4244) // conversion, possible loss of data #include <pwn/mesh/mesh.h> #include <pwn/math/operations.h> #include <pwn/core/stdutil.h> #include <boost/foreach.hpp> namespace pwn { namespace mesh { real Timed::getTime() const { return time; } Timed::Timed(real t) : time(t) { } FramePosition::FramePosition() : Timed(0) , location(math::Origo3().vec) { } FramePosition::FramePosition(real time, const math::vec3& loc) : Timed(time) , location(loc) { } string FramePosition::toString() const { return core::Str() << getTime() << " " << location; } math::vec3 Interpolate(const FramePosition& from, real current, const FramePosition& to) { real scale = math::To01(from.getTime(), current, to.getTime()); if (math::IsWithin(0, scale, 1) == false) throw "invalid scale"; return math::Lerp(from.location, scale, to.location); } FrameRotation::FrameRotation() : Timed(0) , rotation(math::qIdentity()) { } FrameRotation::FrameRotation(real time, const math::quat& rot) : Timed(time) , rotation(rot) { } string FrameRotation::toString() const { return core::Str() << getTime() << " " << math::cAxisAngle(rotation); } math::quat Interpolate(const FrameRotation& from, real current, const FrameRotation& to) { real scale = math::To01(from.getTime(), current, to.getTime()); if (math::IsWithin(0, scale, 1) == false) throw "invalid scale"; return math::SlerpShortway(from.rotation, scale, to.rotation); } PosePerBone::PosePerBone() : location(math::Origo3().vec) , rotation(math::qIdentity()) { } PosePerBone::PosePerBone(math::vec3 l, math::quat r) : location(l) , rotation(r) { } string PosePerBone::toString() const { return core::Str() << location << ": " << math::cAxisAngle(rotation); } math::quat Interpolate(real time, const core::Vector<FrameRotation>& fr) { const int fri = Get(fr, time); if (fri == -1) return math::qIdentity(); const math::quat r( Interpolate(fr[fri - 1], time, fr[fri]) ); return r; } math::vec3 Interpolate(real time, const core::Vector<FramePosition>& fp) { const int fpi = Get(fp, time); if (fpi == -1) return math::Origo3().vec; const math::vec3 res( Interpolate(fp[fpi - 1], time, fp[fpi]) ); return res; } AnimationPerBone::AnimationPerBone() { } AnimationPerBone::AnimationPerBone(core::Vector<FramePosition>& afp, core::Vector<FrameRotation>& afr) { fp.swap(afp); fr.swap(afr); } string AnimationPerBone::toString() const { return core::Str() << "<" << fp.size() << " " << fr.size() << ">"; } real AnimationPerBone::getLength() const { // get the time of the last frame return fp[fp.size() - 1].getTime(); } PosePerBone AnimationPerBone::getBonePose(real time) const { const PosePerBone p( Interpolate(time, fp), Interpolate(time, fr) ); return p; } void AnimationPerBone::sub(int start, int end, AnimationPerBone* out) const { std::vector<FramePosition> abfp; std::vector<FrameRotation> abfr; real length = end - start; bool first = true; real last = 0; for(std::size_t i=0; i<this->fp.size(); ++i) { const FramePosition& fp = this->fp[i]; if (math::IsWithin(start, fp.getTime(), end)) { real mark = fp.getTime()-start; if (first && math::IsZero(mark)==false) { abfp.push_back(FramePosition(0, Interpolate(start, this->fp))); } mark = math::ZeroOrValue(mark); first = false; abfp.push_back(FramePosition(mark, fp.location)); last = mark; } } if (math::IsEqual(length, last)==false ) { abfp.push_back(FramePosition(length, Interpolate(end, this->fp))); } first = true; last = 0; for(std::size_t i=0; i<this->fr.size(); ++i) { const FrameRotation& fr = this->fr[i]; if (math::IsWithin(start, fr.getTime(), end)) { real mark = fr.getTime() - start; if (first && math::IsZero(mark) == false) { abfr.push_back(FrameRotation(0, Interpolate(start, this->fr))); } mark = math::ZeroOrValue(mark); first = false; abfr.push_back(FrameRotation(mark, fr.rotation)); last = mark; } } if (math::IsEqual(length, last) == false) { abfr.push_back(FrameRotation(length, Interpolate(end, this->fr))); } if (abfp.size() < 2 || abfr.size() < 2) throw "Data error, need atleast 2 keyframes per animation"; core::Vector<FramePosition> abfpv(abfp); out->fp.swap( abfpv ); core::Vector<FrameRotation> abfrv(abfr); out->fr.swap( abfrv ); } void AnimationPerBone::scale(real scale) { for(std::size_t i=0; i<fp.size(); ++i) { FramePosition& f = fp[i]; f.location *= scale; } } Pose::Pose(core::Vector<PosePerBone>& apose) : bones(apose) { } void UpdateMatrix(core::Vector<math::mat44>& result, const Bone& bone, const Pose& pose, const std::vector<Bone>& list) ;/*{ mat44 parent; if (bone.hasParent() == false) parent = mat44.Identity; else parent = result[bone.parent]; vec3 loc = pose.bones[bone.index].location; quat rot = pose.bones[bone.index].rotation; // bone.pos Rotate(-bone.rot). result[bone.index] = new MatrixHelper(parent).Rotate(bone.rot).Translate(bone.pos).Translate(loc).Rotate(-rot).mat44; BOOST_FOREACH(Bone b, bone.childs) { updateMatrix(ref result, b, pose, list); } }*/ CompiledPose::CompiledPose(const Pose& pose, const Mesh& def) { if (pose.bones.size() != def.bones.size()) throw "Invalid animation/mesh, bone count differs"; core::Vector<math::mat44> result( pose.bones.size() ); for (std::size_t i = 0; i < pose.bones.size(); ++i) result[i] = math::mat44Identity(); BOOST_FOREACH(const Bone& b, def.bones) { UpdateMatrix(result, b, pose, def.bones); } transforms.swap(result); } AnimationInformation::AnimationInformation(int s, int e, const string& n) : start(s) , end(e) , name(n) { } real CalculateLength(const core::Vector<AnimationPerBone>& bones) { real length = 0; for(std::size_t i=0; i<bones.size(); ++i) { const AnimationPerBone& ab = bones[i]; length = math::Max(length, ab.getLength()); } return length; } Animation::Animation(core::Vector<AnimationPerBone>& abones) : length( CalculateLength(abones) ) { bones.swap(abones); } void Animation::getPose(real time, Pose* out) const { core::Vector<PosePerBone> bd; bd.reset(bones.size()); for(std::size_t i=0; i<bones.size(); ++i) { const AnimationPerBone& ab = bones[i]; bd[i] = ab.getBonePose(time); } out->bones.swap(bd); } void Animation::subanim(int start, int end, Animation* out) const { core::Vector<AnimationPerBone> bd(bones.size()); for(std::size_t i=0; i<bones.size(); ++i) { const AnimationPerBone& ab = bones[i]; ab.sub(start, end, &bd[i]); } out->bones.swap(bd); } void Animation::subanim(const AnimationInformation& info, Animation* out) const { subanim(info.start, info.end, out); } void Animation::scale(real scale) { for(std::size_t i=0; i<bones.size(); ++i) { AnimationPerBone& ab = bones[i]; ab.scale(scale); } } } }
#pragma warning(disable: 4244) // conversion, possible loss of data #include <pwn/mesh/mesh.h> #include <pwn/math/operations.h> #include <pwn/core/stdutil.h> #include <boost/foreach.hpp> #include <pwn/assert.h> namespace pwn { namespace mesh { real Timed::getTime() const { return time; } Timed::Timed(real t) : time(t) { } FramePosition::FramePosition() : Timed(0) , location(math::Origo3().vec) { } FramePosition::FramePosition(real time, const math::vec3& loc) : Timed(time) , location(loc) { } string FramePosition::toString() const { return core::Str() << getTime() << " " << location; } math::vec3 Interpolate(const FramePosition& from, real current, const FramePosition& to) { real scale = math::To01(from.getTime(), current, to.getTime()); if (math::IsWithin(0, scale, 1) == false) throw "invalid scale"; return math::Lerp(from.location, scale, to.location); } FrameRotation::FrameRotation() : Timed(0) , rotation(math::qIdentity()) { } FrameRotation::FrameRotation(real time, const math::quat& rot) : Timed(time) , rotation(rot) { } string FrameRotation::toString() const { return core::Str() << getTime() << " " << math::cAxisAngle(rotation); } math::quat Interpolate(const FrameRotation& from, real current, const FrameRotation& to) { real scale = math::To01(from.getTime(), current, to.getTime()); if (math::IsWithin(0, scale, 1) == false) throw "invalid scale"; return math::SlerpShortway(from.rotation, scale, to.rotation); } PosePerBone::PosePerBone() : location(math::Origo3().vec) , rotation(math::qIdentity()) { } PosePerBone::PosePerBone(math::vec3 l, math::quat r) : location(l) , rotation(r) { } string PosePerBone::toString() const { return core::Str() << location << ": " << math::cAxisAngle(rotation); } math::quat Interpolate(real time, const core::Vector<FrameRotation>& fr) { const int fri = Get(fr, time); if (fri == -1) return math::qIdentity(); const math::quat r( Interpolate(fr[fri - 1], time, fr[fri]) ); return r; } math::vec3 Interpolate(real time, const core::Vector<FramePosition>& fp) { const int fpi = Get(fp, time); if (fpi == -1) return math::Origo3().vec; const math::vec3 res( Interpolate(fp[fpi - 1], time, fp[fpi]) ); return res; } AnimationPerBone::AnimationPerBone() { } AnimationPerBone::AnimationPerBone(core::Vector<FramePosition>& afp, core::Vector<FrameRotation>& afr) { fp.swap(afp); fr.swap(afr); } string AnimationPerBone::toString() const { return core::Str() << "<" << fp.size() << " " << fr.size() << ">"; } real AnimationPerBone::getLength() const { // get the time of the last frame return fp[fp.size() - 1].getTime(); } PosePerBone AnimationPerBone::getBonePose(real time) const { const PosePerBone p( Interpolate(time, fp), Interpolate(time, fr) ); return p; } void AnimationPerBone::sub(int start, int end, AnimationPerBone* out) const { std::vector<FramePosition> abfp; std::vector<FrameRotation> abfr; real length = end - start; bool first = true; real last = 0; for(std::size_t i=0; i<this->fp.size(); ++i) { const FramePosition& fp = this->fp[i]; if (math::IsWithin(start, fp.getTime(), end)) { real mark = fp.getTime()-start; if (first && math::IsZero(mark)==false) { abfp.push_back(FramePosition(0, Interpolate(start, this->fp))); } mark = math::ZeroOrValue(mark); first = false; abfp.push_back(FramePosition(mark, fp.location)); last = mark; } } if (math::IsEqual(length, last)==false ) { abfp.push_back(FramePosition(length, Interpolate(end, this->fp))); } first = true; last = 0; for(std::size_t i=0; i<this->fr.size(); ++i) { const FrameRotation& fr = this->fr[i]; if (math::IsWithin(start, fr.getTime(), end)) { real mark = fr.getTime() - start; if (first && math::IsZero(mark) == false) { abfr.push_back(FrameRotation(0, Interpolate(start, this->fr))); } mark = math::ZeroOrValue(mark); first = false; abfr.push_back(FrameRotation(mark, fr.rotation)); last = mark; } } if (math::IsEqual(length, last) == false) { abfr.push_back(FrameRotation(length, Interpolate(end, this->fr))); } if (abfp.size() < 2 || abfr.size() < 2) throw "Data error, need atleast 2 keyframes per animation"; core::Vector<FramePosition> abfpv(abfp); out->fp.swap( abfpv ); core::Vector<FrameRotation> abfrv(abfr); out->fr.swap( abfrv ); } void AnimationPerBone::scale(real scale) { for(std::size_t i=0; i<fp.size(); ++i) { FramePosition& f = fp[i]; f.location *= scale; } } Pose::Pose(core::Vector<PosePerBone>& apose) : bones(apose) { } CompiledPose::CompiledPose(const Pose& pose, const Mesh& def) { if (pose.bones.size() != def.bones.size()) throw "Invalid animation/mesh, bone count differs"; core::Vector<math::mat44> result( pose.bones.size() ); for (std::size_t i = 0; i < pose.bones.size(); ++i) result[i] = math::mat44Identity(); BOOST_FOREACH(const Bone& bone, def.bones) { // either it is a parent, or it's parent has already been precoessed Assert( bone.hasParent()==false || bone.index > bone.parent ); math::mat44 parent = bone.hasParent() ? result[bone.parent] : math::mat44Identity(); const math::vec3 loc = pose.bones[bone.index].location; const math::quat rot = pose.bones[bone.index].rotation; result[bone.index] = math::mat44helper(parent).rotate(bone.rot).translate(bone.pos).translate(loc).rotate(-rot).mat; } transforms.swap(result); } AnimationInformation::AnimationInformation(int s, int e, const string& n) : start(s) , end(e) , name(n) { } real CalculateLength(const core::Vector<AnimationPerBone>& bones) { real length = 0; for(std::size_t i=0; i<bones.size(); ++i) { const AnimationPerBone& ab = bones[i]; length = math::Max(length, ab.getLength()); } return length; } Animation::Animation(core::Vector<AnimationPerBone>& abones) : length( CalculateLength(abones) ) { bones.swap(abones); } void Animation::getPose(real time, Pose* out) const { core::Vector<PosePerBone> bd; bd.reset(bones.size()); for(std::size_t i=0; i<bones.size(); ++i) { const AnimationPerBone& ab = bones[i]; bd[i] = ab.getBonePose(time); } out->bones.swap(bd); } void Animation::subanim(int start, int end, Animation* out) const { core::Vector<AnimationPerBone> bd(bones.size()); for(std::size_t i=0; i<bones.size(); ++i) { const AnimationPerBone& ab = bones[i]; ab.sub(start, end, &bd[i]); } out->bones.swap(bd); } void Animation::subanim(const AnimationInformation& info, Animation* out) const { subanim(info.start, info.end, out); } void Animation::scale(real scale) { for(std::size_t i=0; i<bones.size(); ++i) { AnimationPerBone& ab = bones[i]; ab.scale(scale); } } } }
update matrix removed, and merged into the CompiledPose constructor
update matrix removed, and merged into the CompiledPose constructor
C++
bsd-3-clause
madeso/pwn-engine,madeso/pwn-engine,madeso/pwn-engine,madeso/pwn-engine
7e956cac7cda95dbc4170aea0d166c6f6cc8cb48
src/mode_calc_help.cpp
src/mode_calc_help.cpp
#include <mill/math/Vector.hpp> #include <mill/util/logger.hpp> #include "mode_calc_help.hpp" #include "mode_calc_rmsd.hpp" #include "mode_calc_dist.hpp" namespace mill { const char* mode_calc_help_usage() noexcept { return "usage: mill calc [command] [parameters...]\n\n" " avaiable commands\n" " - rmsd\n" " : calculate RMSD\n" " - dist\n" " : calculate distance from traj file\n" " - wham\n" " : reconstruct free energy surface by WHAM\n" " - help\n" " : print detailed explanation of each command\n"; } //! this function forwards the arguments to different modes. int mode_calc_help(std::deque<std::string_view> args) { using namespace std::literals::string_view_literals; if(args.empty()) { log::info(mode_calc_help_usage()); return 0; } const auto command = args.front(); if(command == "rmsd") { return mode_calc_rmsd({"rmsd"sv, "help"sv}); } else if(command == "dist") { return mode_calc_dist({"dist"sv, "help"sv}); } else if(command == "help") { log::info(mode_calc_help_usage()); return 0; } else { log::error("mill calc help: unknown command : ", command); log::error(mode_calc_help_usage()); return 1; } } } // mill
#include <mill/math/Vector.hpp> #include <mill/util/logger.hpp> #include "mode_calc_help.hpp" #include "mode_calc_rmsd.hpp" #include "mode_calc_wham.hpp" #include "mode_calc_dist.hpp" #include "mode_calc_angle.hpp" #include "mode_calc_obb.hpp" namespace mill { const char* mode_calc_help_usage() noexcept { return "usage: mill calc [command] [parameters...]\n\n" " avaiable commands\n" " - rmsd\n" " : calculate RMSD between a reference and frames in trajectory\n" " - wham\n" " : reconstruct free energy surface by WHAM\n" " - dist\n" " : calculate distance from traj file\n" " - angle\n" " : calculate angle from traj file\n" " - obb\n" " : construct OBB using covariances\n" " - help\n" " : print detailed explanation of each command\n"; } //! this function forwards the arguments to different modes. int mode_calc_help(std::deque<std::string_view> args) { using namespace std::literals::string_view_literals; if(args.empty()) { log::info(mode_calc_help_usage()); return 0; } const auto command = args.front(); if(command == "rmsd") { return mode_calc_rmsd({"help"sv}); } else if(command == "dist") { return mode_calc_dist({"help"sv}); } else if(command == "angle") { return mode_calc_angle({"help"sv}); } else if(command == "wham") { return mode_calc_wham({"help"sv}); } else if(command == "obb") { return mode_calc_obb({"help"sv}); } else if(command == "help") { log::info(mode_calc_help_usage()); return 0; } else { log::error("mill calc help: unknown command : ", command); log::error(mode_calc_help_usage()); return 1; } } } // mill
update help message
:memo: update help message
C++
mit
ToruNiina/Coffee-mill,ToruNiina/Coffee-mill
1576c4a3dab07569ed91b49ef0d5936e28eca5b7
src/Gui/ViewProviderPlane.cpp
src/Gui/ViewProviderPlane.cpp
/*************************************************************************** * Copyright (c) Juergen Riegel ([email protected]) 2012 * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <QApplication> # include <Inventor/SoPickedPoint.h> # include <Inventor/events/SoMouseButtonEvent.h> # include <Inventor/nodes/SoSeparator.h> # include <Inventor/nodes/SoBaseColor.h> # include <Inventor/nodes/SoFontStyle.h> # include <Inventor/nodes/SoPickStyle.h> # include <Inventor/nodes/SoText2.h> # include <Inventor/nodes/SoTranslation.h> # include <Inventor/nodes/SoCoordinate3.h> # include <Inventor/nodes/SoIndexedLineSet.h> # include <Inventor/nodes/SoMarkerSet.h> # include <Inventor/nodes/SoDrawStyle.h> #endif #include <Inventor/nodes/SoMaterial.h> #include <Inventor/nodes/SoAnnotation.h> #include <Inventor/details/SoLineDetail.h> #include <Inventor/nodes/SoAsciiText.h> #include "ViewProviderPlane.h" #include "SoFCSelection.h" #include "Application.h" #include "Document.h" #include "View3DInventorViewer.h" #include "Inventor/SoAutoZoomTranslation.h" #include "SoAxisCrossKit.h" #include "Window.h" //#include <SoDepthBuffer.h> #include <App/PropertyGeo.h> #include <App/PropertyStandard.h> #include <App/MeasureDistance.h> #include <Base/Console.h> using namespace Gui; PROPERTY_SOURCE(Gui::ViewProviderPlane, Gui::ViewProviderGeometryObject) ViewProviderPlane::ViewProviderPlane() { ADD_PROPERTY(Size,(1.0)); pMat = new SoMaterial(); pMat->ref(); float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox() SbVec3f verts[4] = { SbVec3f(size,size,0), SbVec3f(size,-size,0), SbVec3f(-size,-size,0), SbVec3f(-size,size,0), }; // indexes used to create the edges static const int32_t lines[6] = { 0,1,2,3,0,-1 }; // Create the selection node pcHighlight = createFromSettings(); pcHighlight->ref(); if (pcHighlight->selectionMode.getValue() == Gui::SoFCSelection::SEL_OFF) Selectable.setValue(false); pMat->diffuseColor.setNum(1); pMat->diffuseColor.set1Value(0, SbColor(50./255., 150./255., 250./255.)); pCoords = new SoCoordinate3(); pCoords->ref(); pCoords->point.setNum(4); pCoords->point.setValues(0, 4, verts); pLines = new SoIndexedLineSet(); pLines->ref(); pLines->coordIndex.setNum(6); pLines->coordIndex.setValues(0, 6, lines); pFont = new SoFont(); pFont->size.setValue(Size.getValue()/10.); pTranslation = new SoTranslation(); pTranslation->translation.setValue(SbVec3f(-1,9./10.,0)); pText = new SoAsciiText(); pText->width.setValue(-1); sPixmap = "view-measurement"; } ViewProviderPlane::~ViewProviderPlane() { pcHighlight->unref(); pCoords->unref(); pLines->unref(); pMat->unref(); } void ViewProviderPlane::onChanged(const App::Property* prop) { if (prop == &Size){ float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox() SbVec3f verts[4] = { SbVec3f(size,size,0), SbVec3f(size,-size,0), SbVec3f(-size,-size,0), SbVec3f(-size,size,0), }; pCoords->point.setValues(0, 4, verts); pFont->size.setValue(Size.getValue()/10.); pTranslation->translation.setValue(SbVec3f(-size,size*9./10.,0)); } else ViewProviderGeometryObject::onChanged(prop); } std::vector<std::string> ViewProviderPlane::getDisplayModes(void) const { // add modes std::vector<std::string> StrList; StrList.push_back("Base"); return StrList; } void ViewProviderPlane::setDisplayMode(const char* ModeName) { if (strcmp(ModeName, "Base") == 0) setDisplayMaskMode("Base"); ViewProviderGeometryObject::setDisplayMode(ModeName); } void ViewProviderPlane::attach(App::DocumentObject* pcObject) { ViewProviderGeometryObject::attach(pcObject); pcHighlight->objectName = pcObject->getNameInDocument(); pcHighlight->documentName = pcObject->getDocument()->getName(); pcHighlight->subElementName = "Main"; SoSeparator *sep = new SoSeparator(); SoAnnotation *lineSep = new SoAnnotation(); SoDrawStyle* style = new SoDrawStyle(); style->lineWidth = 2.0f; SoMaterialBinding* matBinding = new SoMaterialBinding; matBinding->value = SoMaterialBinding::OVERALL; sep->addChild(matBinding); sep->addChild(pMat); sep->addChild(pcHighlight); pcHighlight->addChild(style); pcHighlight->addChild(pCoords); pcHighlight->addChild(pLines); style = new SoDrawStyle(); style->lineWidth = 2.0f; style->linePattern.setValue(0xF000); lineSep->addChild(style); lineSep->addChild(pLines); lineSep->addChild(pFont); pText->string.setValue(SbString(pcObject->Label.getValue())); lineSep->addChild(pTranslation); lineSep->addChild(pText); pcHighlight->addChild(lineSep); pcHighlight->style = SoFCSelection::EMISSIVE_DIFFUSE; addDisplayMaskMode(sep, "Base"); } void ViewProviderPlane::updateData(const App::Property* prop) { pText->string.setValue(SbString(pcObject->Label.getValue())); ViewProviderGeometryObject::updateData(prop); } std::string ViewProviderPlane::getElement(const SoDetail* detail) const { if (detail) { if (detail->getTypeId() == SoLineDetail::getClassTypeId()) { const SoLineDetail* line_detail = static_cast<const SoLineDetail*>(detail); int edge = line_detail->getLineIndex(); if (edge == 0) { return std::string("Main"); } } } return std::string(""); } SoDetail* ViewProviderPlane::getDetail(const char* subelement) const { SoLineDetail* detail = 0; std::string subelem(subelement); int edge = -1; if(subelem == "Main") edge = 0; if(edge >= 0) { detail = new SoLineDetail(); detail->setPartIndex(edge); } return detail; } bool ViewProviderPlane::isSelectable(void) const { return true; } bool ViewProviderPlane::setEdit(int ModNum) { return true; } void ViewProviderPlane::unsetEdit(int ModNum) { } Gui::SoFCSelection* ViewProviderPlane::createFromSettings() const { Gui::SoFCSelection* sel = new Gui::SoFCSelection(); float transparency; ParameterGrp::handle hGrp = Gui::WindowParameter::getDefaultParameter()->GetGroup("View"); bool enablePre = hGrp->GetBool("EnablePreselection", true); bool enableSel = hGrp->GetBool("EnableSelection", true); if (!enablePre) { sel->highlightMode = Gui::SoFCSelection::OFF; } else { // Search for a user defined value with the current color as default SbColor highlightColor = sel->colorHighlight.getValue(); unsigned long highlight = (unsigned long)(highlightColor.getPackedValue()); highlight = hGrp->GetUnsigned("HighlightColor", highlight); highlightColor.setPackedValue((uint32_t)highlight, transparency); sel->colorHighlight.setValue(highlightColor); } if (!enableSel || !Selectable.getValue()) { sel->selectionMode = Gui::SoFCSelection::SEL_OFF; } else { // Do the same with the selection color SbColor selectionColor = sel->colorSelection.getValue(); unsigned long selection = (unsigned long)(selectionColor.getPackedValue()); selection = hGrp->GetUnsigned("SelectionColor", selection); selectionColor.setPackedValue((uint32_t)selection, transparency); sel->colorSelection.setValue(selectionColor); } return sel; } // ----------------------------------------------------------------------------
/*************************************************************************** * Copyright (c) Juergen Riegel ([email protected]) 2012 * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <QApplication> # include <Inventor/SoPickedPoint.h> # include <Inventor/events/SoMouseButtonEvent.h> # include <Inventor/nodes/SoSeparator.h> # include <Inventor/nodes/SoBaseColor.h> # include <Inventor/nodes/SoFontStyle.h> # include <Inventor/nodes/SoPickStyle.h> # include <Inventor/nodes/SoText2.h> # include <Inventor/nodes/SoTranslation.h> # include <Inventor/nodes/SoCoordinate3.h> # include <Inventor/nodes/SoIndexedLineSet.h> # include <Inventor/nodes/SoMarkerSet.h> # include <Inventor/nodes/SoDrawStyle.h> #endif #include <Inventor/nodes/SoMaterial.h> #include <Inventor/nodes/SoAnnotation.h> #include <Inventor/details/SoLineDetail.h> #include <Inventor/nodes/SoAsciiText.h> #include "ViewProviderPlane.h" #include "SoFCSelection.h" #include "Application.h" #include "Document.h" #include "View3DInventorViewer.h" #include "Inventor/SoAutoZoomTranslation.h" #include "SoAxisCrossKit.h" #include "Window.h" //#include <SoDepthBuffer.h> #include <App/PropertyGeo.h> #include <App/PropertyStandard.h> #include <App/MeasureDistance.h> #include <Base/Console.h> using namespace Gui; PROPERTY_SOURCE(Gui::ViewProviderPlane, Gui::ViewProviderGeometryObject) ViewProviderPlane::ViewProviderPlane() { ADD_PROPERTY(Size,(1.0)); pMat = new SoMaterial(); pMat->ref(); float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox() SbVec3f verts[4] = { SbVec3f(size,size,0), SbVec3f(size,-size,0), SbVec3f(-size,-size,0), SbVec3f(-size,size,0), }; // indexes used to create the edges static const int32_t lines[6] = { 0,1,2,3,0,-1 }; // Create the selection node pcHighlight = createFromSettings(); pcHighlight->ref(); if (pcHighlight->selectionMode.getValue() == Gui::SoFCSelection::SEL_OFF) Selectable.setValue(false); pMat->diffuseColor.setNum(1); pMat->diffuseColor.set1Value(0, SbColor(50.f/255.f, 150.f/255.f, 250.f/255.f)); pCoords = new SoCoordinate3(); pCoords->ref(); pCoords->point.setNum(4); pCoords->point.setValues(0, 4, verts); pLines = new SoIndexedLineSet(); pLines->ref(); pLines->coordIndex.setNum(6); pLines->coordIndex.setValues(0, 6, lines); pFont = new SoFont(); pFont->size.setValue(Size.getValue()/10.); pTranslation = new SoTranslation(); pTranslation->translation.setValue(SbVec3f(-1.f,9.f/10.f,0.f)); pText = new SoAsciiText(); pText->width.setValue(-1); sPixmap = "view-measurement"; } ViewProviderPlane::~ViewProviderPlane() { pcHighlight->unref(); pCoords->unref(); pLines->unref(); pMat->unref(); } void ViewProviderPlane::onChanged(const App::Property* prop) { if (prop == &Size){ float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox() SbVec3f verts[4] = { SbVec3f(size,size,0), SbVec3f(size,-size,0), SbVec3f(-size,-size,0), SbVec3f(-size,size,0), }; pCoords->point.setValues(0, 4, verts); pFont->size.setValue(Size.getValue()/10.); pTranslation->translation.setValue(SbVec3f(-size,size*9./10.,0)); } else ViewProviderGeometryObject::onChanged(prop); } std::vector<std::string> ViewProviderPlane::getDisplayModes(void) const { // add modes std::vector<std::string> StrList; StrList.push_back("Base"); return StrList; } void ViewProviderPlane::setDisplayMode(const char* ModeName) { if (strcmp(ModeName, "Base") == 0) setDisplayMaskMode("Base"); ViewProviderGeometryObject::setDisplayMode(ModeName); } void ViewProviderPlane::attach(App::DocumentObject* pcObject) { ViewProviderGeometryObject::attach(pcObject); pcHighlight->objectName = pcObject->getNameInDocument(); pcHighlight->documentName = pcObject->getDocument()->getName(); pcHighlight->subElementName = "Main"; SoSeparator *sep = new SoSeparator(); SoAnnotation *lineSep = new SoAnnotation(); SoDrawStyle* style = new SoDrawStyle(); style->lineWidth = 2.0f; SoMaterialBinding* matBinding = new SoMaterialBinding; matBinding->value = SoMaterialBinding::OVERALL; sep->addChild(matBinding); sep->addChild(pMat); sep->addChild(pcHighlight); pcHighlight->addChild(style); pcHighlight->addChild(pCoords); pcHighlight->addChild(pLines); style = new SoDrawStyle(); style->lineWidth = 2.0f; style->linePattern.setValue(0xF000); lineSep->addChild(style); lineSep->addChild(pLines); lineSep->addChild(pFont); pText->string.setValue(SbString(pcObject->Label.getValue())); lineSep->addChild(pTranslation); lineSep->addChild(pText); pcHighlight->addChild(lineSep); pcHighlight->style = SoFCSelection::EMISSIVE_DIFFUSE; addDisplayMaskMode(sep, "Base"); } void ViewProviderPlane::updateData(const App::Property* prop) { pText->string.setValue(SbString(pcObject->Label.getValue())); ViewProviderGeometryObject::updateData(prop); } std::string ViewProviderPlane::getElement(const SoDetail* detail) const { if (detail) { if (detail->getTypeId() == SoLineDetail::getClassTypeId()) { const SoLineDetail* line_detail = static_cast<const SoLineDetail*>(detail); int edge = line_detail->getLineIndex(); if (edge == 0) { return std::string("Main"); } } } return std::string(""); } SoDetail* ViewProviderPlane::getDetail(const char* subelement) const { SoLineDetail* detail = 0; std::string subelem(subelement); int edge = -1; if(subelem == "Main") edge = 0; if(edge >= 0) { detail = new SoLineDetail(); detail->setPartIndex(edge); } return detail; } bool ViewProviderPlane::isSelectable(void) const { return true; } bool ViewProviderPlane::setEdit(int ModNum) { return true; } void ViewProviderPlane::unsetEdit(int ModNum) { } Gui::SoFCSelection* ViewProviderPlane::createFromSettings() const { Gui::SoFCSelection* sel = new Gui::SoFCSelection(); float transparency; ParameterGrp::handle hGrp = Gui::WindowParameter::getDefaultParameter()->GetGroup("View"); bool enablePre = hGrp->GetBool("EnablePreselection", true); bool enableSel = hGrp->GetBool("EnableSelection", true); if (!enablePre) { sel->highlightMode = Gui::SoFCSelection::OFF; } else { // Search for a user defined value with the current color as default SbColor highlightColor = sel->colorHighlight.getValue(); unsigned long highlight = (unsigned long)(highlightColor.getPackedValue()); highlight = hGrp->GetUnsigned("HighlightColor", highlight); highlightColor.setPackedValue((uint32_t)highlight, transparency); sel->colorHighlight.setValue(highlightColor); } if (!enableSel || !Selectable.getValue()) { sel->selectionMode = Gui::SoFCSelection::SEL_OFF; } else { // Do the same with the selection color SbColor selectionColor = sel->colorSelection.getValue(); unsigned long selection = (unsigned long)(selectionColor.getPackedValue()); selection = hGrp->GetUnsigned("SelectionColor", selection); selectionColor.setPackedValue((uint32_t)selection, transparency); sel->colorSelection.setValue(selectionColor); } return sel; } // ----------------------------------------------------------------------------
fix some warnings
fix some warnings
C++
lgpl-2.1
jriegel/FreeCAD,jriegel/FreeCAD,jriegel/FreeCAD,jriegel/FreeCAD,jriegel/FreeCAD
757ea38725e8061f0deb618b0ea40489b27c38ba
src/GuiBase/Viewer/Viewer.hpp
src/GuiBase/Viewer/Viewer.hpp
#ifndef RADIUMENGINE_VIEWER_HPP #define RADIUMENGINE_VIEWER_HPP #include <GuiBase/RaGuiBase.hpp> #include <atomic> #include <memory> #include <QWindow> #include <QThread> #include <Core/CoreMacros.hpp> #include <Core/Types.hpp> #include <Engine/RadiumEngine.hpp> #include <Engine/Renderer/Renderer.hpp> #include <GuiBase/Utils/KeyMappingManager.hpp> #include <GuiBase/Viewer/WindowQt.hpp> // Forward declarations class QOpenGLContext; class QSurfaceFormat; namespace Ra { namespace Gui { class CameraManipulator; class GizmoManager; class PickingManager; } // namespace Gui } // namespace Ra namespace Ra { namespace Gui { /** The Viewer is the main display class. It could be used as an independant window or * can be set as a central widget on a more complex gui by using the adapter from QWindow to QWidget * To do that, the following code could be used : * \code{.cpp} * m_viewer = new Ra::Gui::Viewer(); * QWidget * viewerwidget = QWidget::createWindowContainer(m_viewer); * setCentralWidget(viewerwidget); * \endcode * Whatever its usage (QWindow or QWidget) the Viewer has the same funtionalities. * Its acts as a bridge between the interface, the engine and the renderer * Among its responsibilities are : * * Owning the renderer and camera, and managing their lifetime. * * setting up the renderer and camera by keeping it informed of interfaces changes * (e.g. resize). * * catching user interaction (mouse clicks) at the lowest level and forward it to * the camera and the rest of the application * * Expose the asynchronous rendering interface */ class RA_GUIBASE_API Viewer : public WindowQt, public KeyMappingManageable<Viewer> { Q_OBJECT friend class KeyMappingManageable<Viewer>; public: /// Constructor explicit Viewer( QScreen* screen = nullptr ); /// Destructor ~Viewer() override; /// add observers to keyMappingManager for gizmo, camera and viewer. virtual void setupKeyMappingCallbacks(); // // Accessors // /// Access to the OpenGL context of the Viewer QOpenGLContext* getContext() const { return m_context.get(); } /// Set the current camera interface. void setCameraManipulator( CameraManipulator* ci ); /// Access to camera interface. CameraManipulator* getCameraManipulator(); /// Set the camera managed by the cameraInterface void setCamera( Engine::Camera* camera ); /// Access to gizmo manager GizmoManager* getGizmoManager(); /// Read-only access to renderer const Engine::Renderer* getRenderer() const; /// Read-write access to renderer Engine::Renderer* getRenderer(); /** Add a renderer and return its index. Need to be called when catching * \param e : unique_ptr to your own renderer * \return index of the newly added renderer * \code * int rendererId = addRenderer(new MyRenderer(width(), height())); * changeRenderer(rendererId); * getRenderer()->initialize(); * auto light = Ra::Core::make_shared<Engine::DirectionalLight>(); * m_camera->attachLight( light ); * \endcode */ int addRenderer( const std::shared_ptr<Engine::Renderer>& e ); /// Access to the feature picking manager PickingManager* getPickingManager(); // // Time dependent state management // /// Update the internal viewer state to the (application) time dt void update( const Scalar dt ); // // Rendering management // /// Start rendering (potentially asynchronously in a separate thread) void startRendering( const Scalar dt ); /// Blocks until rendering is finished. void swapBuffers(); /// @name /// Misc functions /// @{ /// Emits signals corresponding to picking requests. void processPicking(); /// Moves the camera so that the whole scene is visible. void fitCameraToScene( const Core::Aabb& sceneAabb ); /// Returns the names of the different registred renderers. std::vector<std::string> getRenderersName() const; /// Write the current frame as an image. Supports either BMP or PNG file names. void grabFrame( const std::string& filename ); void enableDebug(); const Core::Utils::Color& getBackgroundColor() const { return m_backgroundColor; } ///@} signals: bool glInitialized(); //! Emitted when GL context is ready. We except call to addRenderer here void rendererReady(); //! Emitted when the rendered is correctly initialized void rightClickPicking( const Ra::Engine::Renderer::PickingResult& result ); //! Emitted when the resut of a right click picking is known (for selection) void toggleBrushPicking( bool on ); //! Emitted when the corresponding key is released (see keyReleaseEvent) void needUpdate(); public slots: /// Tell the renderer to reload all shaders. void reloadShaders(); /// Set the final display texture void displayTexture( const QString& tex ); /// Set the renderer bool changeRenderer( int index ); /// Toggle the post-process effetcs void enablePostProcess( int enabled ); /// Toggle the debug drawing void enableDebugDraw( int enabled ); void setBackgroundColor( const Core::Utils::Color& background ); private slots: /// These slots are connected to the base class signals to properly handle /// concurrent access to the renderer. void onAboutToCompose(); void onAboutToResize(); void onResized(); void onFrameSwapped(); protected: /// create gizmos void createGizmoManager(); /// Initialize renderer internal state + configure lights. void initializeRenderer( Engine::Renderer* renderer ); // // OpenGL primitives // Not herited, defined here in the same way QOpenGLWidget define them. // /// Initialize openGL. Called on by the first "show" call to the main window. /// \warning This function is NOT reentrant, and may behave incorrectly /// if called at the same time than #intializeRenderer bool initializeGL() override; /// Resize the view port and the camera. Called by the resize event. void resizeGL( QResizeEvent* event ) override; Engine::Renderer::PickingMode getPickingMode( const Ra::Gui::KeyMappingManager::KeyMappingAction& action ) const; /// @name /// Qt event, do the viewer stuff, and call handle*Event to perform the /// actual event handling, according to keyMapping. ///@{ /// Do nothing if GL is not initialized, then call handleKeyPressEvent void keyPressEvent( QKeyEvent* event ) override; void keyReleaseEvent( QKeyEvent* event ) override; /// We intercept the mouse events in this widget to get the coordinates of the mouse /// in screen space. void mousePressEvent( QMouseEvent* event ) override; void mouseReleaseEvent( QMouseEvent* event ) override; void mouseMoveEvent( QMouseEvent* event ) override; void wheelEvent( QWheelEvent* event ) override; ///@} void showEvent( QShowEvent* ev ) override; /// @name /// handle the events, called by *Event, do the actual work, should be overriden in /// derived classes. ///@{ virtual void handleKeyPressEvent( QKeyEvent* event ); virtual void handleMousePressEvent( QMouseEvent* event, Ra::Engine::Renderer::PickingResult& result ); virtual void handleMouseReleaseEvent( QMouseEvent* event ); virtual void handleMouseMoveEvent( QMouseEvent* event, Ra::Engine::Renderer::PickingResult& result ); virtual void handleWheelEvent( QWheelEvent* event ); ///@} private: /// update keymapping according to keymapping manager's config, should be /// called each time the configuration changes, or added to observer's list /// with KeyMappingManager::addListener /// Called with KeyManageable::configureKeyMapping static void configureKeyMapping_impl(); Ra::Engine::Renderer::PickingResult pickAtPosition( Core::Vector2 position ); protected: ///\todo make the following private: /// Owning pointer to the renderers. std::vector<std::shared_ptr<Engine::Renderer>> m_renderers; Engine::Renderer* m_currentRenderer; /// Owning Pointer to the feature picking manager. PickingManager* m_pickingManager; bool m_isBrushPickingEnabled; float m_brushRadius; /// Owning pointer to the camera. std::unique_ptr<CameraManipulator> m_camera; /// Owning (QObject child) pointer to gizmo manager. GizmoManager* m_gizmoManager; #ifdef RADIUM_MULTITHREAD_RENDERING // TODO are we really use this ? Remove if we do not plan to do multi thread rendering /// Thread in which rendering is done. [[deprecated]] QThread* m_renderThread = nullptr; // We have to use a QThread for MT rendering #endif Core::Utils::Color m_backgroundColor{Core::Utils::Color::Grey( 0.0392_ra, 0_ra )}; KeyMappingManager::Context m_activeContext{}; #define KeyMappingViewer \ KMA_VALUE( VIEWER_PICKING ) \ KMA_VALUE( VIEWER_PICKING_VERTEX ) \ KMA_VALUE( VIEWER_PICKING_EDGE ) \ KMA_VALUE( VIEWER_PICKING_TRIANGLE ) \ KMA_VALUE( VIEWER_PICKING_MULTI_CIRCLE ) \ KMA_VALUE( VIEWER_RAYCAST ) \ KMA_VALUE( VIEWER_SCALE_BRUSH ) \ KMA_VALUE( VIEWER_RELOAD_SHADERS ) \ KMA_VALUE( VIEWER_TOGGLE_WIREFRAME ) #define KMA_VALUE( x ) static KeyMappingManager::KeyMappingAction x; KeyMappingViewer #undef KMA_VALUE }; } // namespace Gui } // namespace Ra #endif // RADIUMENGINE_VIEWER_HPP
#ifndef RADIUMENGINE_VIEWER_HPP #define RADIUMENGINE_VIEWER_HPP #include <GuiBase/RaGuiBase.hpp> #include <atomic> #include <memory> #include <QWindow> #include <QThread> #include <Core/CoreMacros.hpp> #include <Core/Types.hpp> #include <Engine/RadiumEngine.hpp> #include <Engine/Renderer/Renderer.hpp> #include <GuiBase/Utils/KeyMappingManager.hpp> #include <GuiBase/Viewer/WindowQt.hpp> // Forward declarations class QOpenGLContext; class QSurfaceFormat; namespace Ra { namespace Gui { class CameraManipulator; class GizmoManager; class PickingManager; } // namespace Gui } // namespace Ra namespace Ra { namespace Gui { /** The Viewer is the main display class. It could be used as an independant window or * can be set as a central widget on a more complex gui by using the adapter from QWindow to QWidget * To do that, the following code could be used : * \code{.cpp} * m_viewer = new Ra::Gui::Viewer(); * QWidget * viewerwidget = QWidget::createWindowContainer(m_viewer); * setCentralWidget(viewerwidget); * \endcode * Whatever its usage (QWindow or QWidget) the Viewer has the same funtionalities. * Its acts as a bridge between the interface, the engine and the renderer * Among its responsibilities are : * * Owning the renderer and camera, and managing their lifetime. * * setting up the renderer and camera by keeping it informed of interfaces changes * (e.g. resize). * * catching user interaction (mouse clicks) at the lowest level and forward it to * the camera and the rest of the application * * Expose the asynchronous rendering interface */ class RA_GUIBASE_API Viewer : public WindowQt, public KeyMappingManageable<Viewer> { Q_OBJECT friend class KeyMappingManageable<Viewer>; public: /// Constructor explicit Viewer( QScreen* screen = nullptr ); /// Destructor ~Viewer() override; /// add observers to keyMappingManager for gizmo, camera and viewer. virtual void setupKeyMappingCallbacks(); // // Accessors // /// Access to the OpenGL context of the Viewer QOpenGLContext* getContext() const { return m_context.get(); } /// Set the current camera interface. void setCameraManipulator( CameraManipulator* ci ); /// Access to camera interface. CameraManipulator* getCameraManipulator(); /// Set the camera managed by the cameraInterface void setCamera( Engine::Camera* camera ); /// Access to gizmo manager GizmoManager* getGizmoManager(); /// Read-only access to renderer const Engine::Renderer* getRenderer() const; /// Read-write access to renderer Engine::Renderer* getRenderer(); /** Add a renderer and return its index. Need to be called when catching * \param e : your own renderer * \return index of the newly added renderer * \code * int rendererId = addRenderer(new MyRenderer(width(), height())); * changeRenderer(rendererId); * getRenderer()->initialize(); * auto light = Ra::Core::make_shared<Engine::DirectionalLight>(); * m_camera->attachLight( light ); * \endcode */ int addRenderer( const std::shared_ptr<Engine::Renderer>& e ); /// Access to the feature picking manager PickingManager* getPickingManager(); // // Time dependent state management // /// Update the internal viewer state to the (application) time dt void update( const Scalar dt ); // // Rendering management // /// Start rendering (potentially asynchronously in a separate thread) void startRendering( const Scalar dt ); /// Blocks until rendering is finished. void swapBuffers(); /// @name /// Misc functions /// @{ /// Emits signals corresponding to picking requests. void processPicking(); /// Moves the camera so that the whole scene is visible. void fitCameraToScene( const Core::Aabb& sceneAabb ); /// Returns the names of the different registred renderers. std::vector<std::string> getRenderersName() const; /// Write the current frame as an image. Supports either BMP or PNG file names. void grabFrame( const std::string& filename ); void enableDebug(); const Core::Utils::Color& getBackgroundColor() const { return m_backgroundColor; } ///@} signals: bool glInitialized(); //! Emitted when GL context is ready. We except call to addRenderer here void rendererReady(); //! Emitted when the rendered is correctly initialized void rightClickPicking( const Ra::Engine::Renderer::PickingResult& result ); //! Emitted when the resut of a right click picking is known (for selection) void toggleBrushPicking( bool on ); //! Emitted when the corresponding key is released (see keyReleaseEvent) void needUpdate(); public slots: /// Tell the renderer to reload all shaders. void reloadShaders(); /// Set the final display texture void displayTexture( const QString& tex ); /// Set the renderer bool changeRenderer( int index ); /// Toggle the post-process effetcs void enablePostProcess( int enabled ); /// Toggle the debug drawing void enableDebugDraw( int enabled ); void setBackgroundColor( const Core::Utils::Color& background ); private slots: /// These slots are connected to the base class signals to properly handle /// concurrent access to the renderer. void onAboutToCompose(); void onAboutToResize(); void onResized(); void onFrameSwapped(); protected: /// create gizmos void createGizmoManager(); /// Initialize renderer internal state + configure lights. void initializeRenderer( Engine::Renderer* renderer ); // // OpenGL primitives // Not herited, defined here in the same way QOpenGLWidget define them. // /// Initialize openGL. Called on by the first "show" call to the main window. /// \warning This function is NOT reentrant, and may behave incorrectly /// if called at the same time than #intializeRenderer bool initializeGL() override; /// Resize the view port and the camera. Called by the resize event. void resizeGL( QResizeEvent* event ) override; Engine::Renderer::PickingMode getPickingMode( const Ra::Gui::KeyMappingManager::KeyMappingAction& action ) const; /// @name /// Qt event, do the viewer stuff, and call handle*Event to perform the /// actual event handling, according to keyMapping. ///@{ /// Do nothing if GL is not initialized, then call handleKeyPressEvent void keyPressEvent( QKeyEvent* event ) override; void keyReleaseEvent( QKeyEvent* event ) override; /// We intercept the mouse events in this widget to get the coordinates of the mouse /// in screen space. void mousePressEvent( QMouseEvent* event ) override; void mouseReleaseEvent( QMouseEvent* event ) override; void mouseMoveEvent( QMouseEvent* event ) override; void wheelEvent( QWheelEvent* event ) override; ///@} void showEvent( QShowEvent* ev ) override; /// @name /// handle the events, called by *Event, do the actual work, should be overriden in /// derived classes. ///@{ virtual void handleKeyPressEvent( QKeyEvent* event ); virtual void handleMousePressEvent( QMouseEvent* event, Ra::Engine::Renderer::PickingResult& result ); virtual void handleMouseReleaseEvent( QMouseEvent* event ); virtual void handleMouseMoveEvent( QMouseEvent* event, Ra::Engine::Renderer::PickingResult& result ); virtual void handleWheelEvent( QWheelEvent* event ); ///@} private: /// update keymapping according to keymapping manager's config, should be /// called each time the configuration changes, or added to observer's list /// with KeyMappingManager::addListener /// Called with KeyManageable::configureKeyMapping static void configureKeyMapping_impl(); Ra::Engine::Renderer::PickingResult pickAtPosition( Core::Vector2 position ); protected: ///\todo make the following private: /// Owning pointer to the renderers. std::vector<std::shared_ptr<Engine::Renderer>> m_renderers; Engine::Renderer* m_currentRenderer; /// Owning Pointer to the feature picking manager. PickingManager* m_pickingManager; bool m_isBrushPickingEnabled; float m_brushRadius; /// Owning pointer to the camera. std::unique_ptr<CameraManipulator> m_camera; /// Owning (QObject child) pointer to gizmo manager. GizmoManager* m_gizmoManager; #ifdef RADIUM_MULTITHREAD_RENDERING // TODO are we really use this ? Remove if we do not plan to do multi thread rendering /// Thread in which rendering is done. [[deprecated]] QThread* m_renderThread = nullptr; // We have to use a QThread for MT rendering #endif Core::Utils::Color m_backgroundColor{Core::Utils::Color::Grey( 0.0392_ra, 0_ra )}; KeyMappingManager::Context m_activeContext{}; #define KeyMappingViewer \ KMA_VALUE( VIEWER_PICKING ) \ KMA_VALUE( VIEWER_PICKING_VERTEX ) \ KMA_VALUE( VIEWER_PICKING_EDGE ) \ KMA_VALUE( VIEWER_PICKING_TRIANGLE ) \ KMA_VALUE( VIEWER_PICKING_MULTI_CIRCLE ) \ KMA_VALUE( VIEWER_RAYCAST ) \ KMA_VALUE( VIEWER_SCALE_BRUSH ) \ KMA_VALUE( VIEWER_RELOAD_SHADERS ) \ KMA_VALUE( VIEWER_TOGGLE_WIREFRAME ) #define KMA_VALUE( x ) static KeyMappingManager::KeyMappingAction x; KeyMappingViewer #undef KMA_VALUE }; } // namespace Gui } // namespace Ra #endif // RADIUMENGINE_VIEWER_HPP
fix comment typo.
[guibase] Viewer: fix comment typo.
C++
bsd-3-clause
Zouch/Radium-Engine,Zouch/Radium-Engine
907af154433122890a9d406fc8b2d445137c8193
test/plugin/TestPluginApp.cpp
test/plugin/TestPluginApp.cpp
/* * Copyright (c) 2015, 2016, 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <mpi.h> #include <stdint.h> #include "geopm.h" #include "geopm_time.h" #include "SharedMemory.hpp" #include "ProfileTable.hpp" int main(int argc, char **argv) { const char *policy_name = "geopm_test_plugin_policy"; const char *report_name = "TestPluginApp-prof.txt"; const double imbalance = 0.10; /// @todo: Lost find method. /// const int rank_per_node = 8; const size_t clock_req_base = 100000000000; int comm_size, comm_rank; /// @todo: Lost find method. /// int local_rank; uint64_t region_id; size_t clock_req, num_clock; double progress, time_delta, clock_freq; struct geopm_time_s last_time; struct geopm_time_s curr_time; struct geopm_prof_message_s message; setenv("GEOPM_POLICY", policy_name, 1); setenv("GEOPM_REPORT", report_name, 1); MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &comm_size); MPI_Comm_rank(MPI_COMM_WORLD, &comm_rank); /// @todo: Lost find method. /// local_rank = comm_rank % rank_per_node; geopm::SharedMemoryUser shmem("/geopm_test_platform_shmem_freq", 5.0); geopm::ProfileTable table(shmem.size(), shmem.pointer()); geopm_prof_region("main_loop", GEOPM_REGION_HINT_UNKNOWN, &region_id); // imbalance is proportional to rank and ranges from 0 to 10% clock_req = clock_req_base * (1.0 + (comm_rank * imbalance) / comm_size); geopm_prof_enter(region_id); geopm_time(&last_time); num_clock = 0; while (num_clock < clock_req) { geopm_time(&curr_time); time_delta = geopm_time_diff(&last_time, &curr_time); /// @todo: Lost find method. /// message = table.find(local_rank); clock_freq = message.progress; num_clock += time_delta * clock_freq; progress = (double)num_clock / (double)clock_req; progress = progress <= 1.0 ? progress : 1.0; geopm_prof_progress(region_id, progress); last_time = curr_time; } geopm_prof_exit(region_id); MPI_Finalize(); return 0; }
/* * Copyright (c) 2015, 2016, 2017, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <mpi.h> #include <stdint.h> #include "geopm.h" #include "geopm_time.h" #include "SharedMemory.hpp" #include "ProfileTable.hpp" int main(int argc, char **argv) { const char *policy_name = "geopm_test_plugin_policy"; const char *report_name = "TestPluginApp-prof.txt"; const double imbalance = 0.10; /// @todo: Lost find method. /// const int rank_per_node = 8; const size_t clock_req_base = 100000000000; int comm_size, comm_rank; /// @todo: Lost find method. /// int local_rank; uint64_t region_id; size_t clock_req, num_clock; double progress, time_delta, clock_freq; struct geopm_time_s last_time; struct geopm_time_s curr_time; setenv("GEOPM_POLICY", policy_name, 1); setenv("GEOPM_REPORT", report_name, 1); MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &comm_size); MPI_Comm_rank(MPI_COMM_WORLD, &comm_rank); /// @todo: Lost find method. /// local_rank = comm_rank % rank_per_node; geopm::SharedMemoryUser shmem("/geopm_test_platform_shmem_freq", 5.0); geopm::ProfileTable table(shmem.size(), shmem.pointer()); geopm_prof_region("main_loop", GEOPM_REGION_HINT_UNKNOWN, &region_id); // imbalance is proportional to rank and ranges from 0 to 10% clock_req = clock_req_base * (1.0 + (comm_rank * imbalance) / comm_size); geopm_prof_enter(region_id); geopm_time(&last_time); num_clock = 0; while (num_clock < clock_req) { geopm_time(&curr_time); time_delta = geopm_time_diff(&last_time, &curr_time); /// @todo: Lost find method. std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::iterator it; size_t len; table.dump(it, len); clock_freq = (*it).second.progress; num_clock += time_delta * clock_freq; progress = (double)num_clock / (double)clock_req; progress = progress <= 1.0 ? progress : 1.0; geopm_prof_progress(region_id, progress); last_time = curr_time; } geopm_prof_exit(region_id); MPI_Finalize(); return 0; }
Fix compile time error due to passing uninitialized variable.
Fix compile time error due to passing uninitialized variable. Change-Id: Ibc30d475a20f66ce19ad39ec632c16b2fbf3ef3c Signed-off-by: Christopher M. Cantalupo <[email protected]>
C++
bsd-3-clause
geopm/geopm,cmcantalupo/geopm,cmcantalupo/geopm,geopm/geopm,geopm/geopm,cmcantalupo/geopm,cmcantalupo/geopm,geopm/geopm,geopm/geopm,cmcantalupo/geopm
fdf6ccaea0d23972978197281984dec2ddc9ecf3
src/search/tree/PV.hpp
src/search/tree/PV.hpp
/* PV.hpp * * Kubo Ryosuke */ #ifndef SUNFISH_SEARCH_TREE_PV_HPP__ #define SUNFISH_SEARCH_TREE_PV_HPP__ #include "common/Def.hpp" #include "core/move/Moves.hpp" #include <cstdint> #include <cstring> #include <sstream> namespace sunfish { class PV { public: using SizeType = uint32_t; static CONSTEXPR_CONST SizeType StackSize = 64; PV() : num_(0) { } PV(const PV&) = default; PV(PV&&) = default; PV& operator=(const PV&) = default; PV& operator=(PV&&) = default; void clear() { num_ = 0; } SizeType size() const { return num_; } void set(const Move& move, const PV& pv) { moves_[0] = move; num_ = std::min(pv.num_ + 1, StackSize); memcpy(&moves_[1], pv.moves_, sizeof(moves_[0]) * (num_ - 1)); } const Move& get(SizeType depth) const { return moves_[depth]; } std::string toString() const { std::ostringstream oss; for (SizeType i = 0; i < num_; i++) { if (i != 0) { oss << ' '; } oss << moves_[i].toString(); } return oss.str(); } std::string toStringSFEN() const { std::ostringstream oss; for (SizeType i = 0; i < num_; i++) { if (i != 0) { oss << ' '; } oss << moves_[i].toStringSFEN(); } return oss.str(); } friend std::ostream& operator<<(std::ostream& os, const sunfish::PV& pv) { os << pv.toString(); return os; } private: SizeType num_; Move moves_[StackSize]; }; } // namespace sunfish #endif // SUNFISH_SEARCH_TREE_PV_HPP__
/* PV.hpp * * Kubo Ryosuke */ #ifndef SUNFISH_SEARCH_TREE_PV_HPP__ #define SUNFISH_SEARCH_TREE_PV_HPP__ #include "common/Def.hpp" #include "core/move/Moves.hpp" #include <cstdint> #include <cstring> #include <sstream> namespace sunfish { class PV { public: using SizeType = uint32_t; static CONSTEXPR_CONST SizeType StackSize = 64; PV() : num_(0) { } PV(const PV&) = default; PV(PV&&) = default; PV& operator=(const PV&) = default; PV& operator=(PV&&) = default; void clear() { num_ = 0; } SizeType size() const { return num_; } void set(const Move& move, const PV& pv) { moves_[0] = move; // static_cast is required on Clang. // See https://trello.com/c/iJqg1GqN num_ = std::min(pv.num_ + 1, static_cast<SizeType>(StackSize)); memcpy(&moves_[1], pv.moves_, sizeof(moves_[0]) * (num_ - 1)); } const Move& get(SizeType depth) const { return moves_[depth]; } std::string toString() const { std::ostringstream oss; for (SizeType i = 0; i < num_; i++) { if (i != 0) { oss << ' '; } oss << moves_[i].toString(); } return oss.str(); } std::string toStringSFEN() const { std::ostringstream oss; for (SizeType i = 0; i < num_; i++) { if (i != 0) { oss << ' '; } oss << moves_[i].toStringSFEN(); } return oss.str(); } friend std::ostream& operator<<(std::ostream& os, const sunfish::PV& pv) { os << pv.toString(); return os; } private: SizeType num_; Move moves_[StackSize]; }; } // namespace sunfish #endif // SUNFISH_SEARCH_TREE_PV_HPP__
Fix a link error (https://trello.com/c/iJqg1GqN)
Fix a link error (https://trello.com/c/iJqg1GqN)
C++
mit
sunfish-shogi/sunfish4,sunfish-shogi/sunfish4,sunfish-shogi/sunfish4,sunfish-shogi/sunfish4
399e8be1f8667e8abedad901e2bc597366755a72
Libs/Core/ctkDependencyGraph.cxx
Libs/Core/ctkDependencyGraph.cxx
// QT includes #include <QQueue> #include <QVarLengthArray> #include <QDebug> // CTK includes #include "ctkDependencyGraph.h" // STD includes #include <iostream> #define MAXV 100 #define MAXDEGREE 50 //---------------------------------------------------------------------------- class ctkDependencyGraph::ctkInternal { public: ctkInternal(ctkDependencyGraph* p); /// Compute indegree void computeIndegrees(QVarLengthArray<int, MAXV>& computedIndegrees); /// Traverse tree using Depth-first_search void traverseUsingDFS(int v); /// Called each time an edge is visited void processEdge(int from, int to); /// Called each time a vertex is processed void processVertex(int v); void setEdge(int vertice, int degree, int value); int edge(int vertice, int degree); /// See http://en.wikipedia.org/wiki/Adjacency_list QVarLengthArray<QVarLengthArray<int,MAXDEGREE>*, MAXV+1> Edges; QVarLengthArray<int, MAXV+1> Degree; int NVertices; int NEdges; /// Structure used by DFS /// See http://en.wikipedia.org/wiki/Depth-first_search QVarLengthArray<bool, MAXV> Processed; // processed vertices QVarLengthArray<bool, MAXV> Discovered; // discovered vertices QVarLengthArray<int, MAXV> Parent; // relation discovered bool Abort; // Flag indicating if traverse should be aborted bool Verbose; bool CycleDetected; int CycleOrigin; int CycleEnd; QList<int> ListOfEdgeToExclude; /// Pointer to the public API ctkDependencyGraph* P; }; //---------------------------------------------------------------------------- // ctkInternal methods //---------------------------------------------------------------------------- ctkDependencyGraph::ctkInternal::ctkInternal(ctkDependencyGraph* p) { Q_ASSERT(p); this->P = p; this->NVertices = 0; this->NEdges = 0; this->Abort = false; this->Verbose = false; this->CycleDetected = false; this->CycleOrigin = 0; this->CycleEnd = 0; } //---------------------------------------------------------------------------- void ctkDependencyGraph::ctkInternal::computeIndegrees(QVarLengthArray<int, MAXV>& computedIndegrees) { for (int i=1; i <= this->NVertices; i++) { computedIndegrees[i] = 0; } for (int i=1; i <= this->NVertices; i++) { for (int j=0; j < this->Degree[i]; j++) { computedIndegrees[ this->edge(i,j) ] ++; } } } //---------------------------------------------------------------------------- void ctkDependencyGraph::ctkInternal::traverseUsingDFS(int v) { // allow for search termination if (this->Abort) { return; } this->Discovered[v] = true; this->processVertex(v); int y; // successor vertex for (int i=0; i<this->Degree[v]; i++) { y = this->edge(v, i); if (this->P->shouldExcludeEdge(this->edge(v, i)) == false) { if (this->Discovered[y] == false) { this->Parent[y] = v; this->traverseUsingDFS(y); } else { if (this->Processed[y] == false) { this->processEdge(v,y); } } } if (this->Abort) { return; } } this->Processed[v] = true; } //---------------------------------------------------------------------------- void ctkDependencyGraph::ctkInternal::processEdge(int from, int to) { if (this->Parent[from] != to) { this->CycleDetected = true; this->CycleOrigin = to; this->CycleEnd = from; if (this->Verbose) { QList<int> path; this->P->findPath(from, to, path); qWarning() << "Cycle detected from " << to << " to " << from; qWarning() << " " << path; path.clear(); this->P->findPath(to, from, path); qWarning() << " " << path; } this->Abort = true; } } //---------------------------------------------------------------------------- void ctkDependencyGraph::ctkInternal::processVertex(int v) { if (this->Verbose) { qDebug() << "processed vertex " << v; } } //---------------------------------------------------------------------------- void ctkDependencyGraph::ctkInternal::setEdge(int vertice, int degree, int value) { Q_ASSERT(vertice <= this->NVertices); Q_ASSERT(degree < MAXDEGREE); (*this->Edges[vertice])[degree] = value; } //---------------------------------------------------------------------------- int ctkDependencyGraph::ctkInternal::edge(int vertice, int degree) { Q_ASSERT(vertice <= this->NVertices); Q_ASSERT(degree < MAXDEGREE); return (*this->Edges[vertice])[degree]; } //---------------------------------------------------------------------------- // ctkDependencyGraph methods //---------------------------------------------------------------------------- ctkDependencyGraph::ctkDependencyGraph(int nvertices, int nedges) { this->Internal = new ctkInternal(this); this->Internal->NVertices = nvertices; this->Internal->NEdges = nedges; // Resize internal array this->Internal->Processed.resize(nvertices + 1); this->Internal->Discovered.resize(nvertices + 1); this->Internal->Parent.resize(nvertices + 1); this->Internal->Edges.resize(nvertices + 1); this->Internal->Degree.resize(nvertices + 1); for (int i=1; i <= nvertices; i++) { this->Internal->Degree[i] = 0; } // initialize Edge adjacency list for (int i=0; i <= nvertices; i++) { this->Internal->Edges[i] = new QVarLengthArray<int, MAXDEGREE>(); this->Internal->Edges[i]->resize(MAXDEGREE); } // initialize search for (int i=1; i <= nvertices; i++) { this->Internal->Processed[i] = false; this->Internal->Discovered[i] = false; this->Internal->Parent[i] = -1; } } //---------------------------------------------------------------------------- ctkDependencyGraph::~ctkDependencyGraph() { delete this->Internal; } //---------------------------------------------------------------------------- void ctkDependencyGraph::printAdditionalInfo() { qDebug() << "ctkDependencyGraph (" << this << ")" << endl << " NVertices:" << this->numberOfVertices() << endl << " NEdges:" << this->numberOfEdges() << endl << " Abort:" << this->Internal->Abort; qDebug() << " [Processed]"; for(int i=1; i < this->Internal->Processed.size(); i++) { qDebug() << i << "->" << this->Internal->Processed[i]; } qDebug() << " [Discovered]"; for(int i=1; i < this->Internal->Discovered.size(); i++) { qDebug() << i << "->" << this->Internal->Discovered[i]; } qDebug() << " [Parent]"; for(int i=1; i < this->Internal->Parent.size(); i++) { qDebug() << i << "->" << this->Internal->Parent[i]; } qDebug() << " [Graph]"; this->printGraph(); } //---------------------------------------------------------------------------- void ctkDependencyGraph::printGraph() { for(int i=1; i <= this->Internal->NVertices; i++) { std::cout << i << ":"; for (int j=0; j < this->Internal->Degree[i]; j++) { std::cout << " " << this->Internal->edge(i, j); } std::cout << std::endl; } } //---------------------------------------------------------------------------- int ctkDependencyGraph::numberOfVertices() { return this->Internal->NVertices; } //---------------------------------------------------------------------------- int ctkDependencyGraph::numberOfEdges() { return this->Internal->NEdges; } //---------------------------------------------------------------------------- void ctkDependencyGraph::setVerbose(bool verbose) { this->Internal->Verbose = verbose; } //---------------------------------------------------------------------------- void ctkDependencyGraph::setEdgeListToExclude(const QList<int>& list) { this->Internal->ListOfEdgeToExclude = list; } //---------------------------------------------------------------------------- bool ctkDependencyGraph::shouldExcludeEdge(int edge) { return this->Internal->ListOfEdgeToExclude.contains(edge); } //---------------------------------------------------------------------------- bool ctkDependencyGraph::checkForCycle() { if (this->Internal->NEdges > 0) { // get a valid vertice Id int verticeId = 1; this->Internal->traverseUsingDFS(verticeId); } return this->cycleDetected(); } //---------------------------------------------------------------------------- bool ctkDependencyGraph::cycleDetected() { return this->Internal->CycleDetected; } //---------------------------------------------------------------------------- int ctkDependencyGraph::cycleOrigin() { return this->Internal->CycleOrigin; } //---------------------------------------------------------------------------- int ctkDependencyGraph::cycleEnd() { return this->Internal->CycleEnd; } //---------------------------------------------------------------------------- void ctkDependencyGraph::insertEdge(int from, int to) { Q_ASSERT(from > 0 && from <= this->Internal->NVertices); Q_ASSERT(to > 0 && to <= this->Internal->NVertices); // resize if needed int capacity = this->Internal->Edges[from]->capacity(); if (this->Internal->Degree[from] > capacity) { this->Internal->Edges[from]->resize(capacity + capacity * 0.3); } this->Internal->setEdge(from, this->Internal->Degree[from], to); this->Internal->Degree[from]++; this->Internal->NEdges++; } //---------------------------------------------------------------------------- void ctkDependencyGraph::findPath(int from, int to, QList<int>& path) { if ((from == to) || (to == -1)) { path << from; } else { this->findPath(from, this->Internal->Parent[to], path); path << to; } } //---------------------------------------------------------------------------- bool ctkDependencyGraph::topologicalSort(QList<int>& sorted) { QVarLengthArray<int, MAXV> indegree; // indegree of each vertex QQueue<int> zeroin; // vertices of indegree 0 int x, y; // current and next vertex indegree.resize(this->Internal->NVertices + 1); // resize if needed if (this->Internal->NVertices > MAXV) { indegree.resize(this->Internal->NVertices); } this->Internal->computeIndegrees(indegree); for (int i=1; i <= this->Internal->NVertices; i++) { if (indegree[i] == 0) { zeroin.enqueue(i); } } int j=0; while (zeroin.empty() == false) { j = j+1; x = zeroin.dequeue(); sorted << x; for (int i=0; i < this->Internal->Degree[x]; i++) { y = this->Internal->edge(x, i); indegree[y] --; if (indegree[y] == 0) { zeroin.enqueue(y); } } } if (j != this->Internal->NVertices) { return false; } return true; }
// QT includes #include <QQueue> #include <QVarLengthArray> #include <QDebug> // CTK includes #include "ctkDependencyGraph.h" // STD includes #include <iostream> #define MAXV 100 #define MAXDEGREE 50 //---------------------------------------------------------------------------- class ctkDependencyGraph::ctkInternal { public: ctkInternal(ctkDependencyGraph* p); /// Compute indegree void computeIndegrees(QVarLengthArray<int, MAXV>& computedIndegrees); /// Traverse tree using Depth-first_search void traverseUsingDFS(int v); /// Called each time an edge is visited void processEdge(int from, int to); /// Called each time a vertex is processed void processVertex(int v); void setEdge(int vertice, int degree, int value); int edge(int vertice, int degree); /// See http://en.wikipedia.org/wiki/Adjacency_list QVarLengthArray<QVarLengthArray<int,MAXDEGREE>*, MAXV+1> Edges; QVarLengthArray<int, MAXV+1> Degree; int NVertices; int NEdges; /// Structure used by DFS /// See http://en.wikipedia.org/wiki/Depth-first_search QVarLengthArray<bool, MAXV> Processed; // processed vertices QVarLengthArray<bool, MAXV> Discovered; // discovered vertices QVarLengthArray<int, MAXV> Parent; // relation discovered bool Abort; // Flag indicating if traverse should be aborted bool Verbose; bool CycleDetected; int CycleOrigin; int CycleEnd; QList<int> ListOfEdgeToExclude; /// Pointer to the public API ctkDependencyGraph* P; }; //---------------------------------------------------------------------------- // ctkInternal methods //---------------------------------------------------------------------------- ctkDependencyGraph::ctkInternal::ctkInternal(ctkDependencyGraph* p) { Q_ASSERT(p); this->P = p; this->NVertices = 0; this->NEdges = 0; this->Abort = false; this->Verbose = false; this->CycleDetected = false; this->CycleOrigin = 0; this->CycleEnd = 0; } //---------------------------------------------------------------------------- void ctkDependencyGraph::ctkInternal::computeIndegrees(QVarLengthArray<int, MAXV>& computedIndegrees) { for (int i=1; i <= this->NVertices; i++) { computedIndegrees[i] = 0; } for (int i=1; i <= this->NVertices; i++) { for (int j=0; j < this->Degree[i]; j++) { computedIndegrees[ this->edge(i,j) ] ++; } } } //---------------------------------------------------------------------------- void ctkDependencyGraph::ctkInternal::traverseUsingDFS(int v) { // allow for search termination if (this->Abort) { return; } this->Discovered[v] = true; this->processVertex(v); int y; // successor vertex for (int i=0; i<this->Degree[v]; i++) { y = this->edge(v, i); if (this->P->shouldExcludeEdge(this->edge(v, i)) == false) { if (this->Discovered[y] == false) { this->Parent[y] = v; this->traverseUsingDFS(y); } else { if (this->Processed[y] == false) { this->processEdge(v,y); } } } if (this->Abort) { return; } } this->Processed[v] = true; } //---------------------------------------------------------------------------- void ctkDependencyGraph::ctkInternal::processEdge(int from, int to) { if (this->Parent[from] != to) { this->CycleDetected = true; this->CycleOrigin = to; this->CycleEnd = from; if (this->Verbose) { QList<int> path; this->P->findPath(from, to, path); qWarning() << "Cycle detected from " << to << " to " << from; qWarning() << " " << path; path.clear(); this->P->findPath(to, from, path); qWarning() << " " << path; } this->Abort = true; } } //---------------------------------------------------------------------------- void ctkDependencyGraph::ctkInternal::processVertex(int v) { if (this->Verbose) { qDebug() << "processed vertex " << v; } } //---------------------------------------------------------------------------- void ctkDependencyGraph::ctkInternal::setEdge(int vertice, int degree, int value) { Q_ASSERT(vertice <= this->NVertices); Q_ASSERT(degree < MAXDEGREE); (*this->Edges[vertice])[degree] = value; } //---------------------------------------------------------------------------- int ctkDependencyGraph::ctkInternal::edge(int vertice, int degree) { Q_ASSERT(vertice <= this->NVertices); Q_ASSERT(degree < MAXDEGREE); return (*this->Edges[vertice])[degree]; } //---------------------------------------------------------------------------- // ctkDependencyGraph methods //---------------------------------------------------------------------------- ctkDependencyGraph::ctkDependencyGraph(int nvertices, int nedges) { this->Internal = new ctkInternal(this); this->Internal->NVertices = nvertices; this->Internal->NEdges = nedges; // Resize internal array this->Internal->Processed.resize(nvertices + 1); this->Internal->Discovered.resize(nvertices + 1); this->Internal->Parent.resize(nvertices + 1); this->Internal->Edges.resize(nvertices + 1); this->Internal->Degree.resize(nvertices + 1); for (int i=1; i <= nvertices; i++) { this->Internal->Degree[i] = 0; } // initialize Edge adjacency list for (int i=0; i <= nvertices; i++) { this->Internal->Edges[i] = new QVarLengthArray<int, MAXDEGREE>(); this->Internal->Edges[i]->resize(MAXDEGREE); } // initialize search for (int i=1; i <= nvertices; i++) { this->Internal->Processed[i] = false; this->Internal->Discovered[i] = false; this->Internal->Parent[i] = -1; } } //---------------------------------------------------------------------------- ctkDependencyGraph::~ctkDependencyGraph() { // Clean memory for (int i=0; i <= this->Internal->NVertices; i++) { delete this->Internal->Edges[i]; } delete this->Internal; } //---------------------------------------------------------------------------- void ctkDependencyGraph::printAdditionalInfo() { qDebug() << "ctkDependencyGraph (" << this << ")" << endl << " NVertices:" << this->numberOfVertices() << endl << " NEdges:" << this->numberOfEdges() << endl << " Abort:" << this->Internal->Abort; qDebug() << " [Processed]"; for(int i=1; i < this->Internal->Processed.size(); i++) { qDebug() << i << "->" << this->Internal->Processed[i]; } qDebug() << " [Discovered]"; for(int i=1; i < this->Internal->Discovered.size(); i++) { qDebug() << i << "->" << this->Internal->Discovered[i]; } qDebug() << " [Parent]"; for(int i=1; i < this->Internal->Parent.size(); i++) { qDebug() << i << "->" << this->Internal->Parent[i]; } qDebug() << " [Graph]"; this->printGraph(); } //---------------------------------------------------------------------------- void ctkDependencyGraph::printGraph() { for(int i=1; i <= this->Internal->NVertices; i++) { std::cout << i << ":"; for (int j=0; j < this->Internal->Degree[i]; j++) { std::cout << " " << this->Internal->edge(i, j); } std::cout << std::endl; } } //---------------------------------------------------------------------------- int ctkDependencyGraph::numberOfVertices() { return this->Internal->NVertices; } //---------------------------------------------------------------------------- int ctkDependencyGraph::numberOfEdges() { return this->Internal->NEdges; } //---------------------------------------------------------------------------- void ctkDependencyGraph::setVerbose(bool verbose) { this->Internal->Verbose = verbose; } //---------------------------------------------------------------------------- void ctkDependencyGraph::setEdgeListToExclude(const QList<int>& list) { this->Internal->ListOfEdgeToExclude = list; } //---------------------------------------------------------------------------- bool ctkDependencyGraph::shouldExcludeEdge(int edge) { return this->Internal->ListOfEdgeToExclude.contains(edge); } //---------------------------------------------------------------------------- bool ctkDependencyGraph::checkForCycle() { if (this->Internal->NEdges > 0) { // get a valid vertice Id int verticeId = 1; this->Internal->traverseUsingDFS(verticeId); } return this->cycleDetected(); } //---------------------------------------------------------------------------- bool ctkDependencyGraph::cycleDetected() { return this->Internal->CycleDetected; } //---------------------------------------------------------------------------- int ctkDependencyGraph::cycleOrigin() { return this->Internal->CycleOrigin; } //---------------------------------------------------------------------------- int ctkDependencyGraph::cycleEnd() { return this->Internal->CycleEnd; } //---------------------------------------------------------------------------- void ctkDependencyGraph::insertEdge(int from, int to) { Q_ASSERT(from > 0 && from <= this->Internal->NVertices); Q_ASSERT(to > 0 && to <= this->Internal->NVertices); // resize if needed int capacity = this->Internal->Edges[from]->capacity(); if (this->Internal->Degree[from] > capacity) { this->Internal->Edges[from]->resize(capacity + capacity * 0.3); } this->Internal->setEdge(from, this->Internal->Degree[from], to); this->Internal->Degree[from]++; this->Internal->NEdges++; } //---------------------------------------------------------------------------- void ctkDependencyGraph::findPath(int from, int to, QList<int>& path) { if ((from == to) || (to == -1)) { path << from; } else { this->findPath(from, this->Internal->Parent[to], path); path << to; } } //---------------------------------------------------------------------------- bool ctkDependencyGraph::topologicalSort(QList<int>& sorted) { QVarLengthArray<int, MAXV> indegree; // indegree of each vertex QQueue<int> zeroin; // vertices of indegree 0 int x, y; // current and next vertex indegree.resize(this->Internal->NVertices + 1); // resize if needed if (this->Internal->NVertices > MAXV) { indegree.resize(this->Internal->NVertices); } this->Internal->computeIndegrees(indegree); for (int i=1; i <= this->Internal->NVertices; i++) { if (indegree[i] == 0) { zeroin.enqueue(i); } } int j=0; while (zeroin.empty() == false) { j = j+1; x = zeroin.dequeue(); sorted << x; for (int i=0; i < this->Internal->Degree[x]; i++) { y = this->Internal->edge(x, i); indegree[y] --; if (indegree[y] == 0) { zeroin.enqueue(y); } } } if (j != this->Internal->NVertices) { return false; } return true; }
Fix memory leak in Core/ctkDependencyGraph
BUG: Fix memory leak in Core/ctkDependencyGraph The instantiated QVarLengthArray arrays weren't deleted.
C++
apache-2.0
jcfr/CTK,151706061/CTK,AndreasFetzer/CTK,Sardge/CTK,lassoan/CTK,espakm/CTK,danielknorr/CTK,fedorov/CTK,finetjul/CTK,danielknorr/CTK,finetjul/CTK,rkhlebnikov/CTK,CJGoch/CTK,SINTEFMedtek/CTK,sankhesh/CTK,mehrtash/CTK,espakm/CTK,danielknorr/CTK,naucoin/CTK,laurennlam/CTK,CJGoch/CTK,espakm/CTK,msmolens/CTK,Heather/CTK,lassoan/CTK,espakm/CTK,vovythevov/CTK,laurennlam/CTK,pieper/CTK,vovythevov/CTK,finetjul/CTK,151706061/CTK,msmolens/CTK,CJGoch/CTK,sankhesh/CTK,ddao/CTK,AndreasFetzer/CTK,laurennlam/CTK,Heather/CTK,naucoin/CTK,sankhesh/CTK,lassoan/CTK,mehrtash/CTK,CJGoch/CTK,vovythevov/CTK,msmolens/CTK,pieper/CTK,Sardge/CTK,SINTEFMedtek/CTK,151706061/CTK,commontk/CTK,lassoan/CTK,finetjul/CTK,Sardge/CTK,jcfr/CTK,fedorov/CTK,CJGoch/CTK,sankhesh/CTK,ddao/CTK,naucoin/CTK,danielknorr/CTK,ddao/CTK,fedorov/CTK,ddao/CTK,msmolens/CTK,Heather/CTK,151706061/CTK,vovythevov/CTK,commontk/CTK,151706061/CTK,rkhlebnikov/CTK,jcfr/CTK,rkhlebnikov/CTK,SINTEFMedtek/CTK,jcfr/CTK,mehrtash/CTK,SINTEFMedtek/CTK,naucoin/CTK,jcfr/CTK,pieper/CTK,Heather/CTK,SINTEFMedtek/CTK,commontk/CTK,AndreasFetzer/CTK,mehrtash/CTK,fedorov/CTK,AndreasFetzer/CTK,commontk/CTK,pieper/CTK,rkhlebnikov/CTK,laurennlam/CTK,Sardge/CTK
d6e17dc4d0849dd174ed09569fa39270c10fbd23
Libs/XNAT/Core/ctkXnatObject.cpp
Libs/XNAT/Core/ctkXnatObject.cpp
/*============================================================================= Library: XNAT/Core Copyright (c) University College London, Centre for Medical Image Computing 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 "ctkXnatObject.h" #include "ctkXnatObjectPrivate.h" #include "ctkXnatDataModel.h" #include "ctkXnatDefaultSchemaTypes.h" #include "ctkXnatException.h" #include "ctkXnatResource.h" #include "ctkXnatResourceFolder.h" #include "ctkXnatSession.h" #include <QDateTime> #include <QDebug> #include <QStringList> #include <QVariant> const QString ctkXnatObject::ID = "ID"; const QString ctkXnatObject::NAME = "name"; const QString ctkXnatObject::LABEL = "label"; const QString ctkXnatObject::URI = "URI"; const QString ctkXnatObject::XSI_SCHEMA_TYPE = "xsiType"; //---------------------------------------------------------------------------- ctkXnatObject::ctkXnatObject(const ctkXnatObject&) { throw ctkRuntimeException("Copy constructor not implemented"); } //---------------------------------------------------------------------------- ctkXnatObject::ctkXnatObject(ctkXnatObject* parent, const QString& schemaType) : d_ptr(new ctkXnatObjectPrivate()) { this->setParent(parent); this->setSchemaType(schemaType); } //---------------------------------------------------------------------------- ctkXnatObject::ctkXnatObject(ctkXnatObjectPrivate& dd, ctkXnatObject* parent, const QString& schemaType) : d_ptr(&dd) { this->setParent(parent); this->setSchemaType(schemaType); } //---------------------------------------------------------------------------- ctkXnatObject::~ctkXnatObject() { Q_D(ctkXnatObject); foreach (ctkXnatObject* child, d->children) { delete child; } } //---------------------------------------------------------------------------- QString ctkXnatObject::id() const { return this->property(ID); } //---------------------------------------------------------------------------- void ctkXnatObject::setId(const QString& id) { this->setProperty(ID, id); } //---------------------------------------------------------------------------- QString ctkXnatObject::name() const { return this->property(NAME); } //---------------------------------------------------------------------------- void ctkXnatObject::setName(const QString& name) { this->setProperty(NAME, name); } //---------------------------------------------------------------------------- QString ctkXnatObject::description() const { Q_D(const ctkXnatObject); return d->description; } //---------------------------------------------------------------------------- void ctkXnatObject::setDescription(const QString& description) { Q_D(ctkXnatObject); d->description = description; } //---------------------------------------------------------------------------- QString ctkXnatObject::childDataType() const { return "Resources"; } QDateTime ctkXnatObject::lastModifiedTimeOnServer() { Q_D(ctkXnatObject); QUuid queryId = this->session()->httpHead(this->resourceUri()); QMap<QByteArray, QByteArray> header = this->session()->httpHeadSync(queryId); QVariant lastModifiedHeader = header.value("Last-Modified"); QDateTime lastModifiedTime; if (lastModifiedHeader.isValid()) { QStringList dateformates; // In case http date formate RFC 822 ( "Sun, 06 Nov 1994 08:49:37 GMT" ) dateformates<<"ddd, dd MMM yyyy HH:mm:ss"; // In case http date formate ANSI ( "Sun Nov 6 08:49:37 1994" ) dateformates<<"ddd MMM d HH:mm:ss yyyy"; // In case http date formate RFC 850 ( "Sunday, 06-Nov-94 08:49:37 GMT" ) dateformates<<"dddd, dd-MMM-yy HH:mm:ss"; QString dateText = lastModifiedHeader.toString(); // Remove "GMT" addition at the end of the http timestamp if (dateText.indexOf("GMT") != -1) { dateText = dateText.left(dateText.length()-4); } foreach (QString format, dateformates) { lastModifiedTime = QDateTime::fromString(dateText, format); if (lastModifiedTime.isValid()) break; } } return lastModifiedTime; } void ctkXnatObject::setLastModifiedTime(const QDateTime &lastModifiedTime) { Q_D(ctkXnatObject); if (d->lastModifiedTime < lastModifiedTime) { d->lastModifiedTime = lastModifiedTime; } } //---------------------------------------------------------------------------- QString ctkXnatObject::property(const QString& name) const { Q_D(const ctkXnatObject); ctkXnatObjectPrivate::PropertyMapConstInterator iter = d->properties.find(name); if (iter != d->properties.end()) { return iter.value(); } return QString::null; } //---------------------------------------------------------------------------- void ctkXnatObject::setProperty(const QString& name, const QVariant& value) { Q_D(ctkXnatObject); if (d->properties[name] != value) { d->properties.insert(name, value.toString()); } } //---------------------------------------------------------------------------- const QMap<QString, QString>& ctkXnatObject::properties() const { Q_D(const ctkXnatObject); return d->properties; } //---------------------------------------------------------------------------- ctkXnatObject* ctkXnatObject::parent() const { Q_D(const ctkXnatObject); return d->parent; } //---------------------------------------------------------------------------- void ctkXnatObject::setParent(ctkXnatObject* parent) { Q_D(ctkXnatObject); if (d->parent != parent) { if (d->parent) { d->parent->remove(this); } if (parent) { parent->add(this); } } } //---------------------------------------------------------------------------- QList<ctkXnatObject*> ctkXnatObject::children() const { Q_D(const ctkXnatObject); return d->children; } //---------------------------------------------------------------------------- void ctkXnatObject::add(ctkXnatObject* child) { Q_D(ctkXnatObject); if (child->parent() != this) { child->d_func()->parent = this; } bool childExists (false); QList<ctkXnatObject*>::iterator iter; for (iter = d->children.begin(); iter != d->children.end(); ++iter) { if (((*iter)->id().length() != 0 && (*iter)->id() == child->id()) || ((*iter)->id().length() == 0 && (*iter)->name() == child->name())) { *iter = child; childExists = true; } } if (!childExists) { d->children.push_back(child); } } //---------------------------------------------------------------------------- void ctkXnatObject::remove(ctkXnatObject* child) { Q_D(ctkXnatObject); if (!d->children.removeOne(child)) { qWarning() << "ctkXnatObject::remove(): Child does not exist"; } } //---------------------------------------------------------------------------- void ctkXnatObject::reset() { Q_D(ctkXnatObject); // d->properties.clear(); d->children.clear(); d->fetched = false; } //---------------------------------------------------------------------------- bool ctkXnatObject::isFetched() const { Q_D(const ctkXnatObject); return d->fetched; } //---------------------------------------------------------------------------- QString ctkXnatObject::schemaType() const { return this->property(XSI_SCHEMA_TYPE); } //---------------------------------------------------------------------------- void ctkXnatObject::setSchemaType(const QString& schemaType) { this->setProperty(XSI_SCHEMA_TYPE, schemaType); } //---------------------------------------------------------------------------- void ctkXnatObject::fetch(bool forceFetch) { Q_D(ctkXnatObject); if (!d->fetched || forceFetch) { this->fetchImpl(); d->fetched = true; } } //---------------------------------------------------------------------------- ctkXnatSession* ctkXnatObject::session() const { const ctkXnatObject* xnatObject = this; while (ctkXnatObject* parent = xnatObject->parent()) { xnatObject = parent; } const ctkXnatDataModel* dataModel = dynamic_cast<const ctkXnatDataModel*>(xnatObject); return dataModel ? dataModel->session() : NULL; } //---------------------------------------------------------------------------- void ctkXnatObject::download(const QString& filename) { this->downloadImpl(filename); } //---------------------------------------------------------------------------- void ctkXnatObject::save(bool overwrite) { Q_D(ctkXnatObject); this->saveImpl(overwrite); } //---------------------------------------------------------------------------- ctkXnatResource* ctkXnatObject::addResourceFolder(QString foldername, QString format, QString content, QString tags) { if (foldername.size() == 0) { throw ctkXnatException("Error creating resource! Foldername must not be empty!"); } ctkXnatResourceFolder* resFolder = 0; QList<ctkXnatObject*> children = this->children(); for (int i = 0; i < children.size(); ++i) { resFolder = dynamic_cast<ctkXnatResourceFolder*>(children.at(i)); if (resFolder) { break; } } if (!resFolder) { resFolder = new ctkXnatResourceFolder(); this->add(resFolder); } ctkXnatResource* resource = new ctkXnatResource(); resource->setName(foldername); if (format.size() != 0) resource->setFormat(format); if (content.size() != 0) resource->setContent(content); if (tags.size() != 0) resource->setTags(tags); resFolder->add(resource); if (!resource->exists()) resource->save(); else qDebug()<<"Not adding resource folder. Folder already exists!"; return resource; } //---------------------------------------------------------------------------- bool ctkXnatObject::exists() const { return this->session()->exists(this); } //---------------------------------------------------------------------------- void ctkXnatObject::saveImpl(bool /*overwrite*/) { Q_D(ctkXnatObject); ctkXnatSession::UrlParameters urlParams; urlParams["xsiType"] = this->schemaType(); // Just do this if there is already a valid last-modification-time, // otherwise the object is not yet on the server! QDateTime remoteModTime; if (d->lastModifiedTime.isValid()) { // TODO Overwrite this for e.g. project and subject which already support modification time! remoteModTime = this->lastModifiedTimeOnServer(); // If the object has been modified on the server, perform an update if (d->lastModifiedTime < remoteModTime) { qWarning()<<"Uploaded object maybe overwritten on server!"; // TODO update from server, since modification time is not really supported // by xnat right now this is not of high priority // something like this->updateImpl + setLastModifiedTime() } } const QMap<QString, QString>& properties = this->properties(); QMapIterator<QString, QString> itProperties(properties); while (itProperties.hasNext()) { itProperties.next(); if (itProperties.key() == "ID" || itProperties.key() == "xsiType") continue; urlParams[itProperties.key()] = itProperties.value(); } // Execute the update QUuid queryID = this->session()->httpPut(this->resourceUri(), urlParams); const QList<QVariantMap> results = this->session()->httpSync(queryID); // If this xnat object did not exist before on the server set the ID returned by Xnat if (results.size() == 1 && results[0].size() == 2) { QVariant id = results[0][ID]; if (!id.isNull()) { this->setId(id.toString()); } } // Finally update the modification time on the server remoteModTime = this->lastModifiedTimeOnServer(); d->lastModifiedTime = remoteModTime; } //---------------------------------------------------------------------------- void ctkXnatObject::fetchResources(const QString& path) { ctkXnatResourceFolder* resFolder = new ctkXnatResourceFolder(); this->add(resFolder); } //---------------------------------------------------------------------------- void ctkXnatObject::erase() { this->session()->remove(this); this->parent()->remove(this); }
/*============================================================================= Library: XNAT/Core Copyright (c) University College London, Centre for Medical Image Computing 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 "ctkXnatObject.h" #include "ctkXnatObjectPrivate.h" #include "ctkXnatDataModel.h" #include "ctkXnatDefaultSchemaTypes.h" #include "ctkXnatException.h" #include "ctkXnatResource.h" #include "ctkXnatResourceFolder.h" #include "ctkXnatSession.h" #include <QDateTime> #include <QDebug> #include <QStringList> #include <QVariant> const QString ctkXnatObject::ID = "ID"; const QString ctkXnatObject::NAME = "name"; const QString ctkXnatObject::LABEL = "label"; const QString ctkXnatObject::URI = "URI"; const QString ctkXnatObject::XSI_SCHEMA_TYPE = "xsiType"; //---------------------------------------------------------------------------- ctkXnatObject::ctkXnatObject(const ctkXnatObject&) { throw ctkRuntimeException("Copy constructor not implemented"); } //---------------------------------------------------------------------------- ctkXnatObject::ctkXnatObject(ctkXnatObject* parent, const QString& schemaType) : d_ptr(new ctkXnatObjectPrivate()) { this->setParent(parent); this->setSchemaType(schemaType); } //---------------------------------------------------------------------------- ctkXnatObject::ctkXnatObject(ctkXnatObjectPrivate& dd, ctkXnatObject* parent, const QString& schemaType) : d_ptr(&dd) { this->setParent(parent); this->setSchemaType(schemaType); } //---------------------------------------------------------------------------- ctkXnatObject::~ctkXnatObject() { Q_D(ctkXnatObject); foreach (ctkXnatObject* child, d->children) { delete child; } } //---------------------------------------------------------------------------- QString ctkXnatObject::id() const { return this->property(ID); } //---------------------------------------------------------------------------- void ctkXnatObject::setId(const QString& id) { this->setProperty(ID, id); } //---------------------------------------------------------------------------- QString ctkXnatObject::name() const { return this->property(NAME); } //---------------------------------------------------------------------------- void ctkXnatObject::setName(const QString& name) { this->setProperty(NAME, name); } //---------------------------------------------------------------------------- QString ctkXnatObject::description() const { Q_D(const ctkXnatObject); return d->description; } //---------------------------------------------------------------------------- void ctkXnatObject::setDescription(const QString& description) { Q_D(ctkXnatObject); d->description = description; } //---------------------------------------------------------------------------- QString ctkXnatObject::childDataType() const { return "Resources"; } QDateTime ctkXnatObject::lastModifiedTimeOnServer() { Q_D(ctkXnatObject); QUuid queryId = this->session()->httpHead(this->resourceUri()); QMap<QByteArray, QByteArray> header = this->session()->httpHeadSync(queryId); QVariant lastModifiedHeader = header.value("Last-Modified"); QDateTime lastModifiedTime; if (lastModifiedHeader.isValid()) { QStringList dateformates; // In case http date formate RFC 822 ( "Sun, 06 Nov 1994 08:49:37 GMT" ) dateformates<<"ddd, dd MMM yyyy HH:mm:ss"; // In case http date formate ANSI ( "Sun Nov 6 08:49:37 1994" ) dateformates<<"ddd MMM d HH:mm:ss yyyy"; // In case http date formate RFC 850 ( "Sunday, 06-Nov-94 08:49:37 GMT" ) dateformates<<"dddd, dd-MMM-yy HH:mm:ss"; QString dateText = lastModifiedHeader.toString(); // Remove "GMT" addition at the end of the http timestamp if (dateText.indexOf("GMT") != -1) { dateText = dateText.left(dateText.length()-4); } foreach (QString format, dateformates) { lastModifiedTime = QDateTime::fromString(dateText, format); if (lastModifiedTime.isValid()) break; } } return lastModifiedTime; } void ctkXnatObject::setLastModifiedTime(const QDateTime &lastModifiedTime) { Q_D(ctkXnatObject); if (d->lastModifiedTime < lastModifiedTime) { d->lastModifiedTime = lastModifiedTime; } } //---------------------------------------------------------------------------- QString ctkXnatObject::property(const QString& name) const { Q_D(const ctkXnatObject); ctkXnatObjectPrivate::PropertyMapConstInterator iter = d->properties.find(name); if (iter != d->properties.end()) { return iter.value(); } return QString::null; } //---------------------------------------------------------------------------- void ctkXnatObject::setProperty(const QString& name, const QVariant& value) { Q_D(ctkXnatObject); if (d->properties[name] != value) { d->properties.insert(name, value.toString()); } } //---------------------------------------------------------------------------- const QMap<QString, QString>& ctkXnatObject::properties() const { Q_D(const ctkXnatObject); return d->properties; } //---------------------------------------------------------------------------- ctkXnatObject* ctkXnatObject::parent() const { Q_D(const ctkXnatObject); return d->parent; } //---------------------------------------------------------------------------- void ctkXnatObject::setParent(ctkXnatObject* parent) { Q_D(ctkXnatObject); if (d->parent != parent) { if (d->parent) { d->parent->remove(this); } if (parent) { parent->add(this); } } } //---------------------------------------------------------------------------- QList<ctkXnatObject*> ctkXnatObject::children() const { Q_D(const ctkXnatObject); return d->children; } //---------------------------------------------------------------------------- void ctkXnatObject::add(ctkXnatObject* child) { Q_D(ctkXnatObject); if (child->parent() != this) { child->d_func()->parent = this; } bool childExists (false); QList<ctkXnatObject*>::iterator iter; for (iter = d->children.begin(); iter != d->children.end(); ++iter) { if (((*iter)->id().length() != 0 && (*iter)->id() == child->id()) || ((*iter)->id().length() == 0 && (*iter)->name() == child->name())) { *iter = child; childExists = true; } } if (!childExists) { d->children.push_back(child); } } //---------------------------------------------------------------------------- void ctkXnatObject::remove(ctkXnatObject* child) { Q_D(ctkXnatObject); if (!d->children.removeOne(child)) { qWarning() << "ctkXnatObject::remove(): Child does not exist"; } } //---------------------------------------------------------------------------- void ctkXnatObject::reset() { Q_D(ctkXnatObject); // d->properties.clear(); d->children.clear(); d->fetched = false; } //---------------------------------------------------------------------------- bool ctkXnatObject::isFetched() const { Q_D(const ctkXnatObject); return d->fetched; } //---------------------------------------------------------------------------- QString ctkXnatObject::schemaType() const { return this->property(XSI_SCHEMA_TYPE); } //---------------------------------------------------------------------------- void ctkXnatObject::setSchemaType(const QString& schemaType) { this->setProperty(XSI_SCHEMA_TYPE, schemaType); } //---------------------------------------------------------------------------- void ctkXnatObject::fetch(bool forceFetch) { Q_D(ctkXnatObject); if (!d->fetched || forceFetch) { this->fetchImpl(); d->fetched = true; } } //---------------------------------------------------------------------------- ctkXnatSession* ctkXnatObject::session() const { const ctkXnatObject* xnatObject = this; while (ctkXnatObject* parent = xnatObject->parent()) { xnatObject = parent; } const ctkXnatDataModel* dataModel = dynamic_cast<const ctkXnatDataModel*>(xnatObject); return dataModel ? dataModel->session() : NULL; } //---------------------------------------------------------------------------- void ctkXnatObject::download(const QString& filename) { this->downloadImpl(filename); } //---------------------------------------------------------------------------- void ctkXnatObject::save(bool overwrite) { Q_D(ctkXnatObject); this->saveImpl(overwrite); } //---------------------------------------------------------------------------- ctkXnatResource* ctkXnatObject::addResourceFolder(QString foldername, QString format, QString content, QString tags) { if (foldername.size() == 0) { throw ctkXnatException("Error creating resource! Foldername must not be empty!"); } ctkXnatResourceFolder* resFolder = 0; QList<ctkXnatObject*> children = this->children(); for (int i = 0; i < children.size(); ++i) { resFolder = dynamic_cast<ctkXnatResourceFolder*>(children.at(i)); if (resFolder) { break; } } if (!resFolder) { resFolder = new ctkXnatResourceFolder(); this->add(resFolder); } ctkXnatResource* resource = new ctkXnatResource(); resource->setName(foldername); if (format.size() != 0) resource->setFormat(format); if (content.size() != 0) resource->setContent(content); if (tags.size() != 0) resource->setTags(tags); resFolder->add(resource); if (!resource->exists()) resource->save(); else qDebug()<<"Not adding resource folder. Folder already exists!"; return resource; } //---------------------------------------------------------------------------- bool ctkXnatObject::exists() const { return this->session()->exists(this); } //---------------------------------------------------------------------------- void ctkXnatObject::saveImpl(bool /*overwrite*/) { Q_D(ctkXnatObject); ctkXnatSession::UrlParameters urlParams; urlParams["xsiType"] = this->schemaType(); // Just do this if there is already a valid last-modification-time, // otherwise the object is not yet on the server! QDateTime remoteModTime; if (d->lastModifiedTime.isValid()) { // TODO Overwrite this for e.g. project and subject which already support modification time! remoteModTime = this->lastModifiedTimeOnServer(); // If the object has been modified on the server, perform an update if (d->lastModifiedTime < remoteModTime) { qWarning()<<"Uploaded object maybe overwritten on server!"; // TODO update from server, since modification time is not really supported // by xnat right now this is not of high priority // something like this->updateImpl + setLastModifiedTime() } } const QMap<QString, QString>& properties = this->properties(); QMapIterator<QString, QString> itProperties(properties); while (itProperties.hasNext()) { itProperties.next(); if (itProperties.key() == "ID" || itProperties.key() == "xsiType") continue; urlParams[itProperties.key()] = itProperties.value(); } // Execute the update QUuid queryID = this->session()->httpPut(this->resourceUri(), urlParams); const QList<QVariantMap> results = this->session()->httpSync(queryID); // If this xnat object did not exist before on the server set the ID returned by Xnat if (results.size() == 1 && results[0].size() == 2) { QVariant id = results[0][ID]; if (!id.isNull()) { this->setId(id.toString()); } } // Finally update the modification time on the server remoteModTime = this->lastModifiedTimeOnServer(); d->lastModifiedTime = remoteModTime; } //---------------------------------------------------------------------------- void ctkXnatObject::fetchResources(const QString& path) { Q_UNUSED(path); ctkXnatResourceFolder* resFolder = new ctkXnatResourceFolder(); this->add(resFolder); } //---------------------------------------------------------------------------- void ctkXnatObject::erase() { this->session()->remove(this); this->parent()->remove(this); }
Fix unused warning in ctkXnatObject::fetchResources
XNAT/Core: Fix unused warning in ctkXnatObject::fetchResources This commit fixes the following warning: /path/to/CTK/Libs/XNAT/Core/ctkXnatObject.cpp: At global scope: /path/to/CTK/Libs/XNAT/Core/ctkXnatObject.cpp:432:51: warning: unused parameter ‘path’ [-Wunused-parameter] void ctkXnatObject::fetchResources(const QString& path) ^
C++
apache-2.0
jcfr/CTK,SINTEFMedtek/CTK,commontk/CTK,SINTEFMedtek/CTK,CJGoch/CTK,commontk/CTK,CJGoch/CTK,CJGoch/CTK,SINTEFMedtek/CTK,jcfr/CTK,jcfr/CTK,SINTEFMedtek/CTK,commontk/CTK,CJGoch/CTK,CJGoch/CTK,jcfr/CTK,jcfr/CTK,commontk/CTK,SINTEFMedtek/CTK
c4e52a03ad4d11a4fb55ab4df57aab31c97525cd
src/PeerConnectionManager.cpp
src/PeerConnectionManager.cpp
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** PeerConnectionManager.cpp ** ** -------------------------------------------------------------------------*/ #include <iostream> #include <utility> #include "webrtc/modules/video_capture/video_capture_factory.h" #include "webrtc/media/engine/webrtcvideocapturerfactory.h" #include "webrtc/media/base/fakevideocapturer.h" #include "PeerConnectionManager.h" #ifdef HAVE_LIVE555 #include "rtspvideocapturer.h" #endif #ifdef HAVE_YUVFRAMEGENERATOR #include "yuvvideocapturer.h" #endif const char kAudioLabel[] = "audio_label"; const char kVideoLabel[] = "video_label"; const char kStreamLabel[] = "stream_label"; // Names used for a IceCandidate JSON object. const char kCandidateSdpMidName[] = "sdpMid"; const char kCandidateSdpMlineIndexName[] = "sdpMLineIndex"; const char kCandidateSdpName[] = "candidate"; // Names used for a SessionDescription JSON object. const char kSessionDescriptionTypeName[] = "type"; const char kSessionDescriptionSdpName[] = "sdp"; PeerConnectionManager::PeerConnectionManager(const std::string & stunurl) : peer_connection_factory_(NULL), stunurl_(stunurl) { } PeerConnectionManager::~PeerConnectionManager() { peer_connection_factory_ = NULL; } const Json::Value PeerConnectionManager::getDeviceList() { Json::Value value; std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> info(webrtc::VideoCaptureFactory::CreateDeviceInfo(0)); if (info) { int num_devices = info->NumberOfDevices(); for (int i = 0; i < num_devices; ++i) { const uint32_t kSize = 256; char name[kSize] = {0}; char id[kSize] = {0}; if (info->GetDeviceName(i, name, kSize, id, kSize) != -1) { value.append(name); } } } return value; } bool PeerConnectionManager::InitializePeerConnection() { peer_connection_factory_ = webrtc::CreatePeerConnectionFactory(); return (peer_connection_factory_.get() != NULL); } std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionManager::PeerConnectionObserver* > PeerConnectionManager::CreatePeerConnection(const std::string & url) { webrtc::PeerConnectionInterface::RTCConfiguration config; webrtc::PeerConnectionInterface::IceServer server; server.uri = "stun:" + stunurl_; server.username = ""; server.password = ""; config.servers.push_back(server); PeerConnectionObserver* obs = PeerConnectionObserver::Create(); rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection = peer_connection_factory_->CreatePeerConnection(config, NULL, NULL, NULL, obs); if (!peer_connection) { LOG(LERROR) << __FUNCTION__ << "CreatePeerConnection failed"; } else { obs->setPeerConnection(peer_connection); if (!this->AddStreams(peer_connection, url)) { peer_connection.release(); } } return std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionObserver* >(peer_connection, obs); } void PeerConnectionManager::DeletePeerConnection() { LOG(INFO) << __FUNCTION__; } void PeerConnectionManager::setAnswer(const std::string &peerid, const std::string& message) { LOG(INFO) << message; Json::Reader reader; Json::Value jmessage; if (!reader.parse(message, jmessage)) { LOG(WARNING) << "Received unknown message. " << message; return; } std::string type; std::string sdp; if ( !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionTypeName, &type) || !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionSdpName, &sdp)) { LOG(WARNING) << "Can't parse received message."; return; } webrtc::SessionDescriptionInterface* session_description(webrtc::CreateSessionDescription(type, sdp, NULL)); if (!session_description) { LOG(WARNING) << "Can't parse received session description message."; return; } LOG(LERROR) << "From peerid:" << peerid << " received session description :" << session_description->type(); std::map<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >::iterator it = peer_connection_map_.find(peerid); if (it != peer_connection_map_.end()) { rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc = it->second; pc->SetRemoteDescription(SetSessionDescriptionObserver::Create(pc, session_description->type()), session_description); } } void PeerConnectionManager::addIceCandidate(const std::string &peerid, const std::string& message) { LOG(INFO) << message; Json::Reader reader; Json::Value jmessage; if (!reader.parse(message, jmessage)) { LOG(WARNING) << "Received unknown message. " << message; return; } std::string sdp_mid; int sdp_mlineindex = 0; std::string sdp; if ( !rtc::GetStringFromJsonObject(jmessage, kCandidateSdpMidName, &sdp_mid) || !rtc::GetIntFromJsonObject(jmessage, kCandidateSdpMlineIndexName, &sdp_mlineindex) || !rtc::GetStringFromJsonObject(jmessage, kCandidateSdpName, &sdp)) { LOG(WARNING) << "Can't parse received message."; return; } std::unique_ptr<webrtc::IceCandidateInterface> candidate(webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp, NULL)); if (!candidate.get()) { LOG(WARNING) << "Can't parse received candidate message."; return; } std::map<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >::iterator it = peer_connection_map_.find(peerid); if (it != peer_connection_map_.end()) { rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc = it->second; if (!pc->AddIceCandidate(candidate.get())) { LOG(WARNING) << "Failed to apply the received candidate"; return; } } } cricket::VideoCapturer* PeerConnectionManager::OpenVideoCaptureDevice(const std::string & url) { LOG(LS_ERROR) << "url:" << url; cricket::VideoCapturer* capturer = NULL; if (url.find("rtsp://") == 0) { #ifdef HAVE_LIVE555 capturer = new RTSPVideoCapturer(url); #endif } else if (url == "YuvFramesGenerator") { #ifdef HAVE_YUVFRAMEGENERATOR capturer = new YuvVideoCapturer(); #endif } else if (url == "FakeVideoCapturer") { capturer = new cricket::FakeVideoCapturer(); } else { std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> info(webrtc::VideoCaptureFactory::CreateDeviceInfo(0)); if (info) { int num_devices = info->NumberOfDevices(); for (int i = 0; i < num_devices; ++i) { const uint32_t kSize = 256; char name[kSize] = {0}; char id[kSize] = {0}; if (info->GetDeviceName(i, name, kSize, id, kSize) != -1) { if (url == name) { cricket::WebRtcVideoDeviceCapturerFactory factory; capturer = factory.Create(cricket::Device(name, 0)); } } } } } return capturer; } bool PeerConnectionManager::AddStreams(webrtc::PeerConnectionInterface* peer_connection, const std::string & url) { bool ret = false; cricket::VideoCapturer* capturer = OpenVideoCaptureDevice(url); if (!capturer) { LOG(LS_ERROR) << "Cannot create capturer " << url; } else { rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> source = peer_connection_factory_->CreateVideoSource(capturer, NULL); rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(peer_connection_factory_->CreateVideoTrack(kVideoLabel, source)); rtc::scoped_refptr<webrtc::MediaStreamInterface> stream = peer_connection_factory_->CreateLocalMediaStream(kStreamLabel); if (!stream.get()) { LOG(LS_ERROR) << "Cannot create stream"; } else { if (!stream->AddTrack(video_track)) { LOG(LS_ERROR) << "Adding Track to PeerConnection failed"; } else if (!peer_connection->AddStream(stream)) { LOG(LS_ERROR) << "Adding stream to PeerConnection failed"; } else { ret = true; } } } return ret; } const std::string PeerConnectionManager::getOffer(std::string &peerid, const std::string & url) { std::string offer; LOG(INFO) << __FUNCTION__; std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionObserver* > peer_connection = this->CreatePeerConnection(url); if (!peer_connection.first) { LOG(LERROR) << "Failed to initialize PeerConnection"; } else { std::ostringstream os; os << rand(); peerid = os.str(); // register peerid peer_connection_map_.insert(std::pair<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >(peerid, peer_connection.first)); peer_connectionobs_map_.insert(std::pair<std::string, PeerConnectionObserver* >(peerid, peer_connection.second)); peer_connection.first->CreateOffer(CreateSessionDescriptionObserver::Create(peer_connection.first), NULL); // waiting for offer int count=10; while ( (peer_connection.first->local_description() == NULL) && (--count > 0) ) { rtc::Thread::Current()->ProcessMessages(10); } const webrtc::SessionDescriptionInterface* desc = peer_connection.first->local_description(); if (desc) { std::string sdp; desc->ToString(&sdp); Json::Value jmessage; jmessage[kSessionDescriptionTypeName] = desc->type(); jmessage[kSessionDescriptionSdpName] = sdp; Json::StyledWriter writer; offer = writer.write(jmessage); } } return offer; } const Json::Value PeerConnectionManager::getIceCandidateList(const std::string &peerid) { Json::Value value; std::map<std::string, PeerConnectionObserver* >::iterator it = peer_connectionobs_map_.find(peerid); if (it != peer_connectionobs_map_.end()) { PeerConnectionObserver* obs = it->second; if (obs) { value = obs->getIceCandidateList(); } else { LOG(LS_ERROR) << "No observer for peer:" << peerid; } } return value; } void PeerConnectionManager::PeerConnectionObserver::OnIceCandidate(const webrtc::IceCandidateInterface* candidate) { LOG(INFO) << __FUNCTION__ << " " << candidate->sdp_mline_index(); std::string sdp; if (!candidate->ToString(&sdp)) { LOG(LS_ERROR) << "Failed to serialize candidate"; } else { LOG(INFO) << sdp; Json::Value jmessage; jmessage[kCandidateSdpMidName] = candidate->sdp_mid(); jmessage[kCandidateSdpMlineIndexName] = candidate->sdp_mline_index(); jmessage[kCandidateSdpName] = sdp; iceCandidateList_.append(jmessage); } }
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** PeerConnectionManager.cpp ** ** -------------------------------------------------------------------------*/ #include <iostream> #include <utility> #include "webrtc/modules/video_capture/video_capture_factory.h" #include "webrtc/media/engine/webrtcvideocapturerfactory.h" #include "PeerConnectionManager.h" #ifdef HAVE_LIVE555 #include "rtspvideocapturer.h" #endif #ifdef HAVE_YUVFRAMEGENERATOR #include "yuvvideocapturer.h" #endif const char kAudioLabel[] = "audio_label"; const char kVideoLabel[] = "video_label"; const char kStreamLabel[] = "stream_label"; // Names used for a IceCandidate JSON object. const char kCandidateSdpMidName[] = "sdpMid"; const char kCandidateSdpMlineIndexName[] = "sdpMLineIndex"; const char kCandidateSdpName[] = "candidate"; // Names used for a SessionDescription JSON object. const char kSessionDescriptionTypeName[] = "type"; const char kSessionDescriptionSdpName[] = "sdp"; PeerConnectionManager::PeerConnectionManager(const std::string & stunurl) : peer_connection_factory_(NULL), stunurl_(stunurl) { } PeerConnectionManager::~PeerConnectionManager() { peer_connection_factory_ = NULL; } const Json::Value PeerConnectionManager::getDeviceList() { Json::Value value; std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> info(webrtc::VideoCaptureFactory::CreateDeviceInfo(0)); if (info) { int num_devices = info->NumberOfDevices(); for (int i = 0; i < num_devices; ++i) { const uint32_t kSize = 256; char name[kSize] = {0}; char id[kSize] = {0}; if (info->GetDeviceName(i, name, kSize, id, kSize) != -1) { value.append(name); } } } return value; } bool PeerConnectionManager::InitializePeerConnection() { peer_connection_factory_ = webrtc::CreatePeerConnectionFactory(); return (peer_connection_factory_.get() != NULL); } std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionManager::PeerConnectionObserver* > PeerConnectionManager::CreatePeerConnection(const std::string & url) { webrtc::PeerConnectionInterface::RTCConfiguration config; webrtc::PeerConnectionInterface::IceServer server; server.uri = "stun:" + stunurl_; server.username = ""; server.password = ""; config.servers.push_back(server); PeerConnectionObserver* obs = PeerConnectionObserver::Create(); rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection = peer_connection_factory_->CreatePeerConnection(config, NULL, NULL, NULL, obs); if (!peer_connection) { LOG(LERROR) << __FUNCTION__ << "CreatePeerConnection failed"; } else { obs->setPeerConnection(peer_connection); if (!this->AddStreams(peer_connection, url)) { peer_connection.release(); } } return std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionObserver* >(peer_connection, obs); } void PeerConnectionManager::DeletePeerConnection() { LOG(INFO) << __FUNCTION__; } void PeerConnectionManager::setAnswer(const std::string &peerid, const std::string& message) { LOG(INFO) << message; Json::Reader reader; Json::Value jmessage; if (!reader.parse(message, jmessage)) { LOG(WARNING) << "Received unknown message. " << message; return; } std::string type; std::string sdp; if ( !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionTypeName, &type) || !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionSdpName, &sdp)) { LOG(WARNING) << "Can't parse received message."; return; } webrtc::SessionDescriptionInterface* session_description(webrtc::CreateSessionDescription(type, sdp, NULL)); if (!session_description) { LOG(WARNING) << "Can't parse received session description message."; return; } LOG(LERROR) << "From peerid:" << peerid << " received session description :" << session_description->type(); std::map<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >::iterator it = peer_connection_map_.find(peerid); if (it != peer_connection_map_.end()) { rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc = it->second; pc->SetRemoteDescription(SetSessionDescriptionObserver::Create(pc, session_description->type()), session_description); } } void PeerConnectionManager::addIceCandidate(const std::string &peerid, const std::string& message) { LOG(INFO) << message; Json::Reader reader; Json::Value jmessage; if (!reader.parse(message, jmessage)) { LOG(WARNING) << "Received unknown message. " << message; return; } std::string sdp_mid; int sdp_mlineindex = 0; std::string sdp; if ( !rtc::GetStringFromJsonObject(jmessage, kCandidateSdpMidName, &sdp_mid) || !rtc::GetIntFromJsonObject(jmessage, kCandidateSdpMlineIndexName, &sdp_mlineindex) || !rtc::GetStringFromJsonObject(jmessage, kCandidateSdpName, &sdp)) { LOG(WARNING) << "Can't parse received message."; return; } std::unique_ptr<webrtc::IceCandidateInterface> candidate(webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp, NULL)); if (!candidate.get()) { LOG(WARNING) << "Can't parse received candidate message."; return; } std::map<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >::iterator it = peer_connection_map_.find(peerid); if (it != peer_connection_map_.end()) { rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc = it->second; if (!pc->AddIceCandidate(candidate.get())) { LOG(WARNING) << "Failed to apply the received candidate"; return; } } } cricket::VideoCapturer* PeerConnectionManager::OpenVideoCaptureDevice(const std::string & url) { LOG(LS_ERROR) << "url:" << url; cricket::VideoCapturer* capturer = NULL; if (url.find("rtsp://") == 0) { #ifdef HAVE_LIVE555 capturer = new RTSPVideoCapturer(url); #endif } else if (url == "YuvFramesGenerator") { #ifdef HAVE_YUVFRAMEGENERATOR capturer = new YuvVideoCapturer(); #endif } else { std::unique_ptr<webrtc::VideoCaptureModule::DeviceInfo> info(webrtc::VideoCaptureFactory::CreateDeviceInfo(0)); if (info) { int num_devices = info->NumberOfDevices(); for (int i = 0; i < num_devices; ++i) { const uint32_t kSize = 256; char name[kSize] = {0}; char id[kSize] = {0}; if (info->GetDeviceName(i, name, kSize, id, kSize) != -1) { if (url == name) { cricket::WebRtcVideoDeviceCapturerFactory factory; capturer = factory.Create(cricket::Device(name, 0)); } } } } } return capturer; } bool PeerConnectionManager::AddStreams(webrtc::PeerConnectionInterface* peer_connection, const std::string & url) { bool ret = false; cricket::VideoCapturer* capturer = OpenVideoCaptureDevice(url); if (!capturer) { LOG(LS_ERROR) << "Cannot create capturer " << url; } else { rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> source = peer_connection_factory_->CreateVideoSource(capturer, NULL); rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(peer_connection_factory_->CreateVideoTrack(kVideoLabel, source)); rtc::scoped_refptr<webrtc::MediaStreamInterface> stream = peer_connection_factory_->CreateLocalMediaStream(kStreamLabel); if (!stream.get()) { LOG(LS_ERROR) << "Cannot create stream"; } else { if (!stream->AddTrack(video_track)) { LOG(LS_ERROR) << "Adding Track to PeerConnection failed"; } else if (!peer_connection->AddStream(stream)) { LOG(LS_ERROR) << "Adding stream to PeerConnection failed"; } else { ret = true; } } } return ret; } const std::string PeerConnectionManager::getOffer(std::string &peerid, const std::string & url) { std::string offer; LOG(INFO) << __FUNCTION__; std::pair<rtc::scoped_refptr<webrtc::PeerConnectionInterface>, PeerConnectionObserver* > peer_connection = this->CreatePeerConnection(url); if (!peer_connection.first) { LOG(LERROR) << "Failed to initialize PeerConnection"; } else { std::ostringstream os; os << rand(); peerid = os.str(); // register peerid peer_connection_map_.insert(std::pair<std::string, rtc::scoped_refptr<webrtc::PeerConnectionInterface> >(peerid, peer_connection.first)); peer_connectionobs_map_.insert(std::pair<std::string, PeerConnectionObserver* >(peerid, peer_connection.second)); peer_connection.first->CreateOffer(CreateSessionDescriptionObserver::Create(peer_connection.first), NULL); // waiting for offer int count=10; while ( (peer_connection.first->local_description() == NULL) && (--count > 0) ) { rtc::Thread::Current()->ProcessMessages(10); } const webrtc::SessionDescriptionInterface* desc = peer_connection.first->local_description(); if (desc) { std::string sdp; desc->ToString(&sdp); Json::Value jmessage; jmessage[kSessionDescriptionTypeName] = desc->type(); jmessage[kSessionDescriptionSdpName] = sdp; Json::StyledWriter writer; offer = writer.write(jmessage); } } return offer; } const Json::Value PeerConnectionManager::getIceCandidateList(const std::string &peerid) { Json::Value value; std::map<std::string, PeerConnectionObserver* >::iterator it = peer_connectionobs_map_.find(peerid); if (it != peer_connectionobs_map_.end()) { PeerConnectionObserver* obs = it->second; if (obs) { value = obs->getIceCandidateList(); } else { LOG(LS_ERROR) << "No observer for peer:" << peerid; } } return value; } void PeerConnectionManager::PeerConnectionObserver::OnIceCandidate(const webrtc::IceCandidateInterface* candidate) { LOG(INFO) << __FUNCTION__ << " " << candidate->sdp_mline_index(); std::string sdp; if (!candidate->ToString(&sdp)) { LOG(LS_ERROR) << "Failed to serialize candidate"; } else { LOG(INFO) << sdp; Json::Value jmessage; jmessage[kCandidateSdpMidName] = candidate->sdp_mid(); jmessage[kCandidateSdpMlineIndexName] = candidate->sdp_mline_index(); jmessage[kCandidateSdpName] = sdp; iceCandidateList_.append(jmessage); } }
remove reference of fakecapturer
remove reference of fakecapturer
C++
unlicense
mpromonet/webrtc-streamer,ghostzero2000/webrtc-streamer-base,ghostzero2000/webrtc-streamer-base,mpromonet/webrtc-streamer,ghostzero2000/webrtc-streamer-base
ad93418c75f7cd86f128bfb05c331c86f9994e98
src/ServerManager/Manager.cpp
src/ServerManager/Manager.cpp
/* * This file is part ServerManager of package * * (c) Ondřej Záruba <[email protected]> * * For the full copyright and license information, please view the license.md * file that was distributed with this source code. */ #include <string> #include <fstream> #include <cstdlib> #include <sstream> #include "./Manager.h" #include "./Configuration.h" #include "./Console.h" #include "./Files.h" #include "./Strings.h" using namespace ServerManager; using namespace std; Manager::Manager(){} void Manager::setConfiguration(Configuration config) { this->config = config; } string Manager::search(string hostName) { string cmd = "cat " + this->config.hosts + " | grep " + hostName; Console console(cmd); return console.exec(); } string Manager::getList() { ifstream file(this->config.hosts.c_str()); string line, result; if (file.good()) { while(getline(file, line)) { istringstream line_string(line); string key; if (line.find(" ") != std::string::npos) { if (getline(line_string, key, ' ')) { this->appendLine(&result, key, line); } } else { if (getline(line_string, key, '\t')) { this->appendLine(&result, key, line); } } } file.close(); return result; } else { file.close(); throw "Invalid path to hosts file or you don't run as administrator(sudo)"; } } string Manager::create(string hostName) { string result; Console console("nginx -s stop"); if (console.exec().empty()) { result.append("Stoping nginx"); } ofstream hostsFile(this->config.hosts.c_str(), ios_base::app | ios_base::out); if (!hostsFile.good()) { hostsFile.close(); throw "Invalid path to hosts file or you don't run as administrator(sudo)"; } if (!this->search(hostName).empty()) { hostsFile.close(); throw "Hostname already exists"; } hostsFile << endl << this->getHostConfig(hostName); result.append("\nAdded virtual host into hosts file"); hostsFile.close(); string path = this->config.nginx + "/" + hostName + ".conf"; ofstream nginxConfig(path.c_str()); if (nginxConfig.good()) { nginxConfig << this->getServerConfig(hostName); if(nginxConfig.good()) { result.append("\nAdded virtual host nginx configuration"); } Console mkdirLog("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.log); Console mkdirRoot("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.root); if (mkdirLog.exec().empty() && mkdirRoot.exec().empty()) { result.append("\nCreated base project directories: "); result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.log); result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.root); } nginxConfig.close(); } else { nginxConfig.close(); throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)"; } Console nginxStart("nginx"); if (nginxStart.exec().empty()) { result.append("\nStarting nginx"); } Console chmodCmd("chmod -R 0777 " + this->config.htdocs + "/" + hostName); if (chmodCmd.exec().empty()) { result.append("\nSet chmod"); } return result; } string Manager::remove(string hostName) { string result; Console console("nginx -s stop"); if (console.exec().empty()) { result.append("Stoping nginx"); } Console rmProject("rm -rf " + this->config.htdocs + "/" + hostName); Console rmNginxConf("rm -rf " + this->config.nginx + "/" + hostName + ".conf"); if (rmProject.exec().empty()) { result.append("\nProject directory has been removed"); } else { throw "Invalid path to host(project) directory or you don't run as administrator(sudo)"; } if (rmNginxConf.exec().empty()) { result.append("\nNginx configuration has been removed"); } else { throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)"; } ifstream ihostFile(this->config.hosts.c_str()); if (ihostFile.good()) { string line, newContent = ""; while(getline(ihostFile, line)) { if (line.compare(this->getHostConfig(hostName)) != 0 && !line.empty()) { newContent.append(line + "\n"); } } ofstream ohostFile(this->config.hosts.c_str()); ohostFile << newContent; result.append("\nVirtual host has been removed from hosts file"); ihostFile.close(); ohostFile.close(); } else { throw "Invalid path to hosts file or you don't run as administrator(sudo)"; ihostFile.close(); } Console nginxStart("nginx"); if (nginxStart.exec().empty()) { result.append("\nStarting nginx"); } return result; } void Manager::appendLine(string* result,string key, string line) { if (key.compare("127.0.0.1") == 0) { (*result).append(line + "\n"); } } string Manager::getServerConfig(string hostName) { Files files; Strings strings; string content = files.getString(this->config.serverTemplate); string config = strings.replace("%hostName%", hostName, content); config = strings.replace("%tld%", this->config.tld, config); config = strings.replace("%htdocs%", this->config.htdocs, config); config = strings.replace("%root%", this->config.root, config); config = strings.replace("%log%", this->config.log, config); return config; } string Manager::getHostConfig(string hostName) { Files files; Strings strings; string content = files.getString(this->config.systemTemplate); string host = strings.replace("%hostName%", hostName, content); host = strings.replace("%tld%", this->config.tld, host); return host; }
/* * This file is part ServerManager of package * * (c) Ondřej Záruba <[email protected]> * * For the full copyright and license information, please view the license.md * file that was distributed with this source code. */ #include <string> #include <fstream> #include <cstdlib> #include <sstream> #include "./Manager.h" #include "./Configuration.h" #include "./Console.h" #include "./Files.h" #include "./Strings.h" using namespace ServerManager; using namespace std; Manager::Manager(){} void Manager::setConfiguration(Configuration config) { this->config = config; } string Manager::search(string hostName) { string cmd = "cat " + this->config.hosts + " | grep " + hostName; Console console(cmd); return console.exec(); } string Manager::getList() { ifstream file(this->config.hosts.c_str()); string line, result; if (file.good()) { while(getline(file, line)) { istringstream line_string(line); string key; if (line.find(" ") != std::string::npos) { if (getline(line_string, key, ' ')) { this->appendLine(&result, key, line); } } else { if (getline(line_string, key, '\t')) { this->appendLine(&result, key, line); } } } file.close(); return result; } else { file.close(); throw "Invalid path to hosts file or you don't run as administrator(sudo)"; } } string Manager::create(string hostName) { string result; Console console("nginx -s stop"); if (console.exec().empty()) { result.append("Stoping nginx"); } ofstream hostsFile(this->config.hosts.c_str(), ios_base::app | ios_base::out); if (hostsFile.good()) { hostsFile << endl << this->getHostConfig(hostName); result.append("\nAdded virtual host into hosts file"); hostsFile.close(); } else { hostsFile.close(); throw "Invalid path to hosts file or you don't run as administrator(sudo)"; } string path = this->config.nginx + "/" + hostName + ".conf"; ofstream nginxConfig(path.c_str()); if (nginxConfig.good()) { nginxConfig << this->getServerConfig(hostName); if(nginxConfig.good()) { result.append("\nAdded virtual host nginx configuration"); } if(!this->config.project.empty()) { Console testGitRepository("git ls-remote " + this->config.project + " --exit-code"); if(testGitRepository.exec().empty()) { Console cloneGitRepository("git clone " + this->config.project + " " + this->config.htdocs + "/" + hostName); cloneGitRepository.exec(); result.append("\nCreated project from git repository"); } else { nginxConfig.close(); throw "Check if repository of project is valid: " + this->config.project; } } else { Console mkdirLog("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.log); Console mkdirRoot("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.root); if (mkdirLog.exec().empty() && mkdirRoot.exec().empty()) { result.append("\nCreated base project directories: "); result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.log); result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.root); } } nginxConfig.close(); } else { nginxConfig.close(); throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)"; } Console nginxStart("nginx"); if (nginxStart.exec().empty()) { result.append("\nStarting nginx"); } Console chmodCmd("chmod -R 0777 " + this->config.htdocs + "/" + hostName); if (chmodCmd.exec().empty()) { result.append("\nSet chmod"); } return result; } string Manager::remove(string hostName) { string result; Console console("nginx -s stop"); if (console.exec().empty()) { result.append("Stoping nginx"); } Console rmProject("rm -rf " + this->config.htdocs + "/" + hostName); Console rmNginxConf("rm -rf " + this->config.nginx + "/" + hostName + ".conf"); if (rmProject.exec().empty()) { result.append("\nProject directory has been removed"); } else { throw "Invalid path to host(project) directory or you don't run as administrator(sudo)"; } if (rmNginxConf.exec().empty()) { result.append("\nNginx configuration has been removed"); } else { throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)"; } ifstream ihostFile(this->config.hosts.c_str()); if (ihostFile.good()) { string line, newContent = ""; while(getline(ihostFile, line)) { if (line.compare(this->getHostConfig(hostName)) != 0 && !line.empty()) { newContent.append(line + "\n"); } } ofstream ohostFile(this->config.hosts.c_str()); ohostFile << newContent; result.append("\nVirtual host has been removed from hosts file"); ihostFile.close(); ohostFile.close(); } else { throw "Invalid path to hosts file or you don't run as administrator(sudo)"; ihostFile.close(); } Console nginxStart("nginx"); if (nginxStart.exec().empty()) { result.append("\nStarting nginx"); } return result; } void Manager::appendLine(string* result,string key, string line) { if (key.compare("127.0.0.1") == 0) { (*result).append(line + "\n"); } } string Manager::getServerConfig(string hostName) { Files files; Strings strings; string content = files.getString(this->config.serverTemplate); string config = strings.replace("%hostName%", hostName, content); config = strings.replace("%tld%", this->config.tld, config); config = strings.replace("%htdocs%", this->config.htdocs, config); config = strings.replace("%root%", this->config.root, config); config = strings.replace("%log%", this->config.log, config); return config; } string Manager::getHostConfig(string hostName) { Files files; Strings strings; string content = files.getString(this->config.systemTemplate); string host = strings.replace("%hostName%", hostName, content); host = strings.replace("%tld%", this->config.tld, host); return host; }
Revert "Manager create: do not allow duplicates, throw exception"
Revert "Manager create: do not allow duplicates, throw exception"
C++
mit
Budry/ServerManager,Budry/ServerManager
071d056cea1d89eab3705959eeeb0dd5a6a2d6cc
src/camera/dynamic_camera.cxx
src/camera/dynamic_camera.cxx
/** * @file * @author Jason Lingle * @brief Implementation of src/camera/dynamic_camera.hxx */ #include <cmath> #include <cstdlib> #include <cstring> #include <iostream> #include "camera.hxx" #include "dynamic_camera.hxx" #include "src/globals.hxx" #include "src/control/human_controller.hxx" #include "src/control/hc_conf.hxx" #include "src/graphics/matops.hxx" #include "src/graphics/asgi.hxx" using namespace std; using namespace hc_conf; #define ACCEL_SPEED 0.001f #define MOVE_SPEED 0.01f #define ZOOM_SPEED 0.002f #define STABILIZE_RATIO_SEC 0.1f #define ROT_SPEED (2*pi/1000.0f) bool debug_dynamicCameraDisableVibration=false; DynamicCamera::DynamicCamera(GameObject* ref, GameField* field) : Camera(ref), currX(ref? ref->getX(): 0), currY(ref? ref->getY() : 0), currZ(1.0f), currT(0), vibration(0), vx(0), vy(0), zoom(0.35f), rotateMode(None), lookAhead(conf["conf"]["camera"]["lookahead"]), targetRotation(0), baseDetailLevel(conf["conf"]["graphics"]["detail_level"]), hud((Ship*)ref, field) { const char* mode=conf["conf"]["camera"]["mode"]; if (0 == strcmp(mode, "none")) rotateMode=None; else if (0 == strcmp(mode, "rotation")) rotateMode=Direction; else if (0 == strcmp(mode, "velocity")) rotateMode=Velocity; } DynamicCamera::~DynamicCamera() { asgi::reset(); glClearColor(0,0,0,1); //Restore actual detail level config conf["conf"]["graphics"]["detail_level"]=(int)baseDetailLevel; } #define ref reference void DynamicCamera::doSetup() noth { if (debug_dynamicCameraDisableVibration) vibration=0; if (!ref) return; //Adjust detail level for zoom. Always round down (for better //quality) and never decrease beyond the base conf["conf"]["graphics"]["detail_level"] = min(8, (int)(currZ > 1? baseDetailLevel : (unsigned)(baseDetailLevel/currZ))); //Handle vibration float vibx=vibration*(rand()/(float)RAND_MAX) - vibration/2, viby=vibration*(rand()/(float)RAND_MAX) - vibration/2; mTrans(0.5f, vheight/2-(rotateMode!=None? lookAhead : 0), matrix_stack::view); mUScale(currZ, matrix_stack::view); mRot(-currT, matrix_stack::view); mTrans(-currX+vibx, -currY+viby, matrix_stack::view); //We form a box around the largest possible area, regardless //of actual orientation. //A constantly-changing framerate is more distracting than //a consistently low framerate (eg, on slower computers) float cx=currX - vibx/currZ - (rotateMode!=None? lookAhead : 0)*sin(currT)/currZ, cy=currY - viby/currZ + (rotateMode!=None? lookAhead : 0)*cos(currT)/currZ; float ratio=sqrt(2.0f)/2.0f/currZ; cameraX1=cx - ratio; cameraX2=cx + ratio; cameraY1=cy - ratio/* *vheight*/; cameraY2=cy + ratio/* *vheight*/; cameraCX=currX - vibx/currZ; cameraCY=currY - viby/currZ; cameraZoom=currZ; float cornerAngle=atan2(vheight/2, 0.5f); float cornerDist=sqrt(vheight*vheight/4 + 0.25f)/currZ; screenCorners[0].first = cornerDist*cos(cornerAngle + currT) + cx; screenCorners[0].second= cornerDist*sin(cornerAngle + currT) + cy; screenCorners[1].first = cornerDist*cos(pi - cornerAngle + currT) + cx; screenCorners[1].second= cornerDist*sin(pi - cornerAngle + currT) + cy; screenCorners[2].first = cornerDist*cos(pi + cornerAngle + currT) + cx; screenCorners[2].second= cornerDist*sin(pi + cornerAngle + currT) + cy; screenCorners[3].first = cornerDist*cos(-cornerAngle + currT) + cx; screenCorners[3].second= cornerDist*sin(-cornerAngle + currT) + cy; //glLineWidth(currZ); //glPointSize(currZ); mId(); } void DynamicCamera::update(float time) noth { Ship* s=NULL; hud.setRef(s=dynamic_cast<Ship*>(const_cast<GameObject*>(ref))); hud.update(time); targetRotation=getRotation(); /* Lower frame-rates can give a "choppy" feel, since the math we use * will result in the camera jumping around a bit. * Force updates to a 10ms granularity. */ for (float t=time; t>0; t -= 10) { float time = (t>10? 10 : t); currX+=vx*time; currY+=vy*time; if (currT!=targetRotation) { float diff=currT-targetRotation; if (diff<-pi) diff+=2*pi; if (diff>+pi) diff-=2*pi; if (diff<0) { if (fabs(diff)<ROT_SPEED*time) currT=targetRotation; else { currT+=ROT_SPEED*time; if (currT>2*pi) currT-=2*pi; } } else if (diff>0) { if (fabs(diff)<ROT_SPEED*time) currT=targetRotation; else { currT-=ROT_SPEED*time; if (currT<0) currT+=2*pi; } } } if (currZ<zoom) { currZ+=time*ZOOM_SPEED*currZ; if (currZ>zoom) currZ=zoom; } else if (currZ>zoom) { currZ-=time*ZOOM_SPEED*currZ; if (currZ<zoom) currZ=zoom; } vibration*=pow(STABILIZE_RATIO_SEC, time/1000.0f); if (!ref) continue; //Adjust vx and vy as necessary float tx=ref->getX(), ty=ref->getY(); float dx=tx-currX, dy=ty-currY; currX+=dx*MOVE_SPEED*time; currY+=dy*MOVE_SPEED*time; float dvx=vx-ref->getVX(), dvy=vy-ref->getVY(); vx-=dvx*ACCEL_SPEED*time; vy-=dvy*ACCEL_SPEED*time; } } void DynamicCamera::drawOverlays() noth { hud.draw(this); } void DynamicCamera::reset() noth { //currZ=zoom; currX=ref->getX(); currY=ref->getY(); vibration=0; vx=vy=0; currT=targetRotation=getRotation(); float ratio=sqrt(2.0f)/currZ/2; cameraX1=currX-ratio; cameraX2=currX+ratio; cameraY1=currY-ratio*vheight; cameraY2=currY+ratio*vheight; } void DynamicCamera::impact(float amt) noth { vibration+=amt*15; hud.damage(amt); } float DynamicCamera::getZoom() const noth { return zoom; } void DynamicCamera::setZoom(float z) noth { if (z>=0.1f && z<=2.0f) zoom=z; } float DynamicCamera::getLookAhead() const noth { return lookAhead; } void DynamicCamera::setLookAhead(float l) noth { if (l>0 && l<vheight/2) lookAhead=l; } DynamicCamera::RotateMode DynamicCamera::getRotateMode() const noth { return rotateMode; } void DynamicCamera::setRotateMode(RotateMode mode) noth { rotateMode=mode; } //When in Velocity mode, when under this speed, we factor actual rotation in //according to the closeness to this speed #define MIN_VEL_SPEED 0.00005f float DynamicCamera::getRotation() const noth { if (!ref) return 0; switch (rotateMode) { case None: return 0; case Direction: return ref->getRotation()-pi/2; case Velocity: float velang=atan2(ref->getVY(), ref->getVX()); if (velang!=velang || sqrt(ref->getVX()*ref->getVX() + ref->getVY()*ref->getVY())<MIN_VEL_SPEED) return ref->getRotation()-pi/2; else return velang-pi/2; } return 0; } namespace dyncam_action { void zoom(Ship* s, ActionDatum& dat) { DynamicCamera* that=(DynamicCamera*)dat.pair.first; float amt=dat.pair.second.amt; that->setZoom(that->getZoom()+amt); } void lookahead(Ship* s, ActionDatum& dat) { DynamicCamera* that=(DynamicCamera*)dat.pair.first; float amt=dat.pair.second.amt; that->setLookAhead(that->getLookAhead()+amt); conf["conf"]["camera"]["lookahead"]=that->getLookAhead(); } void set_mode(Ship* s, ActionDatum& dat) { DynamicCamera* that=(DynamicCamera*)dat.pair.first; const char* val=(const char*)dat.pair.second.ptr; if (0 == strcmp(val, "none" )) that->setRotateMode(DynamicCamera::None); else if (0 == strcmp(val, "rotation")) that->setRotateMode(DynamicCamera::Direction); else if (0 == strcmp(val, "velocity")) that->setRotateMode(DynamicCamera::Velocity); else return; conf["conf"]["camera"]["mode"]=val; } }; void DynamicCamera::hc_conf_bind() { ActionDatum thisPair; thisPair.pair.first=(void*)this; thisPair.pair.second.ptr=NULL; DigitalAction da_zoom = {thisPair, true, false, dyncam_action::zoom, NULL}, da_lkah = {thisPair, true, false, dyncam_action::lookahead, NULL}, da_mode = {thisPair, false, false, dyncam_action::set_mode, NULL}; bind( da_zoom, "adjust camera zoom", Float, true, getFloatLimit(5) ); bind( da_lkah, "adjust camera lookahead", Float, true, getFloatLimit(0.5f) ); bind( da_mode, "set camera mode", CString, true ); hud.hc_conf_bind(); }
/** * @file * @author Jason Lingle * @brief Implementation of src/camera/dynamic_camera.hxx */ #include <cmath> #include <cstdlib> #include <cstring> #include <iostream> #include "camera.hxx" #include "dynamic_camera.hxx" #include "src/globals.hxx" #include "src/control/human_controller.hxx" #include "src/control/hc_conf.hxx" #include "src/graphics/matops.hxx" #include "src/graphics/asgi.hxx" using namespace std; using namespace hc_conf; #define ACCEL_SPEED 0.001f #define MOVE_SPEED 0.01f #define ZOOM_SPEED 0.002f #define STABILIZE_RATIO_SEC 0.1f #define ROT_SPEED (2*pi/1000.0f) bool debug_dynamicCameraDisableVibration=false; DynamicCamera::DynamicCamera(GameObject* ref, GameField* field) : Camera(ref), currX(ref? ref->getX(): 0), currY(ref? ref->getY() : 0), currZ(1.0f), currT(0), vibration(0), vx(0), vy(0), zoom(0.35f), rotateMode(None), lookAhead(conf["conf"]["camera"]["lookahead"]), targetRotation(0), baseDetailLevel(conf["conf"]["graphics"]["detail_level"]), hud((Ship*)ref, field) { const char* mode=conf["conf"]["camera"]["mode"]; if (0 == strcmp(mode, "none")) rotateMode=None; else if (0 == strcmp(mode, "rotation")) rotateMode=Direction; else if (0 == strcmp(mode, "velocity")) rotateMode=Velocity; } DynamicCamera::~DynamicCamera() { asgi::reset(); glClearColor(0,0,0,1); //Restore actual detail level config conf["conf"]["graphics"]["detail_level"]=(int)baseDetailLevel; } #define ref reference void DynamicCamera::doSetup() noth { if (debug_dynamicCameraDisableVibration) vibration=0; if (!ref) return; //Adjust detail level for zoom. Always round down (for better //quality) and never decrease beyond the base conf["conf"]["graphics"]["detail_level"] = min(8, (int)(currZ > 1? baseDetailLevel : (unsigned)(baseDetailLevel/currZ))); //Handle vibration float vibx=vibration*(rand()/(float)RAND_MAX) - vibration/2, viby=vibration*(rand()/(float)RAND_MAX) - vibration/2; mTrans(0.5f, vheight/2-(rotateMode!=None? lookAhead*vheight : 0), matrix_stack::view); mUScale(currZ, matrix_stack::view); mRot(-currT, matrix_stack::view); mTrans(-currX+vibx, -currY+viby, matrix_stack::view); //We form a box around the largest possible area, regardless //of actual orientation. //A constantly-changing framerate is more distracting than //a consistently low framerate (eg, on slower computers) float cx=currX - vibx/currZ - (rotateMode!=None? lookAhead : 0)*sin(currT)/currZ, cy=currY - viby/currZ + (rotateMode!=None? lookAhead : 0)*cos(currT)/currZ; float ratio=sqrt(2.0f)/2.0f/currZ; cameraX1=cx - ratio; cameraX2=cx + ratio; cameraY1=cy - ratio/* *vheight*/; cameraY2=cy + ratio/* *vheight*/; cameraCX=currX - vibx/currZ; cameraCY=currY - viby/currZ; cameraZoom=currZ; float cornerAngle=atan2(vheight/2, 0.5f); float cornerDist=sqrt(vheight*vheight/4 + 0.25f)/currZ; screenCorners[0].first = cornerDist*cos(cornerAngle + currT) + cx; screenCorners[0].second= cornerDist*sin(cornerAngle + currT) + cy; screenCorners[1].first = cornerDist*cos(pi - cornerAngle + currT) + cx; screenCorners[1].second= cornerDist*sin(pi - cornerAngle + currT) + cy; screenCorners[2].first = cornerDist*cos(pi + cornerAngle + currT) + cx; screenCorners[2].second= cornerDist*sin(pi + cornerAngle + currT) + cy; screenCorners[3].first = cornerDist*cos(-cornerAngle + currT) + cx; screenCorners[3].second= cornerDist*sin(-cornerAngle + currT) + cy; //glLineWidth(currZ); //glPointSize(currZ); mId(); } void DynamicCamera::update(float time) noth { Ship* s=NULL; hud.setRef(s=dynamic_cast<Ship*>(const_cast<GameObject*>(ref))); hud.update(time); targetRotation=getRotation(); /* Lower frame-rates can give a "choppy" feel, since the math we use * will result in the camera jumping around a bit. * Force updates to a 10ms granularity. */ for (float t=time; t>0; t -= 10) { float time = (t>10? 10 : t); currX+=vx*time; currY+=vy*time; if (currT!=targetRotation) { float diff=currT-targetRotation; if (diff<-pi) diff+=2*pi; if (diff>+pi) diff-=2*pi; if (diff<0) { if (fabs(diff)<ROT_SPEED*time) currT=targetRotation; else { currT+=ROT_SPEED*time; if (currT>2*pi) currT-=2*pi; } } else if (diff>0) { if (fabs(diff)<ROT_SPEED*time) currT=targetRotation; else { currT-=ROT_SPEED*time; if (currT<0) currT+=2*pi; } } } if (currZ<zoom) { currZ+=time*ZOOM_SPEED*currZ; if (currZ>zoom) currZ=zoom; } else if (currZ>zoom) { currZ-=time*ZOOM_SPEED*currZ; if (currZ<zoom) currZ=zoom; } vibration*=pow(STABILIZE_RATIO_SEC, time/1000.0f); if (!ref) continue; //Adjust vx and vy as necessary float tx=ref->getX(), ty=ref->getY(); float dx=tx-currX, dy=ty-currY; currX+=dx*MOVE_SPEED*time; currY+=dy*MOVE_SPEED*time; float dvx=vx-ref->getVX(), dvy=vy-ref->getVY(); vx-=dvx*ACCEL_SPEED*time; vy-=dvy*ACCEL_SPEED*time; } } void DynamicCamera::drawOverlays() noth { hud.draw(this); } void DynamicCamera::reset() noth { //currZ=zoom; currX=ref->getX(); currY=ref->getY(); vibration=0; vx=vy=0; currT=targetRotation=getRotation(); float ratio=sqrt(2.0f)/currZ/2; cameraX1=currX-ratio; cameraX2=currX+ratio; cameraY1=currY-ratio*vheight; cameraY2=currY+ratio*vheight; } void DynamicCamera::impact(float amt) noth { vibration+=amt*15; hud.damage(amt); } float DynamicCamera::getZoom() const noth { return zoom; } void DynamicCamera::setZoom(float z) noth { if (z>=0.1f && z<=2.0f) zoom=z; } float DynamicCamera::getLookAhead() const noth { return lookAhead; } void DynamicCamera::setLookAhead(float l) noth { if (l>0 && l<vheight/2) lookAhead=l; } DynamicCamera::RotateMode DynamicCamera::getRotateMode() const noth { return rotateMode; } void DynamicCamera::setRotateMode(RotateMode mode) noth { rotateMode=mode; } //When in Velocity mode, when under this speed, we factor actual rotation in //according to the closeness to this speed #define MIN_VEL_SPEED 0.00005f float DynamicCamera::getRotation() const noth { if (!ref) return 0; switch (rotateMode) { case None: return 0; case Direction: return ref->getRotation()-pi/2; case Velocity: float velang=atan2(ref->getVY(), ref->getVX()); if (velang!=velang || sqrt(ref->getVX()*ref->getVX() + ref->getVY()*ref->getVY())<MIN_VEL_SPEED) return ref->getRotation()-pi/2; else return velang-pi/2; } return 0; } namespace dyncam_action { void zoom(Ship* s, ActionDatum& dat) { DynamicCamera* that=(DynamicCamera*)dat.pair.first; float amt=dat.pair.second.amt; that->setZoom(that->getZoom()+amt); } void lookahead(Ship* s, ActionDatum& dat) { DynamicCamera* that=(DynamicCamera*)dat.pair.first; float amt=dat.pair.second.amt; that->setLookAhead(that->getLookAhead()+amt); conf["conf"]["camera"]["lookahead"]=that->getLookAhead(); } void set_mode(Ship* s, ActionDatum& dat) { DynamicCamera* that=(DynamicCamera*)dat.pair.first; const char* val=(const char*)dat.pair.second.ptr; if (0 == strcmp(val, "none" )) that->setRotateMode(DynamicCamera::None); else if (0 == strcmp(val, "rotation")) that->setRotateMode(DynamicCamera::Direction); else if (0 == strcmp(val, "velocity")) that->setRotateMode(DynamicCamera::Velocity); else return; conf["conf"]["camera"]["mode"]=val; } }; void DynamicCamera::hc_conf_bind() { ActionDatum thisPair; thisPair.pair.first=(void*)this; thisPair.pair.second.ptr=NULL; DigitalAction da_zoom = {thisPair, true, false, dyncam_action::zoom, NULL}, da_lkah = {thisPair, true, false, dyncam_action::lookahead, NULL}, da_mode = {thisPair, false, false, dyncam_action::set_mode, NULL}; bind( da_zoom, "adjust camera zoom", Float, true, getFloatLimit(5) ); bind( da_lkah, "adjust camera lookahead", Float, true, getFloatLimit(0.5f) ); bind( da_mode, "set camera mode", CString, true ); hud.hc_conf_bind(); }
Multiply camera lookAhead by vheight so the same value works on all ratios.
Multiply camera lookAhead by vheight so the same value works on all ratios.
C++
bsd-3-clause
AltSysrq/Abendstern,AltSysrq/Abendstern
69846bcbd8b449aeca6c94d2355cd107b8cd3fc3
src/cbang/http/WebHandler.cpp
src/cbang/http/WebHandler.cpp
/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2019, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. The C! library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland [email protected] \******************************************************************************/ #include "WebHandler.h" #include "Context.h" #include "Connection.h" #include "Response.h" #include "Request.h" #include "WebContext.h" #include "FileWebPageHandler.h" #include <cbang/Info.h> #include <cbang/SStream.h> #include <cbang/config/Options.h> #include <cbang/log/Logger.h> #include <cbang/xml/XMLWriter.h> #include <cbang/script/MemberFunctor.h> using namespace std; using namespace cb; using namespace cb::HTTP; using namespace cb::Script; WebHandler::WebHandler(Options &options, const string &match, hasFeature_t hasFeature) : Features(hasFeature), HTTP::Handler(match), options(options), initialized(false) { options.pushCategory("Web Server"); if (hasFeature(FEATURE_FS_STATIC)) options.add("web-static", "Path to static web pages. Empty to disable " "filesystem access for static pages.")->setDefault("www"); options.add("web-allow", "Client addresses which are allowed to connect to " "this Web server. This option overrides IPs which are denied in " "the web-deny option. This option differs from the " "'allow'/'deny' options in that clients that are not allowed " "are served an access denied page rather than simply dropping " "the connection. The value '0/0' matches all IPs." )->setDefault("0/0"); options.add("web-deny", "Client address which are not allowed to connect to " "this Web server.")->setDefault(""); options.popCategory(); } bool WebHandler::_hasFeature(int feature) { return true; } void WebHandler::init() { if (initialized) return; initialized = true; // IP filters ipFilter.allow(options["web-allow"]); ipFilter.deny(options["web-deny"]); if (hasFeature(FEATURE_FS_STATIC) && options["web-static"].hasValue()) addHandler(new FileWebPageHandler(options["web-static"])); } bool WebHandler::allow(WebContext &ctx) const { return ipFilter.isAllowed(ctx.getConnection().getClientIP().getIP()); } void WebHandler::errorPage(WebContext &ctx, StatusCode status, const string &message) const { ctx.errorPage(status, message); } bool WebHandler::handlePage(WebContext &ctx, ostream &stream, const URI &uri) { if (WebPageHandlerGroup::handlePage(ctx, stream, uri)) { // Tell client to cache static pages if (ctx.isStatic()) ctx.getConnection().getResponse().setCacheExpire(); // Set default content type Response &response = ctx.getConnection().getResponse(); if (!response.has("Content-Type")) response.setContentTypeFromExtension(uri.getPath()); return true; } return false; } HTTP::Context *WebHandler::createContext(Connection *con) { return new WebContext(*this, *con); } void WebHandler::buildResponse(HTTP::Context *_ctx) { if (!initialized) THROW("Not initialized"); WebContext *ctx = dynamic_cast<WebContext *>(_ctx); if (!ctx) THROW("Expected WebContext"); Connection &con = ctx->getConnection(); // Check request method Request &request = con.getRequest(); switch (request.getMethod()) { case RequestMethod::HTTP_GET: case RequestMethod::HTTP_POST: break; default: return; // We only handle GET and POST } try { if (!allow(*ctx)) errorPage(*ctx, StatusCode::HTTP_UNAUTHORIZED); else { URI uri = con.getRequest().getURI(); const string &path = uri.getPath(); if (path[path.length() - 1] == '/') uri.setPath(path + "index.html"); // TODO sanitize path if (!handlePage(*ctx, con, uri)) errorPage(*ctx, StatusCode::HTTP_NOT_FOUND); } } catch (const Exception &e) { StatusCode code = StatusCode::HTTP_INTERNAL_SERVER_ERROR; if (0 < e.getCode()) code = (StatusCode::enum_t)e.getCode(); errorPage(*ctx, code, e.getMessage()); LOG_ERROR(code << ": " << e); } con << flush; }
/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2019, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. The C! library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland [email protected] \******************************************************************************/ #include "WebHandler.h" #include "Context.h" #include "Connection.h" #include "Response.h" #include "Request.h" #include "WebContext.h" #include "FileWebPageHandler.h" #include <cbang/Info.h> #include <cbang/SStream.h> #include <cbang/config/Options.h> #include <cbang/log/Logger.h> #include <cbang/xml/XMLWriter.h> #include <cbang/script/MemberFunctor.h> using namespace std; using namespace cb; using namespace cb::HTTP; using namespace cb::Script; WebHandler::WebHandler(Options &options, const string &match, hasFeature_t hasFeature) : Features(hasFeature), HTTP::Handler(match), options(options), initialized(false) { options.pushCategory("Web Server"); if (hasFeature(FEATURE_FS_STATIC)) options.add("web-static", "Path to static web pages. Empty to disable " "filesystem access for static pages.")->setDefault("www"); options.add("web-allow", "Client addresses which are allowed to connect to " "this Web server. This option overrides IPs which are denied in " "the web-deny option. This option differs from the " "'allow'/'deny' options in that clients that are not allowed " "are served an access denied page rather than simply dropping " "the connection. The value '0/0' matches all IPs." )->setDefault("0/0"); options.add("web-deny", "Client address which are not allowed to connect to " "this Web server.")->setDefault(""); options.popCategory(); } bool WebHandler::_hasFeature(int feature) { return true; } void WebHandler::init() { if (initialized) return; initialized = true; // IP filters ipFilter.allow(options["web-allow"]); ipFilter.deny(options["web-deny"]); if (hasFeature(FEATURE_FS_STATIC) && options["web-static"].hasValue()) addHandler(new FileWebPageHandler(options["web-static"])); } bool WebHandler::allow(WebContext &ctx) const { return ipFilter.isAllowed(ctx.getConnection().getClientIP().getIP()); } void WebHandler::errorPage(WebContext &ctx, StatusCode status, const string &message) const { ctx.errorPage(status, message); } bool WebHandler::handlePage(WebContext &ctx, ostream &stream, const URI &uri) { if (WebPageHandlerGroup::handlePage(ctx, stream, uri)) { // Tell client to cache static pages if (ctx.isStatic()) ctx.getConnection().getResponse().setCacheExpire(); // Set default content type Response &response = ctx.getConnection().getResponse(); if (!response.has("Content-Type")) response.setContentTypeFromExtension(uri.getPath()); return true; } return false; } HTTP::Context *WebHandler::createContext(Connection *con) { return new WebContext(*this, *con); } void WebHandler::buildResponse(HTTP::Context *_ctx) { if (!initialized) THROW("Not initialized"); WebContext *ctx = dynamic_cast<WebContext *>(_ctx); if (!ctx) THROW("Expected WebContext"); Connection &con = ctx->getConnection(); try { if (!allow(*ctx)) errorPage(*ctx, StatusCode::HTTP_UNAUTHORIZED); else { URI uri = con.getRequest().getURI(); const string &path = uri.getPath(); if (path[path.length() - 1] == '/') uri.setPath(path + "index.html"); // TODO sanitize path if (!handlePage(*ctx, con, uri)) errorPage(*ctx, StatusCode::HTTP_NOT_FOUND); } } catch (const Exception &e) { StatusCode code = StatusCode::HTTP_INTERNAL_SERVER_ERROR; if (0 < e.getCode()) code = (StatusCode::enum_t)e.getCode(); errorPage(*ctx, code, e.getMessage()); LOG_ERROR(code << ": " << e); } con << flush; }
Allow other HTTP methods
Allow other HTTP methods
C++
lgpl-2.1
CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang
440a4e25b89b24321e0f905ba442b595c37ae31a
plugins/single_plugins/move.cpp
plugins/single_plugins/move.cpp
#include <output.hpp> #include <core.hpp> #include <view.hpp> #include <workspace-manager.hpp> #include <render-manager.hpp> #include <linux/input.h> #include <signal-definitions.hpp> #include "snap_signal.hpp" #include "../wobbly/wobbly-signal.hpp" class wayfire_move : public wayfire_plugin_t { signal_callback_t move_request, view_destroyed; button_callback activate_binding; touch_callback touch_activate_binding; wayfire_view view; wf_option enable_snap, enable_snap_off, snap_threshold, snap_off_threshold; bool is_using_touch; bool was_client_request; bool unsnapped = false; // if the view was maximized or snapped, we wait a little bit before moving the view // while waiting, unsnapped = false int slot; wf_geometry initial_geometry; wf_point initial_cursor; public: void init(wayfire_config *config) { grab_interface->name = "move"; grab_interface->abilities_mask = WF_ABILITY_CHANGE_VIEW_GEOMETRY | WF_ABILITY_GRAB_INPUT; auto section = config->get_section("move"); wf_option button = section->get_option("activate", "<alt> BTN_LEFT"); activate_binding = [=] (uint32_t, int x, int y) { is_using_touch = false; was_client_request = false; auto focus = core->get_cursor_focus(); auto view = focus ? core->find_view(focus->get_main_surface()) : nullptr; if (view && view->role != WF_VIEW_ROLE_SHELL_VIEW) initiate(view, x, y); }; touch_activate_binding = [=] (int32_t sx, int32_t sy) { is_using_touch = true; was_client_request = false; auto focus = core->get_touch_focus(); auto view = focus ? core->find_view(focus->get_main_surface()) : nullptr; if (view && view->role != WF_VIEW_ROLE_SHELL_VIEW) initiate(view, sx, sy); }; output->add_button(button, &activate_binding); output->add_touch(new_static_option("<alt>"), &touch_activate_binding); enable_snap = section->get_option("enable_snap", "1"); enable_snap_off = section->get_option("enable_snap_off", "1"); snap_threshold = section->get_option("snap_threshold", "2"); snap_off_threshold = section->get_option("snap_off_threshold", "0"); using namespace std::placeholders; grab_interface->callbacks.pointer.button = [=] (uint32_t b, uint32_t state) { /* the request usually comes with the left button ... */ if (state == WLR_BUTTON_RELEASED && was_client_request && b == BTN_LEFT) return input_pressed(state); if (b != button->as_button().button) return; is_using_touch = false; input_pressed(state); }; grab_interface->callbacks.pointer.motion = [=] (int x, int y) { input_motion(x, y); }; grab_interface->callbacks.touch.motion = [=] (int32_t id, int32_t sx, int32_t sy) { if (id > 0) return; input_motion(sx, sy); }; grab_interface->callbacks.touch.up = [=] (int32_t id) { if (id == 0) input_pressed(WLR_BUTTON_RELEASED); }; grab_interface->callbacks.cancel = [=] () { input_pressed(WLR_BUTTON_RELEASED); }; move_request = std::bind(std::mem_fn(&wayfire_move::move_requested), this, _1); output->connect_signal("move-request", &move_request); view_destroyed = [=] (signal_data* data) { if (get_signaled_view(data) == view) { view = nullptr; input_pressed(WLR_BUTTON_RELEASED); } }; output->connect_signal("detach-view", &view_destroyed); output->connect_signal("unmap-view", &view_destroyed); } void move_requested(signal_data *data) { auto view = get_signaled_view(data); if (!view) return; int sx, sy; GetTuple(tx, ty, core->get_touch_position(0)); if (tx != wayfire_core::invalid_coordinate && ty != wayfire_core::invalid_coordinate) { sx = tx; sy = ty; is_using_touch = true; } else { GetTuple(px, py, core->get_cursor_position()); sx = px; sy = py; is_using_touch = false; } was_client_request = true; initiate(view, sx, sy); } void initiate(wayfire_view view, int sx, int sy) { if (!view || view->destroyed) return; if (!output->workspace-> get_implementation(output->workspace->get_current_workspace())-> view_movable(view)) return; if (view->get_output() != output) return; if (!output->activate_plugin(grab_interface)) return; if (!grab_interface->grab()) { output->deactivate_plugin(grab_interface); return; } unsnapped = !view->maximized; initial_geometry = view->get_wm_geometry(); initial_cursor = {sx, sy}; output->bring_to_front(view); if (enable_snap) slot = 0; this->view = view; output->render->auto_redraw(true); start_wobbly(view, sx, sy); if (!unsnapped) snap_wobbly(view, view->get_output_geometry()); core->set_cursor("grabbing"); } void input_pressed(uint32_t state) { if (state != WLR_BUTTON_RELEASED) return; grab_interface->ungrab(); output->deactivate_plugin(grab_interface); output->render->auto_redraw(false); if (view) { if (view->role == WF_VIEW_ROLE_SHELL_VIEW) return; end_wobbly(view); view->set_moving(false); if (enable_snap && slot != 0) { snap_signal data; data.view = view; data.tslot = (slot_type)slot; output->emit_signal("view-snap", &data); } } } int calc_slot(int x, int y) { auto g = output->workspace->get_workarea(); if (!point_inside({x, y}, output->get_relative_geometry())) return 0; bool is_left = x - g.x <= snap_threshold->as_cached_int(); bool is_right = g.x + g.width - x <= snap_threshold->as_cached_int(); bool is_top = y - g.y < snap_threshold->as_cached_int(); bool is_bottom = g.x + g.height - y < snap_threshold->as_cached_int(); if (is_left && is_top) return SLOT_TL; else if (is_left && is_bottom) return SLOT_BL; else if (is_left) return SLOT_LEFT; else if (is_right && is_top) return SLOT_TR; else if (is_right && is_bottom) return SLOT_BR; else if (is_right) return SLOT_RIGHT; else if (is_top) return SLOT_CENTER; else if (is_bottom) return SLOT_BOTTOM; else return 0; } void input_motion(int x, int y) { move_wobbly(view, x, y); int dx = x - initial_cursor.x; int dy = y - initial_cursor.y; if (std::sqrt(dx * dx + dy * dy) >= snap_off_threshold->as_cached_int() && !unsnapped && enable_snap_off->as_int()) { unsnapped = 1; if (view->fullscreen) view->fullscreen_request(view->get_output(), false); if (view->maximized) view->maximize_request(false); /* view geometry might change after unmaximize/unfullscreen, so update position */ initial_geometry = view->get_wm_geometry(); snap_wobbly(view, {}, false); view->set_moving(true); } if (!unsnapped) return; view->move(initial_geometry.x + dx, initial_geometry.y + dy); std::tuple<int, int> global_input; if (is_using_touch) { global_input = core->get_touch_position(0); } else { global_input = core->get_cursor_position(); } GetTuple(global_x, global_y, global_input); auto target_output = core->get_output_at(global_x, global_y); if (target_output != output) { move_request_signal req; req.view = view; auto old_g = output->get_full_geometry(); auto new_g = target_output->get_full_geometry(); auto wm_g = view->get_wm_geometry(); view->move(wm_g.x + old_g.x - new_g.x, wm_g.y + old_g.y - new_g.y, false); view->set_moving(false); core->move_view_to_output(view, target_output); core->focus_output(target_output); target_output->emit_signal("move-request", &req); return; } /* TODO: possibly show some visual indication */ if (enable_snap) slot = calc_slot(x, y); } void fini() { if (grab_interface->is_grabbed()) input_pressed(WLR_BUTTON_RELEASED); output->rem_binding(&activate_binding); output->rem_binding(&touch_activate_binding); output->disconnect_signal("move-request", &move_request); output->disconnect_signal("detach-view", &view_destroyed); output->disconnect_signal("unmap-view", &view_destroyed); } }; extern "C" { wayfire_plugin_t* newInstance() { return new wayfire_move(); } }
#include <output.hpp> #include <core.hpp> #include <view.hpp> #include <workspace-manager.hpp> #include <render-manager.hpp> #include <linux/input.h> #include <signal-definitions.hpp> #include "snap_signal.hpp" #include "../wobbly/wobbly-signal.hpp" class wayfire_move : public wayfire_plugin_t { signal_callback_t move_request, view_destroyed; button_callback activate_binding; touch_callback touch_activate_binding; wayfire_view view; wf_option enable_snap, enable_snap_off, snap_threshold, snap_off_threshold; bool is_using_touch; bool was_client_request; bool unsnapped = false; // if the view was maximized or snapped, we wait a little bit before moving the view // while waiting, unsnapped = false int slot; wf_geometry grabbed_geometry; wf_point grab_start; public: void init(wayfire_config *config) { grab_interface->name = "move"; grab_interface->abilities_mask = WF_ABILITY_CHANGE_VIEW_GEOMETRY | WF_ABILITY_GRAB_INPUT; auto section = config->get_section("move"); wf_option button = section->get_option("activate", "<alt> BTN_LEFT"); activate_binding = [=] (uint32_t, int, int) { is_using_touch = false; was_client_request = false; auto focus = core->get_cursor_focus(); auto view = focus ? core->find_view(focus->get_main_surface()) : nullptr; if (view && view->role != WF_VIEW_ROLE_SHELL_VIEW) initiate(view); }; touch_activate_binding = [=] (int32_t sx, int32_t sy) { is_using_touch = true; was_client_request = false; auto focus = core->get_touch_focus(); auto view = focus ? core->find_view(focus->get_main_surface()) : nullptr; if (view && view->role != WF_VIEW_ROLE_SHELL_VIEW) initiate(view); }; output->add_button(button, &activate_binding); output->add_touch(new_static_option("<alt>"), &touch_activate_binding); enable_snap = section->get_option("enable_snap", "1"); enable_snap_off = section->get_option("enable_snap_off", "1"); snap_threshold = section->get_option("snap_threshold", "2"); snap_off_threshold = section->get_option("snap_off_threshold", "0"); using namespace std::placeholders; grab_interface->callbacks.pointer.button = [=] (uint32_t b, uint32_t state) { /* the request usually comes with the left button ... */ if (state == WLR_BUTTON_RELEASED && was_client_request && b == BTN_LEFT) return input_pressed(state); if (b != button->as_button().button) return; is_using_touch = false; input_pressed(state); }; grab_interface->callbacks.pointer.motion = [=] (int x, int y) { handle_input_motion(); }; grab_interface->callbacks.touch.motion = [=] (int32_t id, int32_t sx, int32_t sy) { if (id > 0) return; handle_input_motion(); }; grab_interface->callbacks.touch.up = [=] (int32_t id) { if (id == 0) input_pressed(WLR_BUTTON_RELEASED); }; grab_interface->callbacks.cancel = [=] () { input_pressed(WLR_BUTTON_RELEASED); }; move_request = std::bind(std::mem_fn(&wayfire_move::move_requested), this, _1); output->connect_signal("move-request", &move_request); view_destroyed = [=] (signal_data* data) { if (get_signaled_view(data) == view) { view = nullptr; input_pressed(WLR_BUTTON_RELEASED); } }; output->connect_signal("detach-view", &view_destroyed); output->connect_signal("unmap-view", &view_destroyed); } void move_requested(signal_data *data) { auto view = get_signaled_view(data); if (!view) return; GetTuple(tx, ty, core->get_touch_position(0)); if (tx != wayfire_core::invalid_coordinate && ty != wayfire_core::invalid_coordinate) { is_using_touch = true; } else { is_using_touch = false; } was_client_request = true; initiate(view); } void initiate(wayfire_view view) { if (!view || view->destroyed) return; if (!output->workspace-> get_implementation(output->workspace->get_current_workspace())-> view_movable(view)) return; if (view->get_output() != output) return; if (!output->activate_plugin(grab_interface)) return; if (!grab_interface->grab()) { output->deactivate_plugin(grab_interface); return; } unsnapped = !view->maximized; grabbed_geometry = view->get_wm_geometry(); GetTuple(sx, sy, get_input_coords()); grab_start = {sx, sy}; output->bring_to_front(view); if (enable_snap) slot = 0; this->view = view; output->render->auto_redraw(true); start_wobbly(view, sx, sy); if (!unsnapped) snap_wobbly(view, view->get_output_geometry()); core->set_cursor("grabbing"); } void input_pressed(uint32_t state) { if (state != WLR_BUTTON_RELEASED) return; grab_interface->ungrab(); output->deactivate_plugin(grab_interface); output->render->auto_redraw(false); if (view) { if (view->role == WF_VIEW_ROLE_SHELL_VIEW) return; end_wobbly(view); view->set_moving(false); if (enable_snap && slot != 0) { snap_signal data; data.view = view; data.tslot = (slot_type)slot; output->emit_signal("view-snap", &data); } } } int calc_slot(int x, int y) { auto g = output->workspace->get_workarea(); if (!point_inside({x, y}, output->get_relative_geometry())) return 0; bool is_left = x - g.x <= snap_threshold->as_cached_int(); bool is_right = g.x + g.width - x <= snap_threshold->as_cached_int(); bool is_top = y - g.y < snap_threshold->as_cached_int(); bool is_bottom = g.x + g.height - y < snap_threshold->as_cached_int(); if (is_left && is_top) return SLOT_TL; else if (is_left && is_bottom) return SLOT_BL; else if (is_left) return SLOT_LEFT; else if (is_right && is_top) return SLOT_TR; else if (is_right && is_bottom) return SLOT_BR; else if (is_right) return SLOT_RIGHT; else if (is_top) return SLOT_CENTER; else if (is_bottom) return SLOT_BOTTOM; else return 0; } /* The input has moved enough so we remove the view from its slot */ void unsnap() { unsnapped = 1; if (view->fullscreen) view->fullscreen_request(view->get_output(), false); if (view->maximized) view->maximize_request(false); /* view geometry might change after unmaximize/unfullscreen, so update position */ grabbed_geometry = view->get_wm_geometry(); snap_wobbly(view, {}, false); view->set_moving(true); } /* Returns the currently used input coordinates in global compositor space */ std::tuple<int, int> get_global_input_coords() { if (is_using_touch) { return core->get_touch_position(0); } else { return core->get_cursor_position(); } } /* Returns the currently used input coordinates in output-local space */ std::tuple<int, int> get_input_coords() { GetTuple(gx, gy, get_global_input_coords()); auto og = output->get_full_geometry(); return std::tuple<int, int> {gx - og.x, gy - og.y}; } /* Moves the view to another output and sends a move request */ void move_to_output(wayfire_output *new_output) { move_request_signal req; req.view = view; auto old_g = output->get_full_geometry(); auto new_g = new_output->get_full_geometry(); auto wm_g = view->get_wm_geometry(); view->move(wm_g.x + old_g.x - new_g.x, wm_g.y + old_g.y - new_g.y, false); view->set_moving(false); core->move_view_to_output(view, new_output); core->focus_output(new_output); new_output->emit_signal("move-request", &req); } void handle_input_motion() { GetTuple(x, y, get_input_coords()); move_wobbly(view, x, y); int dx = x - grab_start.x; int dy = y - grab_start.y; if (std::sqrt(dx * dx + dy * dy) >= snap_off_threshold->as_cached_int() && !unsnapped && enable_snap_off->as_int()) { unsnap(); } if (!unsnapped) return; view->move(grabbed_geometry.x + dx, grabbed_geometry.y + dy); GetTuple(global_x, global_y, get_global_input_coords()); auto target_output = core->get_output_at(global_x, global_y); if (target_output != output) return move_to_output(target_output); /* TODO: possibly show some visual indication */ if (enable_snap) slot = calc_slot(x, y); } void fini() { if (grab_interface->is_grabbed()) input_pressed(WLR_BUTTON_RELEASED); output->rem_binding(&activate_binding); output->rem_binding(&touch_activate_binding); output->disconnect_signal("move-request", &move_request); output->disconnect_signal("detach-view", &view_destroyed); output->disconnect_signal("unmap-view", &view_destroyed); } }; extern "C" { wayfire_plugin_t* newInstance() { return new wayfire_move(); } }
refactor coordinate handling
move: refactor coordinate handling Fixes #92 We handled them incorrectly in case of multiple outputs.
C++
mit
ammen99/wayfire,ammen99/wayfire
ffc6a588bd485a63726692986c228926125fae37
src/compiler/csharp_plugin.cc
src/compiler/csharp_plugin.cc
/* * * Copyright 2015 gRPC authors. * * 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. * */ // Generates C# gRPC service interface out of Protobuf IDL. #include <memory> #include "src/compiler/config.h" #include "src/compiler/csharp_generator.h" #include "src/compiler/csharp_generator_helpers.h" class CSharpGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { public: CSharpGrpcGenerator() {} ~CSharpGrpcGenerator() {} uint64_t GetSupportedFeatures() const override { return FEATURE_PROTO3_OPTIONAL; } bool Generate(const grpc::protobuf::FileDescriptor* file, const std::string& parameter, grpc::protobuf::compiler::GeneratorContext* context, std::string* error) const override { std::vector<std::pair<std::string, std::string> > options; grpc::protobuf::compiler::ParseGeneratorParameter(parameter, &options); bool generate_client = true; bool generate_server = true; bool internal_access = false; // the suffix that will get appended to the name generated from the name // of the original .proto file std::string file_suffix = "Grpc.cs"; for (size_t i = 0; i < options.size(); i++) { if (options[i].first == "no_client") { generate_client = false; } else if (options[i].first == "no_server") { generate_server = false; } else if (options[i].first == "internal_access") { internal_access = true; } if (options[i].first == "file_suffix") { file_suffix = options[i].second; } else { *error = "Unknown generator option: " + options[i].first; return false; } } std::string code = grpc_csharp_generator::GetServices( file, generate_client, generate_server, internal_access); if (code.size() == 0) { return true; // don't generate a file if there are no services } // Get output file name. std::string file_name; if (!grpc_csharp_generator::ServicesFilename(file, file_suffix, file_name)) { return false; } std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> output( context->Open(file_name)); grpc::protobuf::io::CodedOutputStream coded_out(output.get()); coded_out.WriteRaw(code.data(), code.size()); return true; } }; int main(int argc, char* argv[]) { CSharpGrpcGenerator generator; return grpc::protobuf::compiler::PluginMain(argc, argv, &generator); }
/* * * Copyright 2015 gRPC authors. * * 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. * */ // Generates C# gRPC service interface out of Protobuf IDL. #include <memory> #include "src/compiler/config.h" #include "src/compiler/csharp_generator.h" #include "src/compiler/csharp_generator_helpers.h" class CSharpGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { public: CSharpGrpcGenerator() {} ~CSharpGrpcGenerator() {} uint64_t GetSupportedFeatures() const override { return FEATURE_PROTO3_OPTIONAL; } bool Generate(const grpc::protobuf::FileDescriptor* file, const std::string& parameter, grpc::protobuf::compiler::GeneratorContext* context, std::string* error) const override { std::vector<std::pair<std::string, std::string> > options; grpc::protobuf::compiler::ParseGeneratorParameter(parameter, &options); bool generate_client = true; bool generate_server = true; bool internal_access = false; // the suffix that will get appended to the name generated from the name // of the original .proto file std::string file_suffix = "Grpc.cs"; for (size_t i = 0; i < options.size(); i++) { if (options[i].first == "no_client") { generate_client = false; } else if (options[i].first == "no_server") { generate_server = false; } else if (options[i].first == "internal_access") { internal_access = true; } else if (options[i].first == "file_suffix") { file_suffix = options[i].second; } else { *error = "Unknown generator option: " + options[i].first; return false; } } std::string code = grpc_csharp_generator::GetServices( file, generate_client, generate_server, internal_access); if (code.size() == 0) { return true; // don't generate a file if there are no services } // Get output file name. std::string file_name; if (!grpc_csharp_generator::ServicesFilename(file, file_suffix, file_name)) { return false; } std::unique_ptr<grpc::protobuf::io::ZeroCopyOutputStream> output( context->Open(file_name)); grpc::protobuf::io::CodedOutputStream coded_out(output.get()); coded_out.WriteRaw(code.data(), code.size()); return true; } }; int main(int argc, char* argv[]) { CSharpGrpcGenerator generator; return grpc::protobuf::compiler::PluginMain(argc, argv, &generator); }
Fix C# protoc plugin argument parsing (#26896) (#27178)
Fix C# protoc plugin argument parsing (#26896) (#27178) Co-authored-by: apolcyn <[email protected]>
C++
apache-2.0
donnadionne/grpc,donnadionne/grpc,donnadionne/grpc,donnadionne/grpc,donnadionne/grpc,donnadionne/grpc,donnadionne/grpc,donnadionne/grpc,donnadionne/grpc,donnadionne/grpc,donnadionne/grpc,donnadionne/grpc
d8688df7dbda08f257a3711ae0da758649a7972c
src/condor_utils/condor_base64.cpp
src/condor_utils/condor_base64.cpp
/*************************************************************** * * Copyright (C) 1990-2016, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_base64.h" static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(BYTE c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string Base64::condor_base64_encode(BYTE const* buf, unsigned int bufLen) { std::string ret; int i = 0; int j = 0; BYTE char_array_3[3]; BYTE char_array_4[4]; int count = 0; while (bufLen--) { char_array_3[i++] = *(buf++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]]; count += 4; i = 0; } if (count == 76) { ret += '\n'; count = 0; } } if (i) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ < 3)) ret += '='; } return ret; } std::vector<BYTE> Base64::condor_base64_decode(std::string encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; BYTE char_array_4[4], char_array_3[3]; std::vector<BYTE> ret; while (in_len-- && ( (encoded_string[in_]=='\n') || (( encoded_string[in_] != '=') && is_base64(encoded_string[in_])))) { if(encoded_string[in_]=='\n') { in_++; continue; } char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret.push_back(char_array_3[i]); i = 0; } } if (i) { for (j = i; j <4; j++) char_array_4[j] = 0; for (j = 0; j <4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret.push_back(char_array_3[j]); } return ret; } // Caller needs to free the returned pointer char* condor_base64_encode(const unsigned char *input, int length) { std::string tstr = Base64::condor_base64_encode(input, length); return strdup(tstr.c_str()); } // Caller needs to free *output if non-NULL void condor_base64_decode(const char *input,unsigned char **output, int *output_length) { std::string tinput(input); std::vector<BYTE> tvec = Base64::condor_base64_decode(tinput); *output_length = tvec.size(); if (*output_length > 0 ) { *output=(unsigned char*)malloc(*output_length); memcpy(*output, tvec.data(), *output_length); } }
/*************************************************************** * * Copyright (C) 1990-2016, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_base64.h" static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(BYTE c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string Base64::condor_base64_encode(BYTE const* buf, unsigned int bufLen) { std::string ret; int i = 0; int j = 0; BYTE char_array_3[3]; BYTE char_array_4[4]; int count = 0; while (bufLen--) { char_array_3[i++] = *(buf++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) { ret += base64_chars[char_array_4[i]]; } count += 4; i = 0; } if (count == 76) { ret += '\n'; count = 0; } } if (i) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ < 3)) ret += '='; } return ret; } std::vector<BYTE> Base64::condor_base64_decode(std::string encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; BYTE char_array_4[4], char_array_3[3]; std::vector<BYTE> ret; while (in_len-- && ( (encoded_string[in_]=='\n') || (( encoded_string[in_] != '=') && is_base64(encoded_string[in_])))) { if(encoded_string[in_]=='\n') { in_++; continue; } char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret.push_back(char_array_3[i]); i = 0; } } if (i) { for (j = i; j <4; j++) char_array_4[j] = 0; for (j = 0; j <4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret.push_back(char_array_3[j]); } return ret; } // Caller needs to free the returned pointer char* condor_base64_encode(const unsigned char *input, int length) { std::string tstr = Base64::condor_base64_encode(input, length); return strdup(tstr.c_str()); } // Caller needs to free *output if non-NULL void condor_base64_decode(const char *input,unsigned char **output, int *output_length) { std::string tinput(input); std::vector<BYTE> tvec = Base64::condor_base64_decode(tinput); *output_length = tvec.size(); if (*output_length > 0 ) { *output=(unsigned char*)malloc(*output_length); memcpy(*output, tvec.data(), *output_length); } }
Fix formatting of #6879
Fix formatting of #6879
C++
apache-2.0
htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor
0a6d1cfeee2909f21a1db6204bcc670b9ca95f91
src/engine/botlib/bot_nav_edit.cpp
src/engine/botlib/bot_nav_edit.cpp
/* =========================================================================== Daemon GPL Source Code Copyright (C) 2012 Unvanquished Developers This file is part of the Daemon GPL Source Code (Daemon Source Code). Daemon Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Daemon Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Daemon Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ extern "C" { #include "../client/client.h" } #include "../../libs/detour/DetourDebugDraw.h" #include "../../libs/detour/DebugDraw.h" #include "bot_navdraw.h" #include "nav.h" #define DEFAULT_CONNECTION_SIZE 50 static int connectionSize = DEFAULT_CONNECTION_SIZE; bool GetPointPointedTo( NavData_t *nav, rVec &p ) { qVec forward; qVec end; rVec extents; rVec pos; trace_t trace; dtPolyRef nearRef; VectorSet( extents, 640, 96, 640 ); AngleVectors( cl.snap.ps.viewangles, forward, NULL, NULL ); VectorMA( cl.snap.ps.origin, 8096, forward, end ); CM_BoxTrace( &trace, cl.snap.ps.origin, end, NULL, NULL, 0, CONTENTS_SOLID | CONTENTS_PLAYERCLIP, TT_AABB ); pos = qVec( trace.endpos ); if ( dtStatusFailed( nav->query->findNearestPoly( pos, extents, &nav->filter, &nearRef, p ) ) ) { return false; } return true; } static struct { bool enabled; bool offBegin; OffMeshConnection pc; NavData_t *nav; } cmd; void BotDrawNavEdit( DebugDrawQuake *dd ) { rVec p; if ( cmd.enabled && GetPointPointedTo( cmd.nav, p ) ) { unsigned int col = duRGBA( 255, 255, 255, 220 ); dd->begin( DU_DRAW_LINES, 2.0f ); duAppendCircle( dd, p[ 0 ], p[ 1 ], p[ 2 ], connectionSize, col ); if ( cmd.offBegin ) { duAppendArc( dd, cmd.pc.start[ 0 ], cmd.pc.start[ 1 ], cmd.pc.start[ 2 ], p[ 0 ], p[ 1 ], p[ 2 ], 0.25f, 0.6f, 0.6f, col ); duAppendCircle( dd, cmd.pc.start[ 0 ], cmd.pc.start[ 1 ], cmd.pc.start[ 2 ], connectionSize, col ); } dd->end(); } } void DrawPath( Bot_t *bot, DebugDrawQuake &dd ) { dd.depthMask(false); const unsigned int spathCol = duRGBA(128,128,128,255); dd.begin(DU_DRAW_LINES, 3.0f); dd.vertex( bot->corridor.getPos(), spathCol ); for (int i = 0; i < bot->numCorners; ++i) dd.vertex(bot->cornerVerts[i*3], bot->cornerVerts[i*3+1]+5.0f, bot->cornerVerts[i*3+2], spathCol); if ( bot->numCorners < MAX_CORNERS - 1 ) { if ( bot->numCorners % 2 != 0 ) { dd.vertex( &bot->cornerVerts[ ( bot->numCorners - 1 ) * 3 ], spathCol ); } dd.vertex( bot->corridor.getTarget(), spathCol ); } dd.end(); dd.depthMask(true); } extern "C" void BotDebugDrawMesh( BotDebugInterface_t *in ) { static DebugDrawQuake dd; dd.init( in ); if ( !cmd.enabled ) { return; } if ( !cmd.nav ) { return; } if ( !cmd.nav->mesh || !cmd.nav->query ) { return; } duDebugDrawNavMeshWithClosedList(&dd, *cmd.nav->mesh, *cmd.nav->query, DU_DRAWNAVMESH_OFFMESHCONS | DU_DRAWNAVMESH_CLOSEDLIST); BotDrawNavEdit( &dd ); for ( int i = 0; i < MAX_CLIENTS; i++ ) { Bot_t *bot = &agents[ i ]; if ( bot->nav == cmd.nav ) { DrawPath( bot, dd ); } } } void Cmd_NavEdit( void ) { int argc = Cmd_Argc(); char *arg = NULL; const char usage[] = "Usage: navedit enable/disable/save <navmesh>\n"; if ( !Cvar_VariableIntegerValue( "sv_cheats" ) ) { Com_Printf( "navedit only available in local devmap\n" ); return; } if ( argc < 2 ) { Com_Printf( "%s", usage ); return; } arg = Cmd_Argv( 1 ); if ( !Q_stricmp( arg, "enable" ) ) { if ( argc < 3 ) { Com_Printf( "%s", usage ); return; } arg = Cmd_Argv( 2 ); for ( int i = 0; i < numNavData; i++ ) { if ( !Q_stricmp( BotNavData[ i ].name, arg ) ) { cmd.nav = &BotNavData[ i ]; break; } } if ( cmd.nav && cmd.nav->mesh && cmd.nav->cache && cmd.nav->query ) { cmd.enabled = true; Cvar_Set( "r_debugSurface", "1" ); } } else if ( !Q_stricmp( arg, "disable" ) ) { cmd.enabled = false; Cvar_Set( "r_debugSurface", "0" ); } else if ( !Q_stricmp( arg, "save" ) ) { if ( !cmd.enabled ) { return; } BotSaveOffMeshConnections( cmd.nav ); } else { Com_Printf( "%s", usage ); } } void Cmd_AddConnection( void ) { const char usage[] = "Usage: addcon start <dir> (radius)\n" " addcon end\n"; char *arg = NULL; int argc = Cmd_Argc(); if ( argc < 2 ) { Com_Printf( "%s", usage ); return; } arg = Cmd_Argv( 1 ); if ( !Q_stricmp( arg, "start" ) ) { if ( !cmd.enabled ) { return; } if ( argc < 3 ) { Com_Printf( "%s", usage ); return; } arg = Cmd_Argv( 2 ); if ( !Q_stricmp( arg, "oneway" ) ) { cmd.pc.dir = 0; } else if ( !Q_stricmp( arg, "twoway" ) ) { cmd.pc.dir = 1; } else { Com_Printf( "Invalid argument for direction, specify oneway or twoway\n" ); return; } if ( GetPointPointedTo( cmd.nav, cmd.pc.start ) ) { cmd.pc.area = DT_TILECACHE_WALKABLE_AREA; cmd.pc.flag = POLYFLAGS_WALK; cmd.pc.userid = 0; if ( argc == 4 ) { cmd.pc.radius = MAX( atoi( Cmd_Argv( 3 ) ), 10 ); } else { cmd.pc.radius = connectionSize; } cmd.offBegin = true; } } else if ( !Q_stricmp( arg, "end" ) ) { if ( !cmd.enabled ) { return; } if ( !cmd.offBegin ) { return; } if ( GetPointPointedTo( cmd.nav, cmd.pc.end ) ) { cmd.nav->process.con.addConnection( cmd.pc ); rBounds box; box.addPoint( cmd.pc.start ); box.addPoint( cmd.pc.end ); box.mins[ 1 ] -= 10; box.maxs[ 1 ] += 10; // rebuild affected tiles dtCompressedTileRef refs[ 32 ]; int tc = 0; cmd.nav->cache->queryTiles( box.mins, box.maxs, refs, &tc, 32 ); for ( int k = 0; k < tc; k++ ) { cmd.nav->cache->buildNavMeshTile( refs[ k ], cmd.nav->mesh ); } cmd.offBegin = false; } } else { Com_Printf( "%s", usage ); } } static void adjustConnectionSize( int dir ) { int argc = Cmd_Argc(); int adjust = 5; int newConnectionSize; if ( argc > 1 ) { adjust = atoi( Cmd_Argv( 1 ) ); adjust = MIN( adjust, 20 ); adjust = MAX( adjust, 1 ); } newConnectionSize = connectionSize + dir * adjust; newConnectionSize = MIN( newConnectionSize, 100 ); newConnectionSize = MAX( newConnectionSize, 20 ); if ( newConnectionSize != connectionSize ) { connectionSize = newConnectionSize; Com_Printf( "Default connection size = %d\n", connectionSize ); } } void Cmd_ConnectionSizeUp( void ) { return adjustConnectionSize( 1 ); } void Cmd_ConnectionSizeDown( void ) { return adjustConnectionSize( -1 ); } void NavEditInit( void ) { #ifndef DEDICATED memset( &cmd, 0, sizeof( cmd ) ); Cvar_Set( "r_debugSurface", "0" ); Cmd_AddCommand( "navedit", Cmd_NavEdit ); Cmd_AddCommand( "addcon", Cmd_AddConnection ); Cmd_AddCommand( "conSizeUp", Cmd_ConnectionSizeUp ); Cmd_AddCommand( "conSizeDown", Cmd_ConnectionSizeDown ); #endif } void NavEditShutdown( void ) { #ifndef DEDICATED Cmd_RemoveCommand( "navedit" ); Cmd_RemoveCommand( "addcon" ); Cmd_RemoveCommand( "conSizeUp" ); Cmd_RemoveCommand( "conSizeDown" ); #endif }
/* =========================================================================== Daemon GPL Source Code Copyright (C) 2012 Unvanquished Developers This file is part of the Daemon GPL Source Code (Daemon Source Code). Daemon Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Daemon Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Daemon Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ extern "C" { #include "../client/client.h" } #include "../../libs/detour/DetourDebugDraw.h" #include "../../libs/detour/DebugDraw.h" #include "bot_navdraw.h" #include "nav.h" #define DEFAULT_CONNECTION_SIZE 50 static int connectionSize = DEFAULT_CONNECTION_SIZE; bool GetPointPointedTo( NavData_t *nav, rVec &p ) { qVec forward; qVec end; rVec extents; rVec pos; trace_t trace; dtPolyRef nearRef; VectorSet( extents, 640, 96, 640 ); AngleVectors( cl.snap.ps.viewangles, forward, NULL, NULL ); VectorMA( cl.snap.ps.origin, 8096, forward, end ); CM_BoxTrace( &trace, cl.snap.ps.origin, end, NULL, NULL, 0, CONTENTS_SOLID | CONTENTS_PLAYERCLIP, TT_AABB ); pos = qVec( trace.endpos ); if ( dtStatusFailed( nav->query->findNearestPoly( pos, extents, &nav->filter, &nearRef, p ) ) ) { return false; } return true; } static struct { bool enabled; bool offBegin; bool shownodes; bool showportals; OffMeshConnection pc; rVec start; bool validPathStart; NavData_t *nav; } cmd; void BotDrawNavEdit( DebugDrawQuake *dd ) { rVec p; if ( cmd.enabled && GetPointPointedTo( cmd.nav, p ) ) { unsigned int col = duRGBA( 255, 255, 255, 220 ); dd->begin( DU_DRAW_LINES, 2.0f ); duAppendCircle( dd, p[ 0 ], p[ 1 ], p[ 2 ], connectionSize, col ); if ( cmd.offBegin ) { duAppendArc( dd, cmd.pc.start[ 0 ], cmd.pc.start[ 1 ], cmd.pc.start[ 2 ], p[ 0 ], p[ 1 ], p[ 2 ], 0.25f, 0.6f, 0.6f, col ); duAppendCircle( dd, cmd.pc.start[ 0 ], cmd.pc.start[ 1 ], cmd.pc.start[ 2 ], connectionSize, col ); } dd->end(); } } void DrawPath( Bot_t *bot, DebugDrawQuake &dd ) { dd.depthMask(false); const unsigned int spathCol = duRGBA(128,128,128,255); dd.begin(DU_DRAW_LINES, 3.0f); dd.vertex( bot->corridor.getPos(), spathCol ); for (int i = 0; i < bot->numCorners; ++i) dd.vertex(bot->cornerVerts[i*3], bot->cornerVerts[i*3+1]+5.0f, bot->cornerVerts[i*3+2], spathCol); if ( bot->numCorners < MAX_CORNERS - 1 ) { if ( bot->numCorners % 2 != 0 ) { dd.vertex( &bot->cornerVerts[ ( bot->numCorners - 1 ) * 3 ], spathCol ); } dd.vertex( bot->corridor.getTarget(), spathCol ); } dd.end(); dd.depthMask(true); } extern "C" void BotDebugDrawMesh( BotDebugInterface_t *in ) { static DebugDrawQuake dd; dd.init( in ); if ( !cmd.enabled ) { return; } if ( !cmd.nav ) { return; } if ( !cmd.nav->mesh || !cmd.nav->query ) { return; } if ( cmd.shownodes ) { duDebugDrawNavMeshNodes( &dd, *cmd.nav->query ); } if ( cmd.showportals ) { duDebugDrawNavMeshPortals( &dd, *cmd.nav->mesh ); } duDebugDrawNavMeshWithClosedList(&dd, *cmd.nav->mesh, *cmd.nav->query, DU_DRAWNAVMESH_OFFMESHCONS | DU_DRAWNAVMESH_CLOSEDLIST); BotDrawNavEdit( &dd ); for ( int i = 0; i < MAX_CLIENTS; i++ ) { Bot_t *bot = &agents[ i ]; if ( bot->nav == cmd.nav ) { DrawPath( bot, dd ); } } } void Cmd_NavEdit( void ) { int argc = Cmd_Argc(); char *arg = NULL; const char usage[] = "Usage: navedit enable/disable/save <navmesh>\n"; if ( !Cvar_VariableIntegerValue( "sv_cheats" ) ) { Com_Printf( "navedit only available in local devmap\n" ); return; } if ( argc < 2 ) { Com_Printf( "%s", usage ); return; } arg = Cmd_Argv( 1 ); if ( !Q_stricmp( arg, "enable" ) ) { if ( argc < 3 ) { Com_Printf( "%s", usage ); return; } arg = Cmd_Argv( 2 ); for ( int i = 0; i < numNavData; i++ ) { if ( !Q_stricmp( BotNavData[ i ].name, arg ) ) { cmd.nav = &BotNavData[ i ]; break; } } if ( cmd.nav && cmd.nav->mesh && cmd.nav->cache && cmd.nav->query ) { cmd.enabled = true; Cvar_Set( "r_debugSurface", "1" ); } } else if ( !Q_stricmp( arg, "disable" ) ) { cmd.enabled = false; Cvar_Set( "r_debugSurface", "0" ); } else if ( !Q_stricmp( arg, "save" ) ) { if ( !cmd.enabled ) { return; } BotSaveOffMeshConnections( cmd.nav ); } else { Com_Printf( "%s", usage ); } } void Cmd_AddConnection( void ) { const char usage[] = "Usage: addcon start <dir> (radius)\n" " addcon end\n"; char *arg = NULL; int argc = Cmd_Argc(); if ( argc < 2 ) { Com_Printf( "%s", usage ); return; } arg = Cmd_Argv( 1 ); if ( !Q_stricmp( arg, "start" ) ) { if ( !cmd.enabled ) { return; } if ( argc < 3 ) { Com_Printf( "%s", usage ); return; } arg = Cmd_Argv( 2 ); if ( !Q_stricmp( arg, "oneway" ) ) { cmd.pc.dir = 0; } else if ( !Q_stricmp( arg, "twoway" ) ) { cmd.pc.dir = 1; } else { Com_Printf( "Invalid argument for direction, specify oneway or twoway\n" ); return; } if ( GetPointPointedTo( cmd.nav, cmd.pc.start ) ) { cmd.pc.area = DT_TILECACHE_WALKABLE_AREA; cmd.pc.flag = POLYFLAGS_WALK; cmd.pc.userid = 0; if ( argc == 4 ) { cmd.pc.radius = MAX( atoi( Cmd_Argv( 3 ) ), 10 ); } else { cmd.pc.radius = connectionSize; } cmd.offBegin = true; } } else if ( !Q_stricmp( arg, "end" ) ) { if ( !cmd.enabled ) { return; } if ( !cmd.offBegin ) { return; } if ( GetPointPointedTo( cmd.nav, cmd.pc.end ) ) { cmd.nav->process.con.addConnection( cmd.pc ); rBounds box; box.addPoint( cmd.pc.start ); box.addPoint( cmd.pc.end ); box.mins[ 1 ] -= 10; box.maxs[ 1 ] += 10; // rebuild affected tiles dtCompressedTileRef refs[ 32 ]; int tc = 0; cmd.nav->cache->queryTiles( box.mins, box.maxs, refs, &tc, 32 ); for ( int k = 0; k < tc; k++ ) { cmd.nav->cache->buildNavMeshTile( refs[ k ], cmd.nav->mesh ); } cmd.offBegin = false; } } else { Com_Printf( "%s", usage ); } } static void adjustConnectionSize( int dir ) { int argc = Cmd_Argc(); int adjust = 5; int newConnectionSize; if ( argc > 1 ) { adjust = atoi( Cmd_Argv( 1 ) ); adjust = MIN( adjust, 20 ); adjust = MAX( adjust, 1 ); } newConnectionSize = connectionSize + dir * adjust; newConnectionSize = MIN( newConnectionSize, 100 ); newConnectionSize = MAX( newConnectionSize, 20 ); if ( newConnectionSize != connectionSize ) { connectionSize = newConnectionSize; Com_Printf( "Default connection size = %d\n", connectionSize ); } } void Cmd_ConnectionSizeUp( void ) { return adjustConnectionSize( 1 ); } void Cmd_ConnectionSizeDown( void ) { return adjustConnectionSize( -1 ); } void Cmd_NavTest( void ) { const char usage[] = "Usage: navtest shownodes/hidenodes/showportals/hideportals/startpath/endpath\n"; char *arg = NULL; int argc = Cmd_Argc(); if ( !cmd.enabled ) { Com_Printf( "%s", "Can't test navmesh without enabling navedit" ); return; } if ( argc < 2 ) { Com_Printf( "%s", usage ); return; } arg = Cmd_Argv( 1 ); if ( !Q_stricmp( arg, "shownodes" ) ) { cmd.shownodes = true; } else if ( !Q_stricmp( arg, "hidenodes" ) ) { cmd.shownodes = false; } else if ( !Q_stricmp( arg, "showportals" ) ) { cmd.showportals = true; } else if ( !Q_stricmp( arg, "hideportals" ) ) { cmd.showportals = false; } else if ( !Q_stricmp( arg, "startpath" ) ) { if ( GetPointPointedTo( cmd.nav, cmd.start ) ) { cmd.validPathStart = true; } else { cmd.validPathStart = false; } } else if ( !Q_stricmp( arg, "endpath" ) ) { rVec end; if ( GetPointPointedTo( cmd.nav, end ) && cmd.validPathStart ) { dtPolyRef startRef; dtPolyRef endRef; const int maxPath = 512; int npath; dtPolyRef path[ maxPath ]; rVec nearPoint; rVec extents( 300, 300, 300 ); cmd.nav->query->findNearestPoly( cmd.start, extents, &cmd.nav->filter, &startRef, nearPoint ); cmd.nav->query->findNearestPoly( end, extents, &cmd.nav->filter, &endRef, nearPoint ); cmd.nav->query->findPath( startRef, endRef, cmd.start, end, &cmd.nav->filter, path, &npath, maxPath ); } } else { Com_Printf( "%s", usage ); } } void NavEditInit( void ) { #ifndef DEDICATED memset( &cmd, 0, sizeof( cmd ) ); Cvar_Set( "r_debugSurface", "0" ); Cmd_AddCommand( "navedit", Cmd_NavEdit ); Cmd_AddCommand( "addcon", Cmd_AddConnection ); Cmd_AddCommand( "conSizeUp", Cmd_ConnectionSizeUp ); Cmd_AddCommand( "conSizeDown", Cmd_ConnectionSizeDown ); Cmd_AddCommand( "navtest", Cmd_NavTest ); #endif } void NavEditShutdown( void ) { #ifndef DEDICATED Cmd_RemoveCommand( "navedit" ); Cmd_RemoveCommand( "addcon" ); Cmd_RemoveCommand( "conSizeUp" ); Cmd_RemoveCommand( "conSizeDown" ); Cmd_RemoveCommand( "navtest" ); #endif }
Add a navmesh testing command
Add a navmesh testing command
C++
bsd-3-clause
DaemonEngine/Daemon,DaemonEngine/Daemon,DaemonEngine/Daemon,DaemonEngine/Daemon
241362fcdf35fccc46ec2db262745fa45a0d54c9
src/tests/sampling.cpp
src/tests/sampling.cpp
#include "tests/gtest/gtest.h" #include <stdint.h> #include <algorithm> #include "pbrt.h" #include "sampling.h" #include "lowdiscrepancy.h" TEST(LowDiscrepancy, RadicalInverse) { for (int a = 0; a < 1024; ++a) { EXPECT_EQ(ReverseBits32(a) * 2.3283064365386963e-10f, RadicalInverse(0, a)); } } TEST(LowDiscrepancy, GeneratorMatrix) { uint32_t C[32]; // Identity matrix, column-wise for (int i = 0; i < 32; ++i) C[i] = 1 << i; for (int a = 0; a < 128; ++a) { // Make sure identity generator matrix matches van der Corput EXPECT_EQ(a, MultiplyGenerator(C, a)); EXPECT_EQ(RadicalInverse(0, a), ReverseBits32(MultiplyGenerator(C, a)) * 2.3283064365386963e-10f); } for (int a = 0; a < 16; ++a) { EXPECT_EQ(ReverseBits32(a), ReverseMultiplyGenerator(C, a)); EXPECT_EQ(RadicalInverse(0, a), ReverseMultiplyGenerator(C, a) * 2.3283064365386963e-10f); EXPECT_EQ(RadicalInverse(0, a), SampleGeneratorMatrix(C, a)); } } TEST(LowDiscrepancy, GrayCodeSample) { uint32_t C[32]; // Identity matrix, column-wise for (int i = 0; i < 32; ++i) C[i] = 1 << i; std::vector<Float> v(64, (Float)0); GrayCodeSample(C, v.size(), 0, &v[0]); for (int a = 0; a < (int)v.size(); ++a) { Float u = ReverseMultiplyGenerator(C, a) * 2.3283064365386963e-10f; EXPECT_NE(v.end(), std::find(v.begin(), v.end(), u)); } }
#include "tests/gtest/gtest.h" #include <stdint.h> #include <algorithm> #include "pbrt.h" #include "sampling.h" #include "lowdiscrepancy.h" #include "samplers/maxmin.h" #include "samplers/sobol.h" #include "samplers/zerotwosequence.h" TEST(LowDiscrepancy, RadicalInverse) { for (int a = 0; a < 1024; ++a) { EXPECT_EQ(ReverseBits32(a) * 2.3283064365386963e-10f, RadicalInverse(0, a)); } } TEST(LowDiscrepancy, GeneratorMatrix) { uint32_t C[32]; // Identity matrix, column-wise for (int i = 0; i < 32; ++i) C[i] = 1 << i; for (int a = 0; a < 128; ++a) { // Make sure identity generator matrix matches van der Corput EXPECT_EQ(a, MultiplyGenerator(C, a)); EXPECT_EQ(RadicalInverse(0, a), ReverseBits32(MultiplyGenerator(C, a)) * 2.3283064365386963e-10f); } for (int a = 0; a < 16; ++a) { EXPECT_EQ(ReverseBits32(a), ReverseMultiplyGenerator(C, a)); EXPECT_EQ(RadicalInverse(0, a), ReverseMultiplyGenerator(C, a) * 2.3283064365386963e-10f); EXPECT_EQ(RadicalInverse(0, a), SampleGeneratorMatrix(C, a)); } } TEST(LowDiscrepancy, GrayCodeSample) { uint32_t C[32]; // Identity matrix, column-wise for (int i = 0; i < 32; ++i) C[i] = 1 << i; std::vector<Float> v(64, (Float)0); GrayCodeSample(C, v.size(), 0, &v[0]); for (int a = 0; a < (int)v.size(); ++a) { Float u = ReverseMultiplyGenerator(C, a) * 2.3283064365386963e-10f; EXPECT_NE(v.end(), std::find(v.begin(), v.end(), u)); } } // Make sure samplers that are supposed to generate a single sample in // each of the elementary intervals actually do so. // TODO: check Halton (where the elementary intervals are (2^i, 3^j)). TEST(LowDiscrepancy, ElementaryIntervals) { auto checkSampler = [](const char *name, std::unique_ptr<Sampler> sampler, int logSamples) { // Get all of the samples for a pixel. sampler->StartPixel(Point2i(0, 0)); std::vector<Point2f> samples; do { samples.push_back(sampler->Get2D()); } while (sampler->StartNextSample()); for (int i = 0; i <= logSamples; ++i) { // Check one set of elementary intervals: number of intervals // in each dimension. int nx = 1 << i, ny = 1 << (logSamples - i); std::vector<int> count(1 << logSamples, 0); for (const Point2f &s : samples) { // Map the sample to an interval Float x = nx * s.x, y = ny * s.y; EXPECT_GE(x, 0); EXPECT_LT(x, nx); EXPECT_GE(y, 0); EXPECT_LT(y, ny); int index = (int)std::floor(y) * nx + (int)std::floor(x); EXPECT_GE(index, 0); EXPECT_LT(index, count.size()); // This should be the first time a sample has landed in its // interval. EXPECT_EQ(0, count[index]) << "Sampler " << name; ++count[index]; } } }; for (int logSamples = 2; logSamples <= 10; ++logSamples) { checkSampler("MaxMinDistSampler", std::unique_ptr<Sampler>( new MaxMinDistSampler(1 << logSamples, 2)), logSamples); checkSampler("ZeroTwoSequenceSampler", std::unique_ptr<Sampler>( new ZeroTwoSequenceSampler(1 << logSamples, 2)), logSamples); checkSampler("Sobol", std::unique_ptr<Sampler>( new SobolSampler(1 << logSamples, Bounds2i(Point2i(0, 0), Point2i(10, 10)))), logSamples); } } TEST(MaxMinDist, MinDist) { // We use a silly O(n^2) distance check below, so don't go all the way up // to 2^16 samples. for (int logSamples = 2; logSamples <= 10; ++logSamples) { // Store a pixel's worth of samples in the vector s. MaxMinDistSampler mm(1 << logSamples, 2); mm.StartPixel(Point2i(0, 0)); std::vector<Point2f> s; do { s.push_back(mm.Get2D()); } while (mm.StartNextSample()); // Distance with toroidal topology auto dist = [](const Point2f &p0, const Point2f &p1) { Vector2f d = Abs(p1 - p0); if (d.x > 0.5) d.x = 1. - d.x; if (d.y > 0.5) d.y = 1. - d.y; return d.Length(); }; Float minDist = Infinity; for (size_t i = 0; i < s.size(); ++i) { for (size_t j = 0; j < s.size(); ++j) { if (i == j) continue; minDist = std::min(minDist, dist(s[i], s[j])); } } // Expected minimum distances from Gruenschloss et al.'s paper. Float expectedMinDist[17] = { 0., /* not checked */ 0., /* not checked */ 0.35355, 0.35355, 0.22534, 0.16829, 0.11267, 0.07812, 0.05644, 0.03906, 0.02816, 0.01953, 0.01408, 0.00975, 0.00704, 0.00486, 0.00352, }; // Increase the tolerance by a small slop factor. EXPECT_GT(minDist, 0.99 * expectedMinDist[logSamples]); } }
Add some Sampler-related unit tests.
Add some Sampler-related unit tests.
C++
bsd-2-clause
mmp/pbrt-v3,mcanthony/pbrt-v3,bssrdf/pbrt-v3,ambakshi/pbrt-v3,Vertexwahn/pbrt-v3,nispaur/pbrt-v3,shihchinw/pbrt-v3,nyue/pbrt-v3,shihchinw/pbrt-v3,ambakshi/pbrt-v3,bssrdf/pbrt-v3,mmp/pbrt-v3,ambakshi/pbrt-v3,nispaur/pbrt-v3,mmp/pbrt-v3,shihchinw/pbrt-v3,mwkm/pbrt-v3,Vertexwahn/pbrt-v3,mcanthony/pbrt-v3,mwkm/pbrt-v3,nyue/pbrt-v3,mcanthony/pbrt-v3,nyue/pbrt-v3,nispaur/pbrt-v3,shihchinw/pbrt-v3,mmp/pbrt-v3,nispaur/pbrt-v3,Vertexwahn/pbrt-v3,bssrdf/pbrt-v3,nyue/pbrt-v3
777b38f46c113d866fd3ca57b5bddc6c08ab7d95
src/istio/utils/attribute_names.cc
src/istio/utils/attribute_names.cc
/* Copyright 2018 Istio 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 "include/istio/utils/attribute_names.h" namespace istio { namespace utils { // Define attribute names const char AttributeName::kSourceUser[] = "source.user"; const char AttributeName::kSourcePrincipal[] = "source.principal"; const char AttributeName::kRequestHeaders[] = "request.headers"; const char AttributeName::kRequestHost[] = "request.host"; const char AttributeName::kRequestMethod[] = "request.method"; const char AttributeName::kRequestPath[] = "request.path"; const char AttributeName::kRequestReferer[] = "request.referer"; const char AttributeName::kRequestScheme[] = "request.scheme"; const char AttributeName::kRequestBodySize[] = "request.size"; const char AttributeName::kRequestTotalSize[] = "request.total_size"; const char AttributeName::kRequestTime[] = "request.time"; const char AttributeName::kRequestUserAgent[] = "request.useragent"; const char AttributeName::kRequestApiKey[] = "request.api_key"; const char AttributeName::kResponseCode[] = "response.code"; const char AttributeName::kResponseDuration[] = "response.duration"; const char AttributeName::kResponseHeaders[] = "response.headers"; const char AttributeName::kResponseBodySize[] = "response.size"; const char AttributeName::kResponseTotalSize[] = "response.total_size"; const char AttributeName::kResponseTime[] = "response.time"; // TCP attributes // Downstream tcp connection: source ip/port. const char AttributeName::kSourceIp[] = "source.ip"; const char AttributeName::kSourcePort[] = "source.port"; // Upstream tcp connection: destination ip/port. const char AttributeName::kDestinationIp[] = "destination.ip"; const char AttributeName::kDestinationPort[] = "destination.port"; const char AttributeName::kDestinationUID[] = "destination.uid"; const char AttributeName::kConnectionReceviedBytes[] = "connection.received.bytes"; const char AttributeName::kConnectionReceviedTotalBytes[] = "connection.received.bytes_total"; const char AttributeName::kConnectionSendBytes[] = "connection.sent.bytes"; const char AttributeName::kConnectionSendTotalBytes[] = "connection.sent.bytes_total"; const char AttributeName::kConnectionDuration[] = "connection.duration"; const char AttributeName::kConnectionMtls[] = "connection.mtls"; const char AttributeName::kConnectionRequestedServerName[] = "connection.requested_server_name"; // Downstream TCP connection id. const char AttributeName::kConnectionId[] = "connection.id"; const char AttributeName::kConnectionEvent[] = "connection.event"; // Context attributes const char AttributeName::kContextProtocol[] = "context.protocol"; const char AttributeName::kContextTime[] = "context.time"; // Check error code and message. const char AttributeName::kCheckErrorCode[] = "check.error_code"; const char AttributeName::kCheckErrorMessage[] = "check.error_message"; // Check and Quota cache hit const char AttributeName::kCheckCacheHit[] = "check.cache_hit"; const char AttributeName::kQuotaCacheHit[] = "quota.cache_hit"; // Authentication attributes const char AttributeName::kRequestAuthPrincipal[] = "request.auth.principal"; const char AttributeName::kRequestAuthAudiences[] = "request.auth.audiences"; const char AttributeName::kRequestAuthPresenter[] = "request.auth.presenter"; const char AttributeName::kRequestAuthClaims[] = "request.auth.claims"; const char AttributeName::kRequestAuthRawClaims[] = "request.auth.raw_claims"; const char AttributeName::kResponseGrpcStatus[] = "response.grpc_status"; const char AttributeName::kResponseGrpcMessage[] = "response.grpc_message"; } // namespace utils } // namespace istio
/* Copyright 2018 Istio 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 "include/istio/utils/attribute_names.h" namespace istio { namespace utils { // Define attribute names const char AttributeName::kSourceUser[] = "source.user"; const char AttributeName::kSourcePrincipal[] = "source.principal"; const char AttributeName::kRequestHeaders[] = "request.headers"; const char AttributeName::kRequestHost[] = "request.host"; const char AttributeName::kRequestMethod[] = "request.method"; const char AttributeName::kRequestPath[] = "request.path"; const char AttributeName::kRequestReferer[] = "request.referer"; const char AttributeName::kRequestScheme[] = "request.scheme"; const char AttributeName::kRequestBodySize[] = "request.size"; const char AttributeName::kRequestTotalSize[] = "request.total_size"; const char AttributeName::kRequestTime[] = "request.time"; const char AttributeName::kRequestUserAgent[] = "request.useragent"; const char AttributeName::kRequestApiKey[] = "request.api_key"; const char AttributeName::kResponseCode[] = "response.code"; const char AttributeName::kResponseDuration[] = "response.duration"; const char AttributeName::kResponseHeaders[] = "response.headers"; const char AttributeName::kResponseBodySize[] = "response.size"; const char AttributeName::kResponseTotalSize[] = "response.total_size"; const char AttributeName::kResponseTime[] = "response.time"; // TCP attributes // Downstream tcp connection: source ip/port. const char AttributeName::kSourceIp[] = "source.ip"; const char AttributeName::kSourcePort[] = "source.port"; // Upstream tcp connection: destination ip/port. const char AttributeName::kDestinationIp[] = "destination.ip"; const char AttributeName::kDestinationPort[] = "destination.port"; const char AttributeName::kDestinationUID[] = "destination.uid"; const char AttributeName::kConnectionReceviedBytes[] = "connection.received.bytes"; const char AttributeName::kConnectionReceviedTotalBytes[] = "connection.received.bytes_total"; const char AttributeName::kConnectionSendBytes[] = "connection.sent.bytes"; const char AttributeName::kConnectionSendTotalBytes[] = "connection.sent.bytes_total"; const char AttributeName::kConnectionDuration[] = "connection.duration"; const char AttributeName::kConnectionMtls[] = "connection.mtls"; const char AttributeName::kConnectionRequestedServerName[] = "connection.requested_server_name"; // Downstream TCP connection id. const char AttributeName::kConnectionId[] = "connection.id"; const char AttributeName::kConnectionEvent[] = "connection.event"; // Context attributes const char AttributeName::kContextProtocol[] = "context.protocol"; const char AttributeName::kContextTime[] = "context.time"; // Check error code and message. const char AttributeName::kCheckErrorCode[] = "check.error_code"; const char AttributeName::kCheckErrorMessage[] = "check.error_message"; // Check and Quota cache hit const char AttributeName::kCheckCacheHit[] = "check.cache_hit"; const char AttributeName::kQuotaCacheHit[] = "quota.cache_hit"; // Authentication attributes const char AttributeName::kRequestAuthPrincipal[] = "request.auth.principal"; const char AttributeName::kRequestAuthAudiences[] = "request.auth.audiences"; const char AttributeName::kRequestAuthPresenter[] = "request.auth.presenter"; const char AttributeName::kRequestAuthClaims[] = "request.auth.claims"; const char AttributeName::kRequestAuthRawClaims[] = "request.auth.raw_claims"; const char AttributeName::kResponseGrpcStatus[] = "response.grpc_status"; const char AttributeName::kResponseGrpcMessage[] = "response.grpc_message"; } // namespace utils } // namespace istio
fix format
fix format
C++
apache-2.0
lizan/proxy,lizan/proxy,lizan/proxy,istio/proxy,istio/proxy,lizan/proxy,istio/proxy,istio/proxy
1e697b48e9f5aee57a784d6b817b9cd1a3288457
src/lib/WP42DefineColumnsGroup.cpp
src/lib/WP42DefineColumnsGroup.cpp
/* libwpd * Copyright (C) 2006 Fridrich Strba ([email protected]) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * For further information visit http://libwpd.sourceforge.net */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #include "WP42DefineColumnsGroup.h" #include "WP42FileStructure.h" #include "libwpd_internal.h" WP42DefineColumnsGroup::WP42DefineColumnsGroup(WPXInputStream *input, WPXEncryption *encryption, uint8_t group) : WP42MultiByteFunctionGroup(group), m_groupId(group), m_numColumns(0), m_isParallel(false), m_columnsDefinition() { _read(input, encryption); } WP42DefineColumnsGroup::~WP42DefineColumnsGroup() { } void WP42DefineColumnsGroup::_readContents(WPXInputStream *input, WPXEncryption *encryption) { uint8_t maxNumColumns = 0; switch (m_groupId) { case WP42_DEFINE_COLUMNS_OLD_GROUP: input->seek(11, WPX_SEEK_CUR); maxNumColumns = 5; break; case WP42_DEFINE_COLUMNS_NEW_GROUP: input->seek(49, WPX_SEEK_CUR); maxNumColumns = 24; break; default: return; } uint8_t tmpNumColumns = readU8(input, encryption); m_numColumns = tmpNumColumns & 0x7F; if (m_numColumns > maxNumColumns) m_numColumns = maxNumColumns; m_isParallel = ((tmpNumColumns & 0x80) != 0); for (unsigned i = 0; i<2*m_numColumns; i++) m_columnsDefinition.push_back(readU8(input, encryption)); } void WP42DefineColumnsGroup::parse(WP42Listener *listener) { WPD_DEBUG_MSG(("WordPerfect: handling an DefineColumns group\n")); }
/* libwpd * Copyright (C) 2006 Fridrich Strba ([email protected]) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * For further information visit http://libwpd.sourceforge.net */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #include "WP42DefineColumnsGroup.h" #include "WP42FileStructure.h" #include "libwpd_internal.h" WP42DefineColumnsGroup::WP42DefineColumnsGroup(WPXInputStream *input, WPXEncryption *encryption, uint8_t group) : WP42MultiByteFunctionGroup(group), m_groupId(group), m_numColumns(0), m_isParallel(false), m_columnsDefinition() { _read(input, encryption); } WP42DefineColumnsGroup::~WP42DefineColumnsGroup() { } void WP42DefineColumnsGroup::_readContents(WPXInputStream *input, WPXEncryption *encryption) { uint8_t maxNumColumns = 0; switch (m_groupId) { case WP42_DEFINE_COLUMNS_OLD_GROUP: input->seek(11, WPX_SEEK_CUR); maxNumColumns = 5; break; case WP42_DEFINE_COLUMNS_NEW_GROUP: input->seek(49, WPX_SEEK_CUR); maxNumColumns = 24; break; default: return; } uint8_t tmpNumColumns = readU8(input, encryption); m_numColumns = tmpNumColumns & 0x7F; if (m_numColumns > maxNumColumns) m_numColumns = maxNumColumns; m_isParallel = ((tmpNumColumns & 0x80) != 0); for (uint8_t i = 0; i<2*m_numColumns; i++) m_columnsDefinition.push_back(readU8(input, encryption)); } void WP42DefineColumnsGroup::parse(WP42Listener *listener) { WPD_DEBUG_MSG(("WordPerfect: handling an DefineColumns group\n")); }
Fix unsigned/signed + integer promotion issue
Fix unsigned/signed + integer promotion issue
C++
lgpl-2.1
cpjreynolds/libwpd,Distrotech/librevenge,cpjreynolds/libwpd,Distrotech/libpwd,Distrotech/libpwd,Distrotech/libpwd,cpjreynolds/libwpd,Distrotech/librevenge,Distrotech/librevenge,Distrotech/librevenge,Distrotech/librevenge,Distrotech/libpwd
58e837c3d9a5f76b926468048ef4894ba39e2e70
src/libcsg/modules/io/groreader.cc
src/libcsg/modules/io/groreader.cc
/* * Copyright 2009-2013 The VOTCA Development Team (http://www.votca.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 <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include <votca/tools/getline.h> #include <boost/algorithm/string.hpp> #include "groreader.h" namespace votca { namespace csg { bool GROReader::ReadTopology(string file, Topology &top) { _topology = true; top.Cleanup(); _fl.open(file.c_str()); if(!_fl.is_open()) throw std::ios_base::failure("Error on open topology file: " + file); NextFrame(top); _fl.close(); return true; } bool GROReader::Open(const string &file) { _fl.open(file.c_str()); if(!_fl.is_open()) throw std::ios_base::failure("Error on open trajectory file: " + file); return true; } void GROReader::Close() { _fl.close(); } bool GROReader::FirstFrame(Topology &top) { _topology = false; NextFrame(top); return true; } bool GROReader::NextFrame(Topology &top) { string tmp; getline(_fl, tmp);//title getline(_fl, tmp);//number atoms int natoms = atoi(tmp.c_str()); if(!_topology && natoms != top.BeadCount()) throw std::runtime_error("number of beads in topology and trajectory differ"); for(int i=0;i<natoms; i++) { string line; getline(_fl, line); string resNum,resName, atName, x,y,z; try { resNum= string(line,0,5); // %5i resName = string(line,5,5); //%5s atName = string(line,10,5); // %5s //atNum= string(line,15,5); // %5i not needed x = string(line,20,8); // %8.3f y = string(line,28,8); // %8.3f z = string(line,36,8); // %8.3f } catch (std::out_of_range& err) { throw std::runtime_error("Misformated gro file"); } boost::algorithm::trim(atName); boost::algorithm::trim(resName); boost::algorithm::trim(resNum); boost::algorithm::trim(x); boost::algorithm::trim(y); boost::algorithm::trim(z); string vx,vy,vz; bool hasVel=true; try { vx = string(line,44,8); // %8.4f vy = string(line,52,8); // %8.4f vz = string(line,60,8); // %8.4f } catch (std::out_of_range& err) { hasVel=false; } Bead *b; if(_topology){ int resnr = boost::lexical_cast<int>(resNum); if(resnr >= top.ResidueCount()) { if (top.ResidueCount()==0) //gro resnr start with 1 but VOTCA starts with 0 top.CreateResidue("ZERO"); // create 0 res, to allow to keep gro numbering top.CreateResidue(resName); } //this is not correct, but still better than no type at all! BeadType *type = top.GetOrCreateBeadType(atName); b = top.CreateBead(1, atName, type, resnr, 1., 0.); } else { b = top.getBead(i); } b->setPos(vec( boost::lexical_cast<double>(x), boost::lexical_cast<double>(y), boost::lexical_cast<double>(z) )); if (hasVel) { boost::algorithm::trim(vx); boost::algorithm::trim(vy); boost::algorithm::trim(vz); b->setVel(vec( boost::lexical_cast<double>(vx), boost::lexical_cast<double>(vy), boost::lexical_cast<double>(vz) )); } } getline(_fl, tmp); //read box line if(_fl.eof()) throw std::runtime_error("unexpected end of file in poly file, when boxline"); Tokenizer tok(tmp, " "); vector<double> fields; tok.ConvertToVector<double>(fields); matrix box; if ( fields.size() == 3 ) { box.ZeroMatrix(); for (int i=0;i<3;i++) box[i][i] = fields[i]; } else if ( fields.size() == 9 ) { box[0][0]= fields[0]; box[1][1]= fields[1]; box[2][2]= fields[2]; box[1][0]= fields[3]; box[2][0]= fields[4]; box[0][1]= fields[5]; box[2][1]= fields[6]; box[0][2]= fields[7]; box[1][2]= fields[8]; } else { throw std::runtime_error("Error while reading box (last) line"); } top.setBox(box); _fl.close(); cout << "WARNING: topology created from .gro file, masses and charges are wrong!\n"; return true; } }}
/* * Copyright 2009-2013 The VOTCA Development Team (http://www.votca.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 <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include <votca/tools/getline.h> #include <boost/algorithm/string.hpp> #include "groreader.h" namespace votca { namespace csg { bool GROReader::ReadTopology(string file, Topology &top) { _topology = true; top.Cleanup(); _fl.open(file.c_str()); if(!_fl.is_open()) throw std::ios_base::failure("Error on open topology file: " + file); NextFrame(top); _fl.close(); return true; } bool GROReader::Open(const string &file) { _fl.open(file.c_str()); if(!_fl.is_open()) throw std::ios_base::failure("Error on open trajectory file: " + file); return true; } void GROReader::Close() { _fl.close(); } bool GROReader::FirstFrame(Topology &top) { _topology = false; NextFrame(top); return true; } bool GROReader::NextFrame(Topology &top) { string tmp; getline(_fl, tmp);//title if (_fl.eof()) { return !_fl.eof(); } getline(_fl, tmp);//number atoms int natoms = atoi(tmp.c_str()); if(!_topology && natoms != top.BeadCount()) throw std::runtime_error("number of beads in topology and trajectory differ"); for(int i=0;i<natoms; i++) { string line; getline(_fl, line); string resNum,resName, atName, x,y,z; try { resNum= string(line,0,5); // %5i resName = string(line,5,5); //%5s atName = string(line,10,5); // %5s //atNum= string(line,15,5); // %5i not needed x = string(line,20,8); // %8.3f y = string(line,28,8); // %8.3f z = string(line,36,8); // %8.3f } catch (std::out_of_range& err) { throw std::runtime_error("Misformated gro file"); } boost::algorithm::trim(atName); boost::algorithm::trim(resName); boost::algorithm::trim(resNum); boost::algorithm::trim(x); boost::algorithm::trim(y); boost::algorithm::trim(z); string vx,vy,vz; bool hasVel=true; try { vx = string(line,44,8); // %8.4f vy = string(line,52,8); // %8.4f vz = string(line,60,8); // %8.4f } catch (std::out_of_range& err) { hasVel=false; } Bead *b; if(_topology){ int resnr = boost::lexical_cast<int>(resNum); if(resnr >= top.ResidueCount()) { if (top.ResidueCount()==0) //gro resnr start with 1 but VOTCA starts with 0 top.CreateResidue("ZERO"); // create 0 res, to allow to keep gro numbering top.CreateResidue(resName); } //this is not correct, but still better than no type at all! BeadType *type = top.GetOrCreateBeadType(atName); b = top.CreateBead(1, atName, type, resnr, 1., 0.); } else { b = top.getBead(i); } b->setPos(vec( boost::lexical_cast<double>(x), boost::lexical_cast<double>(y), boost::lexical_cast<double>(z) )); if (hasVel) { boost::algorithm::trim(vx); boost::algorithm::trim(vy); boost::algorithm::trim(vz); b->setVel(vec( boost::lexical_cast<double>(vx), boost::lexical_cast<double>(vy), boost::lexical_cast<double>(vz) )); } } getline(_fl, tmp); //read box line if(_fl.eof()) throw std::runtime_error("unexpected end of file in poly file, when boxline"); Tokenizer tok(tmp, " "); vector<double> fields; tok.ConvertToVector<double>(fields); matrix box; if ( fields.size() == 3 ) { box.ZeroMatrix(); for (int i=0;i<3;i++) box[i][i] = fields[i]; } else if ( fields.size() == 9 ) { box[0][0]= fields[0]; box[1][1]= fields[1]; box[2][2]= fields[2]; box[1][0]= fields[3]; box[2][0]= fields[4]; box[0][1]= fields[5]; box[2][1]= fields[6]; box[0][2]= fields[7]; box[1][2]= fields[8]; } else { throw std::runtime_error("Error while reading box (last) line"); } top.setBox(box); if (_topology) { cout << "WARNING: topology created from .gro file, masses and charges are wrong!\n"; } return !_fl.eof(); } }}
fix trajectory reading
groreader: fix trajectory reading
C++
apache-2.0
Pallavi-Banerjee21/votca.csg,vaidyanathanms/votca.csg,vaidyanathanms/votca.csg,Pallavi-Banerjee21/votca.csg,vaidyanathanms/votca.csg,vaidyanathanms/votca.csg,Pallavi-Banerjee21/votca.csg,vaidyanathanms/votca.csg,Pallavi-Banerjee21/votca.csg,Pallavi-Banerjee21/votca.csg,Pallavi-Banerjee21/votca.csg
57ef1ee8484046b56a08c98fb22a0d1827ac79e9
src/core/SkMallocPixelRef.cpp
src/core/SkMallocPixelRef.cpp
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkMallocPixelRef.h" #include "include/core/SkData.h" #include "include/core/SkImageInfo.h" #include "include/private/SkMalloc.h" static bool is_valid(const SkImageInfo& info) { if (info.width() < 0 || info.height() < 0 || (unsigned)info.colorType() > (unsigned)kLastEnum_SkColorType || (unsigned)info.alphaType() > (unsigned)kLastEnum_SkAlphaType) { return false; } return true; } sk_sp<SkPixelRef> SkMallocPixelRef::MakeAllocate(const SkImageInfo& info, size_t rowBytes) { if (rowBytes == 0) { rowBytes = info.minRowBytes(); // rowBytes can still be zero, if it overflowed (width * bytesPerPixel > size_t) // or if colortype is unknown } if (!is_valid(info) || !info.validRowBytes(rowBytes)) { return nullptr; } size_t size = info.computeByteSize(rowBytes); if (SkImageInfo::ByteSizeOverflowed(size)) { return nullptr; } #if defined(SK_BUILD_FOR_FUZZER) if (size > 100000) { return nullptr; } #endif void* addr = sk_calloc_canfail(size); if (nullptr == addr) { return nullptr; } struct PixelRef final : public SkPixelRef { PixelRef(int w, int h, void* s, size_t r) : SkPixelRef(w, h, s, r) {} ~PixelRef() override { sk_free(this->pixels()); } }; return sk_sp<SkPixelRef>(new PixelRef(info.width(), info.height(), addr, rowBytes)); } sk_sp<SkPixelRef> SkMallocPixelRef::MakeWithData(const SkImageInfo& info, size_t rowBytes, sk_sp<SkData> data) { SkASSERT(data != nullptr); if (!is_valid(info)) { return nullptr; } // TODO: what should we return if computeByteSize returns 0? // - the info was empty? // - we overflowed computing the size? if ((rowBytes < info.minRowBytes()) || (data->size() < info.computeByteSize(rowBytes))) { return nullptr; } struct PixelRef final : public SkPixelRef { sk_sp<SkData> fData; PixelRef(int w, int h, void* s, size_t r, sk_sp<SkData> d) : SkPixelRef(w, h, s, r), fData(std::move(d)) {} }; void* pixels = const_cast<void*>(data->data()); sk_sp<SkPixelRef> pr(new PixelRef(info.width(), info.height(), pixels, rowBytes, std::move(data))); pr->setImmutable(); // since we were created with (immutable) data return pr; }
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkMallocPixelRef.h" #include "include/core/SkData.h" #include "include/core/SkImageInfo.h" #include "include/private/SkMalloc.h" static bool is_valid(const SkImageInfo& info) { if (info.width() < 0 || info.height() < 0 || (unsigned)info.colorType() > (unsigned)kLastEnum_SkColorType || (unsigned)info.alphaType() > (unsigned)kLastEnum_SkAlphaType) { return false; } return true; } sk_sp<SkPixelRef> SkMallocPixelRef::MakeAllocate(const SkImageInfo& info, size_t rowBytes) { if (rowBytes == 0) { rowBytes = info.minRowBytes(); // rowBytes can still be zero, if it overflowed (width * bytesPerPixel > size_t) // or if colortype is unknown } if (!is_valid(info) || !info.validRowBytes(rowBytes)) { return nullptr; } size_t size = info.computeByteSize(rowBytes); if (SkImageInfo::ByteSizeOverflowed(size)) { return nullptr; } #if defined(SK_BUILD_FOR_FUZZER) if (size > 10000000) { return nullptr; } #endif void* addr = sk_calloc_canfail(size); if (nullptr == addr) { return nullptr; } struct PixelRef final : public SkPixelRef { PixelRef(int w, int h, void* s, size_t r) : SkPixelRef(w, h, s, r) {} ~PixelRef() override { sk_free(this->pixels()); } }; return sk_sp<SkPixelRef>(new PixelRef(info.width(), info.height(), addr, rowBytes)); } sk_sp<SkPixelRef> SkMallocPixelRef::MakeWithData(const SkImageInfo& info, size_t rowBytes, sk_sp<SkData> data) { SkASSERT(data != nullptr); if (!is_valid(info)) { return nullptr; } // TODO: what should we return if computeByteSize returns 0? // - the info was empty? // - we overflowed computing the size? if ((rowBytes < info.minRowBytes()) || (data->size() < info.computeByteSize(rowBytes))) { return nullptr; } struct PixelRef final : public SkPixelRef { sk_sp<SkData> fData; PixelRef(int w, int h, void* s, size_t r, sk_sp<SkData> d) : SkPixelRef(w, h, s, r), fData(std::move(d)) {} }; void* pixels = const_cast<void*>(data->data()); sk_sp<SkPixelRef> pr(new PixelRef(info.width(), info.height(), pixels, rowBytes, std::move(data))); pr->setImmutable(); // since we were created with (immutable) data return pr; }
Boost SkMallocPixelRef fuzzing limit
Boost SkMallocPixelRef fuzzing limit 100k was probably a bit too small, only allowing a ~150 x ~150 bitmap. 10m lets us get to ~1500 x ~1500 which is hopefully a better balance between reasonable and fuzzer performance. Change-Id: Ifde8cb28c89b648ed4af0c9b1ee081d87c755482 Bug: oss-fuzz:52328 Reviewed-on: https://skia-review.googlesource.com/c/skia/+/597476 Reviewed-by: Ben Wagner <[email protected]>
C++
bsd-3-clause
google/skia,google/skia,google/skia,google/skia,google/skia,google/skia,google/skia,google/skia,google/skia,google/skia
8410b18e42788580d89733ccc8ffbc886713c78c
src/core/grabber/src/main.cpp
src/core/grabber/src/main.cpp
#include "components_manager_killer.hpp" #include "constants.hpp" #include "dispatcher_utility.hpp" #include "filesystem_utility.hpp" #include "grabber/components_manager.hpp" #include "iokit_hid_device_open_checker_utility.hpp" #include "karabiner_version.h" #include "logger.hpp" #include "process_utility.hpp" #include "state_json_writer.hpp" #include <iostream> int main(int argc, const char* argv[]) { // // Initialize // auto scoped_dispatcher_manager = krbn::dispatcher_utility::initialize_dispatchers(); signal(SIGUSR1, SIG_IGN); signal(SIGUSR2, SIG_IGN); // // Check euid // (grabber is launched from LaunchDaemons (root) and LaunchAgents (user).) // bool root = (geteuid() == 0); // // Setup logger // if (root) { krbn::logger::set_async_rotating_logger("grabber", "/var/log/karabiner/grabber.log", 0755); } else { krbn::logger::set_async_rotating_logger("grabber_agent", krbn::constants::get_user_log_directory() + "/grabber_agent.log", 0700); } krbn::logger::get_logger()->info("version {0}", karabiner_version); // // Check another process // { bool another_process_running = false; if (root) { std::string pid_file_path = krbn::constants::get_pid_directory() + "/karabiner_grabber.pid"; another_process_running = !krbn::process_utility::lock_single_application(pid_file_path); } else { another_process_running = !krbn::process_utility::lock_single_application_with_user_pid_file("karabiner_grabber_agent.pid"); } if (another_process_running) { auto message = "Exit since another process is running."; krbn::logger::get_logger()->info(message); std::cerr << message << std::endl; return 1; } } // // Prepare state_json_writer // std::shared_ptr<krbn::state_json_writer> state_json_writer; if (root) { state_json_writer = std::make_shared<krbn::state_json_writer>( krbn::constants::get_grabber_state_json_file_path()); } // // Open IOHIDDevices in order to gain input monitoring permission. // (Both from LaunchDaemons and LaunchAgents) // if (!krbn::iokit_hid_device_open_checker_utility::run_checker()) { if (state_json_writer) { state_json_writer->set("hid_device_open_permitted", false); } if (root) { // We have to restart this process in order to reflect the input monitoring approval. return 0; } } else { if (state_json_writer) { state_json_writer->set("hid_device_open_permitted", true); } } // // Make socket directory. // if (root) { krbn::filesystem_utility::mkdir_tmp_directory(); unlink(krbn::constants::get_grabber_socket_file_path()); // Make console_user_server_socket_directory std::stringstream ss; ss << "rm -r '" << krbn::constants::get_console_user_server_socket_directory() << "'"; system(ss.str().c_str()); mkdir(krbn::constants::get_console_user_server_socket_directory(), 0755); chown(krbn::constants::get_console_user_server_socket_directory(), 0, 0); chmod(krbn::constants::get_console_user_server_socket_directory(), 0755); } // // Run components_manager // krbn::components_manager_killer::initialize_shared_components_manager_killer(); // We have to use raw pointer (not smart pointer) to delete it in `dispatch_async`. krbn::grabber::components_manager* components_manager = nullptr; if (auto killer = krbn::components_manager_killer::get_shared_components_manager_killer()) { killer->kill_called.connect([&components_manager] { dispatch_async(dispatch_get_main_queue(), ^{ { // Mark as main queue to avoid a deadlock in `pqrs::gcd::dispatch_sync_on_main_queue` in destructor. pqrs::gcd::scoped_running_on_main_queue_marker marker; if (components_manager) { delete components_manager; } } CFRunLoopStop(CFRunLoopGetCurrent()); }); }); } if (root) { components_manager = new krbn::grabber::components_manager(); components_manager->async_start(); } CFRunLoopRun(); krbn::components_manager_killer::terminate_shared_components_manager_killer(); state_json_writer = nullptr; krbn::logger::get_logger()->info("karabiner_grabber is terminated."); return 0; }
#include "constants.hpp" #include "dispatcher_utility.hpp" #include "filesystem_utility.hpp" #include "grabber/components_manager.hpp" #include "iokit_hid_device_open_checker_utility.hpp" #include "karabiner_version.h" #include "logger.hpp" #include "process_utility.hpp" #include "state_json_writer.hpp" #include <iostream> int main(int argc, const char* argv[]) { // // Initialize // auto scoped_dispatcher_manager = krbn::dispatcher_utility::initialize_dispatchers(); signal(SIGUSR1, SIG_IGN); signal(SIGUSR2, SIG_IGN); // // Check euid // (grabber is launched from LaunchDaemons (root) and LaunchAgents (user).) // bool root = (geteuid() == 0); // // Setup logger // if (root) { krbn::logger::set_async_rotating_logger("grabber", "/var/log/karabiner/grabber.log", 0755); } else { krbn::logger::set_async_rotating_logger("grabber_agent", krbn::constants::get_user_log_directory() + "/grabber_agent.log", 0700); } krbn::logger::get_logger()->info("version {0}", karabiner_version); // // Check another process // { bool another_process_running = false; if (root) { std::string pid_file_path = krbn::constants::get_pid_directory() + "/karabiner_grabber.pid"; another_process_running = !krbn::process_utility::lock_single_application(pid_file_path); } else { another_process_running = !krbn::process_utility::lock_single_application_with_user_pid_file("karabiner_grabber_agent.pid"); } if (another_process_running) { auto message = "Exit since another process is running."; krbn::logger::get_logger()->info(message); std::cerr << message << std::endl; return 1; } } // // Prepare state_json_writer // std::shared_ptr<krbn::state_json_writer> state_json_writer; if (root) { state_json_writer = std::make_shared<krbn::state_json_writer>( krbn::constants::get_grabber_state_json_file_path()); } // // Open IOHIDDevices in order to gain input monitoring permission. // (Both from LaunchDaemons and LaunchAgents) // if (!krbn::iokit_hid_device_open_checker_utility::run_checker()) { if (state_json_writer) { state_json_writer->set("hid_device_open_permitted", false); } if (root) { // We have to restart this process in order to reflect the input monitoring approval. return 0; } } else { if (state_json_writer) { state_json_writer->set("hid_device_open_permitted", true); } } // // Make socket directory. // if (root) { krbn::filesystem_utility::mkdir_tmp_directory(); unlink(krbn::constants::get_grabber_socket_file_path()); // Make console_user_server_socket_directory std::stringstream ss; ss << "rm -r '" << krbn::constants::get_console_user_server_socket_directory() << "'"; system(ss.str().c_str()); mkdir(krbn::constants::get_console_user_server_socket_directory(), 0755); chown(krbn::constants::get_console_user_server_socket_directory(), 0, 0); chmod(krbn::constants::get_console_user_server_socket_directory(), 0755); } // // Run components_manager // krbn::components_manager_killer::initialize_shared_components_manager_killer(); // We have to use raw pointer (not smart pointer) to delete it in `dispatch_async`. krbn::grabber::components_manager* components_manager = nullptr; if (auto killer = krbn::components_manager_killer::get_shared_components_manager_killer()) { killer->kill_called.connect([&components_manager] { dispatch_async(dispatch_get_main_queue(), ^{ { // Mark as main queue to avoid a deadlock in `pqrs::gcd::dispatch_sync_on_main_queue` in destructor. pqrs::gcd::scoped_running_on_main_queue_marker marker; if (components_manager) { delete components_manager; } } CFRunLoopStop(CFRunLoopGetCurrent()); }); }); } if (root) { components_manager = new krbn::grabber::components_manager(); components_manager->async_start(); } CFRunLoopRun(); krbn::components_manager_killer::terminate_shared_components_manager_killer(); state_json_writer = nullptr; krbn::logger::get_logger()->info("karabiner_grabber is terminated."); return 0; }
update #include
update #include
C++
unlicense
tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements
feb7d3df928488bf05fa0f7f3683e14d498661be
src/win_open_files.cpp
src/win_open_files.cpp
#include <map> #include <memory> #include <windows.h> #include <winternl.h> #include <anisthesia/win_open_files.hpp> #include <anisthesia/win_util.hpp> namespace anisthesia::win::detail { // WARNING: This file uses internal Windows APIs. The functions and structures // that are defined here and in <winternl.h> are subject to change. constexpr NTSTATUS STATUS_INFO_LENGTH_MISMATCH = 0xC0000004L; constexpr NTSTATUS STATUS_SUCCESS = 0x00000000L; enum { // SystemHandleInformation is limited to 16-bit process IDs, so we use // SystemExtendedHandleInformation instead. SystemExtendedHandleInformation = 64, }; struct SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX { PVOID Object; ULONG_PTR UniqueProcessId; HANDLE HandleValue; ACCESS_MASK GrantedAccess; USHORT CreatorBackTraceIndex; USHORT ObjectTypeIndex; ULONG HandleAttributes; ULONG Reserved; }; struct SYSTEM_HANDLE_INFORMATION_EX { ULONG_PTR NumberOfHandles; ULONG_PTR Reserved; SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1]; }; // This structure is defined as PUBLIC_OBJECT_TYPE_INFORMATION in Microsoft's // <winternl.h>, while it is defined as OBJECT_TYPE_INFORMATION in GCC's header // with actual data members instead of 'Reserved[22]'. struct OBJECT_TYPE_INFORMATION { UNICODE_STRING TypeName; ULONG Reserved[22]; }; using buffer_t = std::unique_ptr<BYTE[]>; //////////////////////////////////////////////////////////////////////////////// PVOID GetNtProcAddress(LPCSTR proc_name) { // We have to use run-time dynamic linking, because there is no associated // import library for the internal functions. return reinterpret_cast<PVOID>( GetProcAddress(GetModuleHandleA("ntdll.dll"), proc_name)); } NTSTATUS NtQuerySystemInformation( SYSTEM_INFORMATION_CLASS system_information_class, PVOID system_information, ULONG system_information_length, PULONG return_length) { static const auto nt_query_system_information = reinterpret_cast<decltype(::NtQuerySystemInformation)*>( GetNtProcAddress("NtQuerySystemInformation")); return nt_query_system_information(system_information_class, system_information, system_information_length, return_length); } NTSTATUS NtQueryObject( HANDLE handle, OBJECT_INFORMATION_CLASS object_information_class, PVOID object_information, ULONG object_information_length, PULONG return_length) { static const auto nt_query_object = reinterpret_cast<decltype(::NtQueryObject)*>( GetNtProcAddress("NtQueryObject")); return nt_query_object(handle, object_information_class, object_information, object_information_length, return_length); } //////////////////////////////////////////////////////////////////////////////// inline bool NtSuccess(NTSTATUS status) { return status >= 0; } buffer_t QuerySystemInformation( SYSTEM_INFORMATION_CLASS system_information_class) { ULONG size = 1 << 20; // 1 MiB constexpr ULONG kMaxSize = 1 << 24; // 16 MiB buffer_t buffer(new BYTE[size]); NTSTATUS status = STATUS_SUCCESS; do { ULONG return_length = 0; status = win::detail::NtQuerySystemInformation( system_information_class, buffer.get(), size, &return_length); if (status == STATUS_INFO_LENGTH_MISMATCH) { size = (return_length > size) ? return_length : (size * 2); buffer.reset(new BYTE[size]); } } while (status == STATUS_INFO_LENGTH_MISMATCH && size < kMaxSize); if (!NtSuccess(status)) buffer.reset(); return buffer; } buffer_t QueryObject(HANDLE handle, OBJECT_INFORMATION_CLASS object_information_class, ULONG size) { buffer_t buffer(new BYTE[size]); ULONG return_length = 0; const auto query_object = [&]() { return win::detail::NtQueryObject(handle, object_information_class, buffer.get(), size, &return_length); }; auto status = query_object(); if (status == STATUS_INFO_LENGTH_MISMATCH) { size = return_length; buffer.reset(new BYTE[size]); status = query_object(); } if (!NtSuccess(status)) buffer.reset(); return buffer; } //////////////////////////////////////////////////////////////////////////////// HANDLE OpenProcess(DWORD process_id) { // If we try to open a SYSTEM process, this function fails and the last error // code is ERROR_ACCESS_DENIED. return ::OpenProcess(PROCESS_DUP_HANDLE, false, process_id); } HANDLE DuplicateHandle(HANDLE process_handle, HANDLE handle) { HANDLE dup_handle = nullptr; const auto result = ::DuplicateHandle(process_handle, handle, ::GetCurrentProcess(), &dup_handle, 0, false, DUPLICATE_SAME_ACCESS); return result ? dup_handle : nullptr; } buffer_t GetSystemHandleInformation() { return QuerySystemInformation( static_cast<SYSTEM_INFORMATION_CLASS>(SystemExtendedHandleInformation)); } std::wstring GetUnicodeString(const UNICODE_STRING& unicode_string) { if (!unicode_string.Length) return std::wstring(); return std::wstring(unicode_string.Buffer, unicode_string.Length / sizeof(WCHAR)); } std::wstring GetObjectTypeName(HANDLE handle) { const auto buffer = QueryObject(handle, ObjectTypeInformation, sizeof(OBJECT_TYPE_INFORMATION)); if (!buffer) return std::wstring(); const auto& type_information = *reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer.get()); return GetUnicodeString(type_information.TypeName); } std::wstring GetFinalPathNameByHandle(HANDLE handle) { std::wstring buffer(MAX_PATH, '\0'); auto get_final_path_name_by_handle = [&]() { return ::GetFinalPathNameByHandle(handle, &buffer.front(), buffer.size(), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS); }; auto result = get_final_path_name_by_handle(); if (result > buffer.size()) { buffer.resize(result, '\0'); result = get_final_path_name_by_handle(); } if (result < buffer.size()) buffer.resize(result); return buffer; } //////////////////////////////////////////////////////////////////////////////// bool VerifyObjectType(HANDLE handle, USHORT object_type_index) { // File type index varies between OS versions: // // Index | OS version // ------|----------- // 25 | Vista // 28 | XP // | 7 // 30 | 8.1 // 31 | 8 // | 10 // 34 | 10 1607 (Anniversary Update) // 35 | 10 1703 (Creators Update) // 36 | 10 1709 (Fall Creators Update) // | 10 1803 (April 2018 Update) // | 10 1809 (October 2018 Update) // 37 | 10 1903 (May 2019 Update) // | 10 1909 (November 2019 Update) // // Here we initialize the value with 0, so that it is determined at run time. // This is more reliable than hard-coding the values for each OS version. static USHORT file_type_index = 0; if (file_type_index) return object_type_index == file_type_index; if (!handle) return true; if (GetObjectTypeName(handle) == L"File") { file_type_index = object_type_index; return true; } return false; } bool VerifyAccessMask(ACCESS_MASK access_mask) { // Certain kinds of handles, mostly those which refer to named pipes, cause // some functions such as NtQueryObject and GetFinalPathNameByHandle to hang. // By examining the access mask, we can get some clues about the object type // and bail out if necessary. // // One method would be to hard-code individual masks that are known to cause // trouble: // // - 0x00100000 (SYNCHRONIZE access) // - 0x0012008d (e.g. "\Device\NamedPipe\DropboxDataPipe") // - 0x00120189 // - 0x0012019f // - 0x0016019f (e.g. "\Device\Afd\Endpoint") // - 0x001a019f // // While this works in most situations, we occasionally end up skipping valid // file handles. This method also requires updating the blacklist when we // encounter other masks that cause our application to hang on users' end. // // The most common access mask for the valid files we are interested in is // 0x00120089, which is made up of the following access rights: // // - 0x00000001 FILE_READ_DATA // - 0x00000008 FILE_READ_EA // - 0x00000080 FILE_READ_ATTRIBUTES // - 0x00020000 READ_CONTROL // - 0x00100000 SYNCHRONIZE // // Media players must have read-access in order to play a video file, so we // can safely skip a handle in the absence of this basic right: if (!(access_mask & FILE_READ_DATA)) return false; // We further assume that media players do not have any kind of write access // to video files: if ((access_mask & FILE_APPEND_DATA) || (access_mask & FILE_WRITE_EA) || (access_mask & FILE_WRITE_ATTRIBUTES)) { return false; } return true; } bool VerifyFileType(HANDLE handle) { // Skip character files, sockets, pipes, and files of unknown type return ::GetFileType(handle) == FILE_TYPE_DISK; } bool VerifyPath(const std::wstring& path) { if (path.empty()) return false; // Skip files under system directories if (IsSystemDirectory(path)) return false; // Skip invalid files, and directories const auto file_attributes = ::GetFileAttributes(path.c_str()); if ((file_attributes == INVALID_FILE_ATTRIBUTES) || (file_attributes & FILE_ATTRIBUTE_DIRECTORY)) { return false; } return true; } //////////////////////////////////////////////////////////////////////////////// bool EnumerateOpenFiles(const std::set<DWORD>& process_ids, open_file_proc_t open_file_proc) { if (!open_file_proc) return false; std::map<DWORD, Handle> process_handles; for (const auto& process_id : process_ids) { const auto handle = OpenProcess(process_id); if (handle) process_handles[process_id] = Handle(handle); } if (process_handles.empty()) return false; auto system_handle_information_buffer = GetSystemHandleInformation(); if (!system_handle_information_buffer) return false; const auto& system_handle_information = *reinterpret_cast<SYSTEM_HANDLE_INFORMATION_EX*>( system_handle_information_buffer.get()); if (!system_handle_information.NumberOfHandles) return false; for (size_t i = 0; i < system_handle_information.NumberOfHandles; ++i) { const auto& handle = system_handle_information.Handles[i]; // Skip if this handle does not belong to one of our PIDs const auto process_id = static_cast<DWORD>(handle.UniqueProcessId); if (!process_ids.count(process_id)) continue; // Skip if this is not a file handle if (!VerifyObjectType(nullptr, handle.ObjectTypeIndex)) continue; // Skip if the file handle has an inappropriate access mask if (!VerifyAccessMask(handle.GrantedAccess)) continue; // Duplicate the handle so that we can query it const auto process_handle = process_handles[process_id].get(); Handle dup_handle(DuplicateHandle(process_handle, handle.HandleValue)); if (!dup_handle) continue; // Skip if this is not a file handle, while determining file type index if (!VerifyObjectType(dup_handle.get(), handle.ObjectTypeIndex)) continue; // Skip if this is not a disk file if (!VerifyFileType(dup_handle.get())) continue; OpenFile open_file; open_file.process_id = process_id; open_file.path = GetFinalPathNameByHandle(dup_handle.get()); if (!VerifyPath(open_file.path)) continue; if (!open_file_proc(open_file)) return false; } return true; } } // namespace anisthesia::win::detail
#include <map> #include <memory> #include <windows.h> #include <winternl.h> #include <anisthesia/win_open_files.hpp> #include <anisthesia/win_util.hpp> namespace anisthesia::win::detail { // WARNING: This file uses internal Windows APIs. The functions and structures // that are defined here and in <winternl.h> are subject to change. constexpr NTSTATUS STATUS_INFO_LENGTH_MISMATCH = 0xC0000004L; constexpr NTSTATUS STATUS_SUCCESS = 0x00000000L; enum { // SystemHandleInformation is limited to 16-bit process IDs, so we use // SystemExtendedHandleInformation instead. SystemExtendedHandleInformation = 64, }; struct SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX { PVOID Object; ULONG_PTR UniqueProcessId; HANDLE HandleValue; ACCESS_MASK GrantedAccess; USHORT CreatorBackTraceIndex; USHORT ObjectTypeIndex; ULONG HandleAttributes; ULONG Reserved; }; struct SYSTEM_HANDLE_INFORMATION_EX { ULONG_PTR NumberOfHandles; ULONG_PTR Reserved; SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1]; }; // This structure is defined as PUBLIC_OBJECT_TYPE_INFORMATION in Microsoft's // <winternl.h>, while it is defined as OBJECT_TYPE_INFORMATION in GCC's header // with actual data members instead of 'Reserved[22]'. struct OBJECT_TYPE_INFORMATION { UNICODE_STRING TypeName; ULONG Reserved[22]; }; using buffer_t = std::unique_ptr<BYTE[]>; //////////////////////////////////////////////////////////////////////////////// PVOID GetNtProcAddress(LPCSTR proc_name) { // We have to use run-time dynamic linking, because there is no associated // import library for the internal functions. return reinterpret_cast<PVOID>( GetProcAddress(GetModuleHandleA("ntdll.dll"), proc_name)); } NTSTATUS NtQuerySystemInformation( SYSTEM_INFORMATION_CLASS system_information_class, PVOID system_information, ULONG system_information_length, PULONG return_length) { static const auto nt_query_system_information = reinterpret_cast<decltype(::NtQuerySystemInformation)*>( GetNtProcAddress("NtQuerySystemInformation")); return nt_query_system_information(system_information_class, system_information, system_information_length, return_length); } NTSTATUS NtQueryObject( HANDLE handle, OBJECT_INFORMATION_CLASS object_information_class, PVOID object_information, ULONG object_information_length, PULONG return_length) { static const auto nt_query_object = reinterpret_cast<decltype(::NtQueryObject)*>( GetNtProcAddress("NtQueryObject")); return nt_query_object(handle, object_information_class, object_information, object_information_length, return_length); } //////////////////////////////////////////////////////////////////////////////// inline bool NtSuccess(NTSTATUS status) { return status >= 0; } buffer_t QuerySystemInformation( SYSTEM_INFORMATION_CLASS system_information_class) { ULONG size = 1 << 20; // 1 MiB constexpr ULONG kMaxSize = 1 << 24; // 16 MiB buffer_t buffer(new BYTE[size]); NTSTATUS status = STATUS_SUCCESS; do { ULONG return_length = 0; status = win::detail::NtQuerySystemInformation( system_information_class, buffer.get(), size, &return_length); if (status == STATUS_INFO_LENGTH_MISMATCH) { size = (return_length > size) ? return_length : (size * 2); buffer.reset(new BYTE[size]); } } while (status == STATUS_INFO_LENGTH_MISMATCH && size < kMaxSize); if (!NtSuccess(status)) buffer.reset(); return buffer; } buffer_t QueryObject(HANDLE handle, OBJECT_INFORMATION_CLASS object_information_class, ULONG size) { buffer_t buffer(new BYTE[size]); ULONG return_length = 0; const auto query_object = [&]() { return win::detail::NtQueryObject(handle, object_information_class, buffer.get(), size, &return_length); }; auto status = query_object(); if (status == STATUS_INFO_LENGTH_MISMATCH) { size = return_length; buffer.reset(new BYTE[size]); status = query_object(); } if (!NtSuccess(status)) buffer.reset(); return buffer; } //////////////////////////////////////////////////////////////////////////////// HANDLE OpenProcess(DWORD process_id) { // If we try to open a SYSTEM process, this function fails and the last error // code is ERROR_ACCESS_DENIED. return ::OpenProcess(PROCESS_DUP_HANDLE, false, process_id); } HANDLE DuplicateHandle(HANDLE process_handle, HANDLE handle) { HANDLE dup_handle = nullptr; const auto result = ::DuplicateHandle(process_handle, handle, ::GetCurrentProcess(), &dup_handle, 0, false, DUPLICATE_SAME_ACCESS); return result ? dup_handle : nullptr; } buffer_t GetSystemHandleInformation() { return QuerySystemInformation( static_cast<SYSTEM_INFORMATION_CLASS>(SystemExtendedHandleInformation)); } std::wstring GetUnicodeString(const UNICODE_STRING& unicode_string) { if (!unicode_string.Length) return std::wstring(); return std::wstring(unicode_string.Buffer, unicode_string.Length / sizeof(WCHAR)); } std::wstring GetObjectTypeName(HANDLE handle) { const auto buffer = QueryObject(handle, ObjectTypeInformation, sizeof(OBJECT_TYPE_INFORMATION)); if (!buffer) return std::wstring(); const auto& type_information = *reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer.get()); return GetUnicodeString(type_information.TypeName); } std::wstring GetFinalPathNameByHandle(HANDLE handle) { std::wstring buffer(MAX_PATH, '\0'); auto get_final_path_name_by_handle = [&]() { return ::GetFinalPathNameByHandle(handle, &buffer.front(), buffer.size(), FILE_NAME_NORMALIZED | VOLUME_NAME_DOS); }; auto result = get_final_path_name_by_handle(); if (result > buffer.size()) { buffer.resize(result, '\0'); result = get_final_path_name_by_handle(); } if (result < buffer.size()) buffer.resize(result); return buffer; } //////////////////////////////////////////////////////////////////////////////// bool VerifyObjectType(HANDLE handle, USHORT object_type_index) { // File type index varies between OS versions: // // Index | OS version // ------|----------- // 25 | Vista // 28 | XP // | 7 // 30 | 8.1 // 31 | 8 // | 10 // 34 | 10 1607 (Anniversary Update) // 35 | 10 1703 (Creators Update) // 36 | 10 1709 (Fall Creators Update) // | 10 1803 (April 2018 Update) // | 10 1809 (October 2018 Update) // 37 | 10 1903 (May 2019 Update) // | 10 1909 (November 2019 Update) // | 10 2004 (May 2020 Update) // | 10 20H2 (October 2020 Update) // // Here we initialize the value with 0, so that it is determined at run time. // This is more reliable than hard-coding the values for each OS version. static USHORT file_type_index = 0; if (file_type_index) return object_type_index == file_type_index; if (!handle) return true; if (GetObjectTypeName(handle) == L"File") { file_type_index = object_type_index; return true; } return false; } bool VerifyAccessMask(ACCESS_MASK access_mask) { // Certain kinds of handles, mostly those which refer to named pipes, cause // some functions such as NtQueryObject and GetFinalPathNameByHandle to hang. // By examining the access mask, we can get some clues about the object type // and bail out if necessary. // // One method would be to hard-code individual masks that are known to cause // trouble: // // - 0x00100000 (SYNCHRONIZE access) // - 0x0012008d (e.g. "\Device\NamedPipe\DropboxDataPipe") // - 0x00120189 // - 0x0012019f // - 0x0016019f (e.g. "\Device\Afd\Endpoint") // - 0x001a019f // // While this works in most situations, we occasionally end up skipping valid // file handles. This method also requires updating the blacklist when we // encounter other masks that cause our application to hang on users' end. // // The most common access mask for the valid files we are interested in is // 0x00120089, which is made up of the following access rights: // // - 0x00000001 FILE_READ_DATA // - 0x00000008 FILE_READ_EA // - 0x00000080 FILE_READ_ATTRIBUTES // - 0x00020000 READ_CONTROL // - 0x00100000 SYNCHRONIZE // // Media players must have read-access in order to play a video file, so we // can safely skip a handle in the absence of this basic right: if (!(access_mask & FILE_READ_DATA)) return false; // We further assume that media players do not have any kind of write access // to video files: if ((access_mask & FILE_APPEND_DATA) || (access_mask & FILE_WRITE_EA) || (access_mask & FILE_WRITE_ATTRIBUTES)) { return false; } return true; } bool VerifyFileType(HANDLE handle) { // Skip character files, sockets, pipes, and files of unknown type return ::GetFileType(handle) == FILE_TYPE_DISK; } bool VerifyPath(const std::wstring& path) { if (path.empty()) return false; // Skip files under system directories if (IsSystemDirectory(path)) return false; // Skip invalid files, and directories const auto file_attributes = ::GetFileAttributes(path.c_str()); if ((file_attributes == INVALID_FILE_ATTRIBUTES) || (file_attributes & FILE_ATTRIBUTE_DIRECTORY)) { return false; } return true; } //////////////////////////////////////////////////////////////////////////////// bool EnumerateOpenFiles(const std::set<DWORD>& process_ids, open_file_proc_t open_file_proc) { if (!open_file_proc) return false; std::map<DWORD, Handle> process_handles; for (const auto& process_id : process_ids) { const auto handle = OpenProcess(process_id); if (handle) process_handles[process_id] = Handle(handle); } if (process_handles.empty()) return false; auto system_handle_information_buffer = GetSystemHandleInformation(); if (!system_handle_information_buffer) return false; const auto& system_handle_information = *reinterpret_cast<SYSTEM_HANDLE_INFORMATION_EX*>( system_handle_information_buffer.get()); if (!system_handle_information.NumberOfHandles) return false; for (size_t i = 0; i < system_handle_information.NumberOfHandles; ++i) { const auto& handle = system_handle_information.Handles[i]; // Skip if this handle does not belong to one of our PIDs const auto process_id = static_cast<DWORD>(handle.UniqueProcessId); if (!process_ids.count(process_id)) continue; // Skip if this is not a file handle if (!VerifyObjectType(nullptr, handle.ObjectTypeIndex)) continue; // Skip if the file handle has an inappropriate access mask if (!VerifyAccessMask(handle.GrantedAccess)) continue; // Duplicate the handle so that we can query it const auto process_handle = process_handles[process_id].get(); Handle dup_handle(DuplicateHandle(process_handle, handle.HandleValue)); if (!dup_handle) continue; // Skip if this is not a file handle, while determining file type index if (!VerifyObjectType(dup_handle.get(), handle.ObjectTypeIndex)) continue; // Skip if this is not a disk file if (!VerifyFileType(dup_handle.get())) continue; OpenFile open_file; open_file.process_id = process_id; open_file.path = GetFinalPathNameByHandle(dup_handle.get()); if (!VerifyPath(open_file.path)) continue; if (!open_file_proc(open_file)) return false; } return true; } } // namespace anisthesia::win::detail
Update file type index list
Update file type index list
C++
mit
erengy/anisthesia
505fea62687e23f092c7916057db4e77035b2ab9
src/x0/io/fileinfo.cpp
src/x0/io/fileinfo.cpp
#include "fileinfo.hpp" #include "fileinfo_service.hpp" namespace x0 { fileinfo::fileinfo(fileinfo_service& service, const std::string& filename) : service_(service), watcher_(service.loop_), filename_(filename), exists_(), etag_(service_.make_etag(*this)), mtime_(), mimetype_(service_.get_mimetype(filename_)) { watcher_.set<fileinfo, &fileinfo::callback>(this); watcher_.set(filename_.c_str()); watcher_.start(); exists_ = watcher_.attr.st_nlink > 0; } void fileinfo::callback(ev::stat& w, int revents) { data_.clear(); etag_ = service_.make_etag(*this); mimetype_ = service_.get_mimetype(filename_); } } // namespace x0
#include "fileinfo.hpp" #include "fileinfo_service.hpp" namespace x0 { fileinfo::fileinfo(fileinfo_service& service, const std::string& filename) : service_(service), watcher_(service.loop_), filename_(filename), exists_(), etag_(), mtime_(), mimetype_() { watcher_.set<fileinfo, &fileinfo::callback>(this); watcher_.set(filename_.c_str()); watcher_.start(); if ((exists_ = watcher_.attr.st_nlink > 0)) etag_ = service_.make_etag(*this); mimetype_ = service_.get_mimetype(filename_); } void fileinfo::callback(ev::stat& w, int revents) { data_.clear(); etag_ = service_.make_etag(*this); mimetype_ = service_.get_mimetype(filename_); } } // namespace x0
fix initialization error in fileinfo
core: fix initialization error in fileinfo
C++
mit
xzero/x0,christianparpart/x0,christianparpart/x0,xzero/x0,christianparpart/x0,xzero/x0,xzero/x0,xzero/x0,christianparpart/x0,christianparpart/x0,christianparpart/x0,christianparpart/x0,xzero/x0
93a59295acd099da91b9f1bb9d24c826e506e5b8
mpi_helpers.hpp
mpi_helpers.hpp
#pragma once #include <cstdio> #include <exception> #include <mpi.h> #include <string> #include <sstream> #include <chrono> #include <mutex> #include <chrono> #include <thread> #include <condition_variable> #include <array> #include <cstdlib> #include <cstring> #include "log.hpp" #include "setsm_code.hpp" static bool need_custom_async_progress() { static const std::array<std::string, 6> enable_strs = { "1", "y", "on", "yes", "enable" }; const char *s = getenv("SETSM_CUSTOM_ASYNC"); if(!s) return false; // convert to lowercase for comparison std::unique_ptr<char []> lower(new char[strlen(s) +1]()); for(int i = 0; s[i]; i++){ lower[i] = tolower(s[i]); } for(auto &s : enable_strs) { if(s == lower.get()) { return true; } } return false; } // adapted from https://stackoverflow.com/a/29775639 class InterruptableTimer { public: /** sleep for time, interruptable * * Returns false if interrupted, otherwise true **/ template<class R, class P> bool sleep( std::chrono::duration<R,P> const& time ) { auto is_stopped = [&](){ return _stop; }; std::unique_lock<std::mutex> lock(m); return !cv.wait_for(lock, time, is_stopped); } void stop() { std::unique_lock<std::mutex> lock(m); _stop = true; cv.notify_all(); } private: std::mutex m; std::condition_variable cv; bool _stop = false; }; template<class R, class P> void async_progress(InterruptableTimer &timer, std::chrono::duration<R,P> interval) { int flag; MPI_Status status; while(timer.sleep(interval)) { LOG("timer hit, probing MPI\n"); MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status); } LOG("worker exiting...\n"); } class MPIProgressor { public: template<class R, class P> MPIProgressor(std::chrono::duration<R,P> interval) : worker(&async_progress<R, P>, std::ref(timer), interval) { LOG("progressor starting\n"); } ~MPIProgressor() { LOG("MPIProgressor destructor entrance. stopping timer..\n"); timer.stop(); LOG("timer stopped...\n"); worker.join(); LOG("worked has joined, MPIProgressor exiting destructor\n"); } private: InterruptableTimer timer; std::thread worker; }; class MPIException: public std::exception { public: MPIException(const std::string& func, int error_code, const std::string& msg) { int len; char err_buf[MPI_MAX_ERROR_STRING + 1] = {}; const char *err_msg = err_buf; int ret = MPI_Error_string(error_code, err_buf, &len); if(ret != MPI_SUCCESS) err_msg = "Unknown error code"; std::ostringstream os; os << "function " << func << " returned (" << error_code << ") " << err_msg << ": " << msg; m_msg = os.str(); } virtual const char* what() const throw () { return m_msg.c_str(); } private: std::string m_msg; }; class MPICounter { public: MPICounter(int start_value=0) { int rank, ret; ret = MPI_Comm_rank(MPI_COMM_WORLD, &rank); if(ret != MPI_SUCCESS) { throw MPIException("MPI_Comm_rank", ret, "Could not get comm rank for counter"); } int sz = rank == 0 ? sizeof(int) : 0; ret = MPI_Alloc_mem(sz, MPI_INFO_NULL, &local); if(ret != MPI_SUCCESS) { throw MPIException("MPI_Alloc_mem", ret, "Could not allocate mem for counter window"); } // initialize counter to zero if(sz) local[0] = start_value; ret = MPI_Win_create(local, sz, sizeof(int), MPI_INFO_NULL, MPI_COMM_WORLD, &win); if(ret != MPI_SUCCESS) { throw MPIException("MPI_Win_create", ret, "Could not create counter window"); } } ~MPICounter() { LOG("freeing window...\n"); MPI_Win_free(&win); LOG("window freed\n"); LOG("freeing memory...\n"); MPI_Free_mem(local); LOG("memory freed\n"); } MPICounter(const MPICounter&) = delete; MPICounter operator=(const MPICounter&) = delete; int next() { LOG("locking window...\n"); int ret = MPI_Win_lock(MPI_LOCK_SHARED, 0, 0, win); if(ret != MPI_SUCCESS) { throw MPIException("MPI_Win_lock", ret, "Failed to lock counter window"); } LOG("window locked. Fetching and updaating...\n"); const int one = 1; int val; ret = MPI_Fetch_and_op(&one, &val, MPI_INT, 0, 0, MPI_SUM, win); if(ret != MPI_SUCCESS) { throw MPIException("MPI_Fetch_and_op", ret, "failed to get and increment counter"); } LOG("fetch and update done. unlocking...\n"); ret = MPI_Win_unlock(0, win); if(ret != MPI_SUCCESS) { throw MPIException("MPI_win_unlock", ret, "Failed to unlock window for counter"); } LOG("unlocked. returning %d\n", val); return val; } private: int *local; MPI_Win win; }; class MPITileIndexer : public TileIndexer { private: std::shared_ptr<MPICounter> counter; int length; int rank; public: MPITileIndexer(int length, int rank) : counter(new MPICounter), length(length), rank(rank) {} int next() { printf("DBG: rank %d calling counter->next()...\n", rank); int i = counter->next(); printf("DBG: rank %d counter->next() returned %d\n", rank, i); if(i < length) { printf("DBG: rank %d (%d < %d), returning %d from next()\n", rank, i, length, i); return i; } printf("DBG: rank %d (%d >= %d), returning %d from next()\n", rank, i, length, -1); return -1; } };
#pragma once #include <cstdio> #include <exception> #include <mpi.h> #include <string> #include <sstream> #include <chrono> #include <mutex> #include <chrono> #include <thread> #include <condition_variable> #include <array> #include <cstdlib> #include <cstring> #include "log.hpp" #include "setsm_code.hpp" static bool need_custom_async_progress() { static const std::array<std::string, 6> enable_strs = { "1", "y", "on", "yes", "enable" }; const char *s = getenv("SETSM_CUSTOM_ASYNC"); if(!s) return false; // convert to lowercase for comparison std::unique_ptr<char []> lower(new char[strlen(s) +1]()); for(int i = 0; s[i]; i++){ lower[i] = tolower(s[i]); } for(auto &s : enable_strs) { if(s == lower.get()) { return true; } } return false; } // adapted from https://stackoverflow.com/a/29775639 class InterruptableTimer { public: /** sleep for time, interruptable * * Returns false if interrupted, otherwise true **/ template<class R, class P> bool sleep( std::chrono::duration<R,P> const& time ) { auto is_stopped = [&](){ return _stop; }; std::unique_lock<std::mutex> lock(m); return !cv.wait_for(lock, time, is_stopped); } void stop() { std::unique_lock<std::mutex> lock(m); _stop = true; cv.notify_all(); } private: std::mutex m; std::condition_variable cv; bool _stop = false; }; template<class R, class P> void async_progress(InterruptableTimer &timer, std::chrono::duration<R,P> interval) { int flag; MPI_Status status; while(timer.sleep(interval)) { MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status); } } class MPIProgressor { public: template<class R, class P> MPIProgressor(std::chrono::duration<R,P> interval) : worker(&async_progress<R, P>, std::ref(timer), interval) { } ~MPIProgressor() { timer.stop(); worker.join(); } private: InterruptableTimer timer; std::thread worker; }; class MPIException: public std::exception { public: MPIException(const std::string& func, int error_code, const std::string& msg) { int len; char err_buf[MPI_MAX_ERROR_STRING + 1] = {}; const char *err_msg = err_buf; int ret = MPI_Error_string(error_code, err_buf, &len); if(ret != MPI_SUCCESS) err_msg = "Unknown error code"; std::ostringstream os; os << "function " << func << " returned (" << error_code << ") " << err_msg << ": " << msg; m_msg = os.str(); } virtual const char* what() const throw () { return m_msg.c_str(); } private: std::string m_msg; }; class MPICounter { public: MPICounter(int start_value=0) { int rank, ret; ret = MPI_Comm_rank(MPI_COMM_WORLD, &rank); if(ret != MPI_SUCCESS) { throw MPIException("MPI_Comm_rank", ret, "Could not get comm rank for counter"); } int sz = rank == 0 ? sizeof(int) : 0; ret = MPI_Alloc_mem(sz, MPI_INFO_NULL, &local); if(ret != MPI_SUCCESS) { throw MPIException("MPI_Alloc_mem", ret, "Could not allocate mem for counter window"); } // initialize counter to zero if(sz) local[0] = start_value; ret = MPI_Win_create(local, sz, sizeof(int), MPI_INFO_NULL, MPI_COMM_WORLD, &win); if(ret != MPI_SUCCESS) { throw MPIException("MPI_Win_create", ret, "Could not create counter window"); } } ~MPICounter() { MPI_Win_free(&win); MPI_Free_mem(local); } MPICounter(const MPICounter&) = delete; MPICounter operator=(const MPICounter&) = delete; int next() { int ret = MPI_Win_lock(MPI_LOCK_SHARED, 0, 0, win); if(ret != MPI_SUCCESS) { throw MPIException("MPI_Win_lock", ret, "Failed to lock counter window"); } const int one = 1; int val; ret = MPI_Fetch_and_op(&one, &val, MPI_INT, 0, 0, MPI_SUM, win); if(ret != MPI_SUCCESS) { throw MPIException("MPI_Fetch_and_op", ret, "failed to get and increment counter"); } ret = MPI_Win_unlock(0, win); if(ret != MPI_SUCCESS) { throw MPIException("MPI_win_unlock", ret, "Failed to unlock window for counter"); } return val; } private: int *local; MPI_Win win; }; class MPITileIndexer : public TileIndexer { private: std::shared_ptr<MPICounter> counter; int length; int rank; public: MPITileIndexer(int length, int rank) : counter(new MPICounter), length(length), rank(rank) {} int next() { int i = counter->next(); if(i < length) { return i; } return -1; } };
Remove debug logging from mpi code
Remove debug logging from mpi code
C++
apache-2.0
setsmdeveloper/SETSM,setsmdeveloper/SETSM,setsmdeveloper/SETSM
37ed47b2b89eccb3996e260e64aff05567b22ffe
kr_common/include/kr_common/ros_helper.hpp
kr_common/include/kr_common/ros_helper.hpp
#ifndef KR_COMMON_ROS_HELPER_HPP_ #define KR_COMMON_ROS_HELPER_HPP_ #include <ros/ros.h> #include <ros/package.h> namespace kr { /** * @brief getParam Get ros param in node handle's namespace, with default value */ template <typename T> T GetParam(const ros::NodeHandle& nh, const std::string& param_name, const T& default_val) { T param_val; nh.param<T>(nh.resolveName(param_name), param_val, default_val); return param_val; } /** * @brief GetParam Get ros param in node handle's namespace ,use T's default * constructor */ template <typename T> T GetParam(const ros::NodeHandle& nh, const std::string& param_name) { const T default_val{}; return GetParam<T>(nh, param_name, default_val); } /** * @brief getParam Get ros param in node's namespace with default value */ template <typename T> T GetParam(const std::string& param_name, const T& default_val) { T param_val; ros::param::param<T>(ros::names::resolve(param_name), param_val, default_val); return param_val; } template <typename T> /** * @brief GetParam Get ros param in node's namespace, use T's default * constructor */ T GetParam(const std::string& param_name) { const T default_val{}; return GetParam<T>(param_name, default_val); } /** * @brief PackageUrlToFullPath Get full file path based on package url * @param url Url start with package:// * @return Path of url * @note Assume url contains no special variable needs to be resolved */ std::string PackageUrlToFullPath(const std::string url) { static const std::string pkg_prefix("package://"); static const size_t prefix_len = pkg_prefix.length(); const size_t rest = url.find('/', prefix_len); const std::string pkg(url.substr(prefix_len, rest - prefix_len)); // Look up the ROS package path name. const std::string pkg_path(ros::package::getPath(pkg)); if (pkg_path.empty()) { ROS_WARN_STREAM("unknown package: " << pkg << " (ignored)"); return pkg_path; } return pkg_path + url.substr(rest); } /** * @brief The UrlParser class */ class RosUrlParser { public: /** * @brief UrlToFullPath Get full path based on url * @param url Url start with package:// or file:// * @return Path of url if valid, empty string if invalid */ static std::string UrlToFullPath(const std::string& url) { const std::string url_resolved(ResolveUrl(url)); const auto url_type = ParseUrl(url_resolved); if (url_type == UrlType::URL_FILE) { return url_resolved.substr(7); } if (url_type == UrlType::URL_PACKAGE) { return PackageUrlToFullPath(url_resolved); } return std::string{}; } /** * @brief ResolveUrl Resolve variables in url * @return Resolved url */ static std::string ResolveUrl(const std::string& url) { std::string resolved; size_t rest = 0; while (true) { // find the next '$' in the URL string auto dollar = url.find('$', rest); if (dollar >= url.length()) { // no more variables left in the URL resolved += url.substr(rest); break; } // copy characters up to the next '$' resolved += url.substr(rest, dollar - rest); if (url.substr(dollar + 1, 1) != "{") { // no '{' follows, so keep the '$' resolved += "$"; } else if (url.substr(dollar + 1, 10) == "{ROS_HOME}") { // substitute $ROS_HOME std::string ros_home; char* ros_home_env; if ((ros_home_env = getenv("ROS_HOME"))) { // use environment variable ros_home = ros_home_env; } else if ((ros_home_env = getenv("HOME"))) { // use "$HOME/.ros" ros_home = ros_home_env; ros_home += "/.ros"; } resolved += ros_home; dollar += 10; } else { // not a valid substitution variable ROS_ERROR_STREAM( "[UrlParser]" " invalid URL substitution (not resolved): " << url); resolved += "$"; // keep the bogus '$' } // look for next '$' rest = dollar + 1; } return resolved; } /** * @brief ValidateUrl Validate if url is supported * @return True if url is valid */ static bool ValidateUrl(const std::string& url) { UrlType url_type = ParseUrl(ResolveUrl(url)); return (url_type < UrlType::URL_INVALID); } private: enum class UrlType { URL_EMPTY = 0, // empty string URL_FILE, // file: URL_PACKAGE, // package: URL_INVALID // anything >= is invalid }; /** * @brief ParseUrl Parse resolved url * @return Url type */ static UrlType ParseUrl(const std::string& url_resolved) { if (url_resolved == "") { return UrlType::URL_EMPTY; } if (url_resolved.substr(0, 8) == "file:///") { return UrlType::URL_FILE; } if (url_resolved.substr(0, 10) == "package://") { auto rest = url_resolved.find('/', 10); if (rest < url_resolved.length() - 1 && rest > 10) { return UrlType::URL_PACKAGE; } } return UrlType::URL_INVALID; } }; } // namespace kr #endif // KR_COMMON_ROS_HELPER_HPP_
#ifndef KR_COMMON_ROS_HELPER_HPP_ #define KR_COMMON_ROS_HELPER_HPP_ #include <ros/ros.h> #include <ros/package.h> namespace kr { /** * @brief getParam Get ros param in node handle's namespace, with default value */ template <typename T> T GetParam(const ros::NodeHandle& nh, const std::string& param_name, const T& default_val) { T param_val; nh.param<T>(nh.resolveName(param_name), param_val, default_val); return param_val; } /** * @brief GetParam Get ros param in node handle's namespace ,use T's default * constructor */ template <typename T> T GetParam(const ros::NodeHandle& nh, const std::string& param_name) { const T default_val{}; return GetParam<T>(nh, param_name, default_val); } /** * @brief getParam Get ros param in node's namespace with default value */ template <typename T> T GetParam(const std::string& param_name, const T& default_val) { T param_val; ros::param::param<T>(ros::names::resolve(param_name), param_val, default_val); return param_val; } template <typename T> /** * @brief GetParam Get ros param in node's namespace, use T's default * constructor */ T GetParam(const std::string& param_name) { const T default_val{}; return GetParam<T>(param_name, default_val); } /** * @brief PackageUrlToFullPath Get full file path based on package url * @param url Url start with package:// * @return Path of url * @note Assume url contains no special variable needs to be resolved */ static inline std::string PackageUrlToFullPath(const std::string url) { static const std::string pkg_prefix("package://"); static const size_t prefix_len = pkg_prefix.length(); const size_t rest = url.find('/', prefix_len); const std::string pkg(url.substr(prefix_len, rest - prefix_len)); // Look up the ROS package path name. const std::string pkg_path(ros::package::getPath(pkg)); if (pkg_path.empty()) { ROS_WARN_STREAM("unknown package: " << pkg << " (ignored)"); return pkg_path; } return pkg_path + url.substr(rest); } /** * @brief The UrlParser class */ class RosUrlParser { public: /** * @brief UrlToFullPath Get full path based on url * @param url Url start with package:// or file:// * @return Path of url if valid, empty string if invalid */ static std::string UrlToFullPath(const std::string& url) { const std::string url_resolved(ResolveUrl(url)); const auto url_type = ParseUrl(url_resolved); if (url_type == UrlType::URL_FILE) { return url_resolved.substr(7); } if (url_type == UrlType::URL_PACKAGE) { return PackageUrlToFullPath(url_resolved); } return std::string{}; } /** * @brief ResolveUrl Resolve variables in url * @return Resolved url */ static std::string ResolveUrl(const std::string& url) { std::string resolved; size_t rest = 0; while (true) { // find the next '$' in the URL string auto dollar = url.find('$', rest); if (dollar >= url.length()) { // no more variables left in the URL resolved += url.substr(rest); break; } // copy characters up to the next '$' resolved += url.substr(rest, dollar - rest); if (url.substr(dollar + 1, 1) != "{") { // no '{' follows, so keep the '$' resolved += "$"; } else if (url.substr(dollar + 1, 10) == "{ROS_HOME}") { // substitute $ROS_HOME std::string ros_home; char* ros_home_env; if ((ros_home_env = getenv("ROS_HOME"))) { // use environment variable ros_home = ros_home_env; } else if ((ros_home_env = getenv("HOME"))) { // use "$HOME/.ros" ros_home = ros_home_env; ros_home += "/.ros"; } resolved += ros_home; dollar += 10; } else { // not a valid substitution variable ROS_ERROR_STREAM( "[UrlParser]" " invalid URL substitution (not resolved): " << url); resolved += "$"; // keep the bogus '$' } // look for next '$' rest = dollar + 1; } return resolved; } /** * @brief ValidateUrl Validate if url is supported * @return True if url is valid */ static bool ValidateUrl(const std::string& url) { UrlType url_type = ParseUrl(ResolveUrl(url)); return (url_type < UrlType::URL_INVALID); } private: enum class UrlType { URL_EMPTY = 0, // empty string URL_FILE, // file: URL_PACKAGE, // package: URL_INVALID // anything >= is invalid }; /** * @brief ParseUrl Parse resolved url * @return Url type */ static UrlType ParseUrl(const std::string& url_resolved) { if (url_resolved == "") { return UrlType::URL_EMPTY; } if (url_resolved.substr(0, 8) == "file:///") { return UrlType::URL_FILE; } if (url_resolved.substr(0, 10) == "package://") { auto rest = url_resolved.find('/', 10); if (rest < url_resolved.length() - 1 && rest > 10) { return UrlType::URL_PACKAGE; } } return UrlType::URL_INVALID; } }; } // namespace kr #endif // KR_COMMON_ROS_HELPER_HPP_
add static inline to PackageUrlToFullPath
add static inline to PackageUrlToFullPath
C++
apache-2.0
KumarRobotics/kr_utils
b991f48ccff0567d581cf95e4eda1bffd5bbada3
lib/Analysis/ReturnPointerRangeChecker.cpp
lib/Analysis/ReturnPointerRangeChecker.cpp
//== ReturnPointerRangeChecker.cpp ------------------------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines ReturnPointerRangeChecker, which is a path-sensitive check // which looks for an out-of-bound pointer being returned to callers. // //===----------------------------------------------------------------------===// #include "GRExprEngineInternalChecks.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" #include "clang/Analysis/PathSensitive/BugReporter.h" #include "clang/Analysis/PathSensitive/CheckerVisitor.h" using namespace clang; namespace { class VISIBILITY_HIDDEN ReturnPointerRangeChecker : public CheckerVisitor<ReturnPointerRangeChecker> { BuiltinBug *BT; public: ReturnPointerRangeChecker() : BT(0) {} static void *getTag(); void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *RS); }; } void clang::RegisterReturnPointerRangeChecker(GRExprEngine &Eng) { Eng.registerCheck(new ReturnPointerRangeChecker()); } void *ReturnPointerRangeChecker::getTag() { static int x = 0; return &x; } void ReturnPointerRangeChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *RS) { const GRState *state = C.getState(); const Expr *RetE = RS->getRetValue(); if (!RetE) return; SVal V = state->getSVal(RetE); const MemRegion *R = V.getAsRegion(); const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(R); if (!ER) return; DefinedOrUnknownSVal &Idx = cast<DefinedOrUnknownSVal>(ER->getIndex()); // FIXME: All of this out-of-bounds checking should eventually be refactored into a // common place. // Zero index is always in bound, this also passes ElementRegions created for // pointer casts. if (Idx.isZeroConstant()) return; SVal NumVal = C.getStoreManager().getSizeInElements(state, ER->getSuperRegion()); DefinedOrUnknownSVal &NumElements = cast<DefinedOrUnknownSVal>(NumVal); const GRState *StInBound = state->AssumeInBound(Idx, NumElements, true); const GRState *StOutBound = state->AssumeInBound(Idx, NumElements, false); if (StOutBound && !StInBound) { ExplodedNode *N = C.GenerateNode(RS, StOutBound, true); if (!N) return; // FIXME: This bug correspond to CWE-466. Eventually we should have bug types explicitly // reference such exploit categories (when applicable). if (!BT) BT = new BuiltinBug("Return of pointer value outside of expected range", "Returned pointer value points outside the original object (potential buffer overflow)"); // FIXME: It would be nice to eventually make this diagnostic more clear, e.g., by referencing // the original declaration or by saying *why* this reference is outside the range. // Generate a report for this bug. RangedBugReport *report = new RangedBugReport(*BT, BT->getDescription().c_str(), N); report->addRange(RetE->getSourceRange()); C.EmitReport(report); } }
//== ReturnPointerRangeChecker.cpp ------------------------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines ReturnPointerRangeChecker, which is a path-sensitive check // which looks for an out-of-bound pointer being returned to callers. // //===----------------------------------------------------------------------===// #include "GRExprEngineInternalChecks.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" #include "clang/Analysis/PathSensitive/BugReporter.h" #include "clang/Analysis/PathSensitive/CheckerVisitor.h" using namespace clang; namespace { class VISIBILITY_HIDDEN ReturnPointerRangeChecker : public CheckerVisitor<ReturnPointerRangeChecker> { BuiltinBug *BT; public: ReturnPointerRangeChecker() : BT(0) {} static void *getTag(); void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *RS); }; } void clang::RegisterReturnPointerRangeChecker(GRExprEngine &Eng) { Eng.registerCheck(new ReturnPointerRangeChecker()); } void *ReturnPointerRangeChecker::getTag() { static int x = 0; return &x; } void ReturnPointerRangeChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *RS) { const GRState *state = C.getState(); const Expr *RetE = RS->getRetValue(); if (!RetE) return; SVal V = state->getSVal(RetE); const MemRegion *R = V.getAsRegion(); if (!R) return; R = R->StripCasts(); if (!R) return; const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(R); if (!ER) return; DefinedOrUnknownSVal &Idx = cast<DefinedOrUnknownSVal>(ER->getIndex()); // FIXME: All of this out-of-bounds checking should eventually be refactored // into a common place. SVal NumVal = C.getStoreManager().getSizeInElements(state, ER->getSuperRegion()); DefinedOrUnknownSVal &NumElements = cast<DefinedOrUnknownSVal>(NumVal); const GRState *StInBound = state->AssumeInBound(Idx, NumElements, true); const GRState *StOutBound = state->AssumeInBound(Idx, NumElements, false); if (StOutBound && !StInBound) { ExplodedNode *N = C.GenerateNode(RS, StOutBound, true); if (!N) return; // FIXME: This bug correspond to CWE-466. Eventually we should have bug // types explicitly reference such exploit categories (when applicable). if (!BT) BT = new BuiltinBug("Return of pointer value outside of expected range", "Returned pointer value points outside the original object " "(potential buffer overflow)"); // FIXME: It would be nice to eventually make this diagnostic more clear, // e.g., by referencing the original declaration or by saying *why* this // reference is outside the range. // Generate a report for this bug. RangedBugReport *report = new RangedBugReport(*BT, BT->getDescription().c_str(), N); report->addRange(RetE->getSourceRange()); C.EmitReport(report); } }
use StripCasts() instead of checking for zero index explicitly.
ReturnPointerRangeChecker: use StripCasts() instead of checking for zero index explicitly. Fix 80-col violations. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@86833 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang
d423e7f9476151a2a0f86d7de1a559347f2dfd5b
Source/Core/Game.cpp
Source/Core/Game.cpp
#include "Game.h" using namespace std; using namespace glm; Game *Game::inst = 0; Game::Game() { // Initialize game variables and settings isRunning = true; isFullscreen = false; caption = "Iceberg3D"; window = NULL; screenSurface = NULL; screenWidth = 640; screenHeight = 480; maxFPS = 60; previousTime = std::chrono::high_resolution_clock::now(); } Game *Game::GetInstance() { if (inst == 0) { inst = new Game(); } return inst; } bool Game::Initialize() { // Set caption caption = "Matthew Berger's Game Engine"; // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not be initialized! SDL_Error: %s", SDL_GetError() ); return false; } else { #ifdef VIRTUAL_MACHINE SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); #else SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); #endif // Create the window if (isFullscreen == true) { window = SDL_CreateWindow(caption.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN_DESKTOP); } else if (isFullscreen == false) { window = SDL_CreateWindow(caption.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); } if (window == NULL) { printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); return false; } else { // Create OpenGL Context context = SDL_GL_CreateContext(window); if (context == NULL) { printf("OpenGL context could not be created! SDL_Error: %s\n", SDL_GetError()); return false; } else { // Initialize OpenGL // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); // Depth testing glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // Enable culling //glEnable(GL_CULL_FACE); //glCullFace(GL_BACK); //glFrontFace(GL_CW); // Initialize GLEW glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK) { printf("Error initializing GLEW! %s \n", glewGetErrorString(glewError)); return false; } /* // Use Vsync if (SDL_GL_SetSwapInterval(1) < 0) { printf("Warning: Unable to set VSync! SDL Error: %s", SDL_GetError()); return false; }*/ // Initialize screen surface screenSurface = SDL_GetWindowSurface(window); // Initialize Sub Systems if(TTF_Init != 0) { printf("Error initializing SDL_ttf! %s \n", TTF_GetError()); return false; } } } } return true; } bool Game::LoadContent(GameState *state) { //-- Load game content here ChangeState(state); //-- return true; } void Game::UnloadContent() { // Release game content, Free Surfaces, Close Libraries if (!GameStates.empty()) { GameStates.back()->Finalize(); GameStates.pop_back(); } /************************************************/ // TTF_Quit(); // Mix_CloseAudio(); // Destroy Window SDL_DestroyWindow( window ); window = NULL; // Quit subsystems TTF_Quit(); SDL_Quit(); } void Game::ChangeState(GameState *state) { // If there is a state, clean it up and pop it off if (!GameStates.empty()) { GameStates.back()->Finalize(); GameStates.pop_back(); } // Push on the new one and initialize it GameStates.push_back(state); GameStates.back()->Initialize(); } void Game::PushState(GameState *state) { // Pause state if there is one already on stack if (!GameStates.empty()) { GameStates.back()->Pause(); } // Push state onto stack and initialize it GameStates.push_back(state); GameStates.back()->Initialize(); } void Game::PopState() { if (!GameStates.empty()) { // If somethings on the stack and finish up state then pop it off GameStates.back()->Finalize(); GameStates.pop_back(); // If there's a state left, it is paused, so resume it GameStates.back()->Resume(); } } void Game::Update() { // Place Update logic here GameStates.back()->Update(); } void Game::Draw() { // Place Rendering logic here GameStates.back()->Draw(); } void Game::EventHandler() { while( SDL_PollEvent(&event) != 0 ) { //Place Event Handling Functions here GameStates.back()->HandleEvents(); if (event.type == SDL_QUIT) { this->StopRunning(); } else if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_F11: this->ToggleFullScreen(); break; case SDLK_ESCAPE: this->StopRunning(); break; } } } } void Game::DestroyInstance() { delete inst; inst = 0; } void Game::ToggleFullScreen() { if (isFullscreen == false) { SDL_SetWindowFullscreen(window, SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP); isFullscreen = true; } else if (isFullscreen == true) { SDL_SetWindowFullscreen(window, 0); isFullscreen = false; } } bool Game::IsRunning() { return isRunning; } int Game::GetMaxFPS() { return maxFPS; } int Game::GetScreenWidth() { return screenWidth; } int Game::GetScreenHeight() { return screenHeight; } SDL_Event Game::GetEvent() { return event; } SDL_Surface* Game::GetSurface() { return screenSurface; // null } SDL_Window* Game::GetWindow() { return window; // null } void Game::SetMaxFPS(int newFPS) { maxFPS = newFPS; } void Game::StopRunning() { isRunning = false; } float Game::GetTimeDelta() { currentTime = std::chrono::high_resolution_clock::now(); float returnValue = std::chrono::duration_cast< std::chrono::duration<float> >(currentTime - previousTime).count(); previousTime = std::chrono::high_resolution_clock::now(); return returnValue; } float Game::GetAspectRatio() { // Prevent division by 0 float width = float(screenWidth); float height = float(screenHeight); return (height == 0) ? (width) : (width/height); }
#include "Game.h" using namespace std; using namespace glm; Game *Game::inst = 0; Game::Game() { // Initialize game variables and settings isRunning = true; isFullscreen = false; caption = "Iceberg3D"; window = NULL; screenSurface = NULL; screenWidth = 640; screenHeight = 480; maxFPS = 60; previousTime = std::chrono::high_resolution_clock::now(); } Game *Game::GetInstance() { if (inst == 0) { inst = new Game(); } return inst; } bool Game::Initialize() { // Set caption caption = "Matthew Berger's Game Engine"; // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not be initialized! SDL_Error: %s", SDL_GetError() ); return false; } else { #ifdef VIRTUAL_MACHINE SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); #else SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); #endif // Create the window if (isFullscreen == true) { window = SDL_CreateWindow(caption.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN_DESKTOP); } else if (isFullscreen == false) { window = SDL_CreateWindow(caption.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); } if (window == NULL) { printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); return false; } else { // Create OpenGL Context context = SDL_GL_CreateContext(window); if (context == NULL) { printf("OpenGL context could not be created! SDL_Error: %s\n", SDL_GetError()); return false; } else { // Initialize OpenGL // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); // Depth testing glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // Enable culling //glEnable(GL_CULL_FACE); //glCullFace(GL_BACK); //glFrontFace(GL_CW); // Initialize GLEW glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != GLEW_OK) { printf("Error initializing GLEW! %s \n", glewGetErrorString(glewError)); return false; } /* // Use Vsync if (SDL_GL_SetSwapInterval(1) < 0) { printf("Warning: Unable to set VSync! SDL Error: %s", SDL_GetError()); return false; }*/ // Initialize screen surface screenSurface = SDL_GetWindowSurface(window); // Initialize Sub Systems if(TTF_Init() != 0) { printf("Error initializing SDL_ttf! %s \n", TTF_GetError()); return false; } } } } return true; } bool Game::LoadContent(GameState *state) { //-- Load game content here ChangeState(state); //-- return true; } void Game::UnloadContent() { // Release game content, Free Surfaces, Close Libraries if (!GameStates.empty()) { GameStates.back()->Finalize(); GameStates.pop_back(); } /************************************************/ // TTF_Quit(); // Mix_CloseAudio(); // Destroy Window SDL_DestroyWindow( window ); window = NULL; // Quit subsystems TTF_Quit(); SDL_Quit(); } void Game::ChangeState(GameState *state) { // If there is a state, clean it up and pop it off if (!GameStates.empty()) { GameStates.back()->Finalize(); GameStates.pop_back(); } // Push on the new one and initialize it GameStates.push_back(state); GameStates.back()->Initialize(); } void Game::PushState(GameState *state) { // Pause state if there is one already on stack if (!GameStates.empty()) { GameStates.back()->Pause(); } // Push state onto stack and initialize it GameStates.push_back(state); GameStates.back()->Initialize(); } void Game::PopState() { if (!GameStates.empty()) { // If somethings on the stack and finish up state then pop it off GameStates.back()->Finalize(); GameStates.pop_back(); // If there's a state left, it is paused, so resume it GameStates.back()->Resume(); } } void Game::Update() { // Place Update logic here GameStates.back()->Update(); } void Game::Draw() { // Place Rendering logic here GameStates.back()->Draw(); } void Game::EventHandler() { while( SDL_PollEvent(&event) != 0 ) { //Place Event Handling Functions here GameStates.back()->HandleEvents(); if (event.type == SDL_QUIT) { this->StopRunning(); } else if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_F11: this->ToggleFullScreen(); break; case SDLK_ESCAPE: this->StopRunning(); break; } } } } void Game::DestroyInstance() { delete inst; inst = 0; } void Game::ToggleFullScreen() { if (isFullscreen == false) { SDL_SetWindowFullscreen(window, SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP); isFullscreen = true; } else if (isFullscreen == true) { SDL_SetWindowFullscreen(window, 0); isFullscreen = false; } } bool Game::IsRunning() { return isRunning; } int Game::GetMaxFPS() { return maxFPS; } int Game::GetScreenWidth() { return screenWidth; } int Game::GetScreenHeight() { return screenHeight; } SDL_Event Game::GetEvent() { return event; } SDL_Surface* Game::GetSurface() { return screenSurface; // null } SDL_Window* Game::GetWindow() { return window; // null } void Game::SetMaxFPS(int newFPS) { maxFPS = newFPS; } void Game::StopRunning() { isRunning = false; } float Game::GetTimeDelta() { currentTime = std::chrono::high_resolution_clock::now(); float returnValue = std::chrono::duration_cast< std::chrono::duration<float> >(currentTime - previousTime).count(); previousTime = std::chrono::high_resolution_clock::now(); return returnValue; } float Game::GetAspectRatio() { // Prevent division by 0 float width = float(screenWidth); float height = float(screenHeight); return (height == 0) ? (width) : (width/height); }
Correct typo in last commit.
Correct typo in last commit.
C++
mit
matthewjberger/Iceberg3D,matthewjberger/Iceberg3D
98eb4b5fe9d4b684e8e6ad1dc865b8e7407ebff2
src/engine/framework/Rcon.cpp
src/engine/framework/Rcon.cpp
/* =========================================================================== Daemon BSD Source Code Copyright (c) 2013-2016, Daemon Developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Daemon developers 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 DAEMON DEVELOPERS 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 "common/Common.h" #include "engine/qcommon/qcommon.h" #include "Rcon.h" #include "Crypto.h" #include "framework/Network.h" #include "engine/server/CryptoChallenge.h" namespace Rcon { Message::Message( const netadr_t& remote, std::string command, Secure secure, std::string password, std::string challenge ) : secure(secure), challenge(std::move(challenge)), command(std::move(command)), password(std::move(password)), remote(remote) {} Message::Message( std::string error_message ) : error(std::move(error_message)) {} bool Message::Valid(std::string *invalid_reason) const { auto invalid = [invalid_reason](const char* reason) { if ( invalid_reason ) *invalid_reason = reason; return false; }; if ( !error.empty() ) { return invalid(error.c_str()); } if ( secure < Secure::Unencrypted || secure > Secure::EncryptedChallenge ) { return invalid("Unknown secure protocol"); } if ( password.empty() ) { return invalid("Missing password"); } if ( command.empty() ) { return invalid("Missing command"); } if ( secure == Secure::EncryptedChallenge && challenge.empty() ) { return invalid("Missing challenge"); } return true; } } // namespace Rcon
/* =========================================================================== Daemon BSD Source Code Copyright (c) 2013-2016, Daemon Developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Daemon developers 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 DAEMON DEVELOPERS 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 "common/Common.h" #include "engine/qcommon/qcommon.h" #include "Rcon.h" #include "Crypto.h" #include "framework/Network.h" #include "engine/server/CryptoChallenge.h" namespace Rcon { Message::Message( const netadr_t& remote, std::string command, Secure secure, std::string password, std::string challenge ) : secure(secure), challenge(std::move(challenge)), command(std::move(command)), password(std::move(password)), remote(remote) {} Message::Message( std::string error_message ) : secure(Secure::Invalid), error(std::move(error_message)) { memset(&remote, 0, sizeof(remote)); } bool Message::Valid(std::string *invalid_reason) const { auto invalid = [invalid_reason](const char* reason) { if ( invalid_reason ) *invalid_reason = reason; return false; }; if ( !error.empty() ) { return invalid(error.c_str()); } if ( secure < Secure::Unencrypted || secure > Secure::EncryptedChallenge ) { return invalid("Unknown secure protocol"); } if ( password.empty() ) { return invalid("Missing password"); } if ( command.empty() ) { return invalid("Missing command"); } if ( secure == Secure::EncryptedChallenge && challenge.empty() ) { return invalid("Missing challenge"); } return true; } } // namespace Rcon
Initialize message members to prevent UB on access to them
[framework] Initialize message members to prevent UB on access to them
C++
bsd-3-clause
DaemonEngine/Daemon,DaemonEngine/Daemon,DaemonEngine/Daemon,DaemonEngine/Daemon
f79853ccfe14314caebc7e03ac1ebf1bbf8c159a
svtools/source/control/collatorres.cxx
svtools/source/control/collatorres.cxx
#include <svtdata.hxx> #include <svtools.hrc> #ifndef SVTOOLS_COLLATORRESSOURCE_HXX #include <collatorres.hxx> #endif // ------------------------------------------------------------------------- // // wrapper for locale specific translations data of collator algorithm // // ------------------------------------------------------------------------- class CollatorRessourceData { friend class CollatorRessource; private: /* data */ String ma_Name; String ma_Translation; private: /* member functions */ CollatorRessourceData () {} public: CollatorRessourceData ( const String &r_Algorithm, const String &r_Translation) : ma_Name (r_Algorithm), ma_Translation (r_Translation) {} const String& GetAlgorithm () const { return ma_Name; } const String& GetTranslation () const { return ma_Translation; } ~CollatorRessourceData () {} CollatorRessourceData& operator= (CollatorRessourceData& r_From) { ma_Name = r_From.GetAlgorithm(); ma_Translation = r_From.GetTranslation(); return *this; } }; // ------------------------------------------------------------------------- // // implementation of the collator-algorithm-name translation // // ------------------------------------------------------------------------- #define COLLATOR_RESSOURCE_COUNT 9 CollatorRessource::CollatorRessource() { mp_Data = new CollatorRessourceData[COLLATOR_RESSOURCE_COUNT]; #define ASCSTR(str) String(RTL_CONSTASCII_USTRINGPARAM(str)) #define RESSTR(rid) String(SvtResId(rid)) mp_Data[0] = CollatorRessourceData (ASCSTR("alphanumeric"), RESSTR(STR_SVT_COLLATE_ALPHANUMERIC)); mp_Data[1] = CollatorRessourceData (ASCSTR("charset"), RESSTR(STR_SVT_COLLATE_CHARSET)); mp_Data[2] = CollatorRessourceData (ASCSTR("dict"), RESSTR(STR_SVT_COLLATE_DICTIONARY)); mp_Data[3] = CollatorRessourceData (ASCSTR("normal"), RESSTR(STR_SVT_COLLATE_NORMAL)); mp_Data[4] = CollatorRessourceData (ASCSTR("pinyin"), RESSTR(STR_SVT_COLLATE_PINYIN)); mp_Data[5] = CollatorRessourceData (ASCSTR("radical"), RESSTR(STR_SVT_COLLATE_RADICAL)); mp_Data[6] = CollatorRessourceData (ASCSTR("stroke"), RESSTR(STR_SVT_COLLATE_STROKE)); mp_Data[7] = CollatorRessourceData (ASCSTR("unicode"), RESSTR(STR_SVT_COLLATE_UNICODE)); mp_Data[8] = CollatorRessourceData (ASCSTR("zhuyin"), RESSTR(STR_SVT_COLLATE_ZHUYIN)); } CollatorRessource::~CollatorRessource() { delete[] mp_Data; } const String& CollatorRessource::GetTranslation (const String &r_Algorithm) { xub_StrLen nIndex = r_Algorithm.Search('.'); String aLocaleFreeAlgorithm; if (nIndex == STRING_NOTFOUND) { aLocaleFreeAlgorithm = r_Algorithm; } else { nIndex += 1; aLocaleFreeAlgorithm = String(r_Algorithm, nIndex, r_Algorithm.Len() - nIndex); } for (sal_uInt32 i = 0; i < COLLATOR_RESSOURCE_COUNT; i++) { if (aLocaleFreeAlgorithm == mp_Data[i].GetAlgorithm()) return mp_Data[i].GetTranslation(); } return r_Algorithm; }
#include <svtdata.hxx> #include <svtools.hrc> #ifndef SVTOOLS_COLLATORRESSOURCE_HXX #include <collatorres.hxx> #endif // ------------------------------------------------------------------------- // // wrapper for locale specific translations data of collator algorithm // // ------------------------------------------------------------------------- class CollatorRessourceData { friend class CollatorRessource; private: /* data */ String ma_Name; String ma_Translation; private: /* member functions */ CollatorRessourceData () {} public: CollatorRessourceData ( const String &r_Algorithm, const String &r_Translation) : ma_Name (r_Algorithm), ma_Translation (r_Translation) {} const String& GetAlgorithm () const { return ma_Name; } const String& GetTranslation () const { return ma_Translation; } ~CollatorRessourceData () {} CollatorRessourceData& operator= (const CollatorRessourceData& r_From) { ma_Name = r_From.GetAlgorithm(); ma_Translation = r_From.GetTranslation(); return *this; } }; // ------------------------------------------------------------------------- // // implementation of the collator-algorithm-name translation // // ------------------------------------------------------------------------- #define COLLATOR_RESSOURCE_COUNT 9 CollatorRessource::CollatorRessource() { mp_Data = new CollatorRessourceData[COLLATOR_RESSOURCE_COUNT]; #define ASCSTR(str) String(RTL_CONSTASCII_USTRINGPARAM(str)) #define RESSTR(rid) String(SvtResId(rid)) mp_Data[0] = CollatorRessourceData (ASCSTR("alphanumeric"), RESSTR(STR_SVT_COLLATE_ALPHANUMERIC)); mp_Data[1] = CollatorRessourceData (ASCSTR("charset"), RESSTR(STR_SVT_COLLATE_CHARSET)); mp_Data[2] = CollatorRessourceData (ASCSTR("dict"), RESSTR(STR_SVT_COLLATE_DICTIONARY)); mp_Data[3] = CollatorRessourceData (ASCSTR("normal"), RESSTR(STR_SVT_COLLATE_NORMAL)); mp_Data[4] = CollatorRessourceData (ASCSTR("pinyin"), RESSTR(STR_SVT_COLLATE_PINYIN)); mp_Data[5] = CollatorRessourceData (ASCSTR("radical"), RESSTR(STR_SVT_COLLATE_RADICAL)); mp_Data[6] = CollatorRessourceData (ASCSTR("stroke"), RESSTR(STR_SVT_COLLATE_STROKE)); mp_Data[7] = CollatorRessourceData (ASCSTR("unicode"), RESSTR(STR_SVT_COLLATE_UNICODE)); mp_Data[8] = CollatorRessourceData (ASCSTR("zhuyin"), RESSTR(STR_SVT_COLLATE_ZHUYIN)); } CollatorRessource::~CollatorRessource() { delete[] mp_Data; } const String& CollatorRessource::GetTranslation (const String &r_Algorithm) { xub_StrLen nIndex = r_Algorithm.Search('.'); String aLocaleFreeAlgorithm; if (nIndex == STRING_NOTFOUND) { aLocaleFreeAlgorithm = r_Algorithm; } else { nIndex += 1; aLocaleFreeAlgorithm = String(r_Algorithm, nIndex, r_Algorithm.Len() - nIndex); } for (sal_uInt32 i = 0; i < COLLATOR_RESSOURCE_COUNT; i++) { if (aLocaleFreeAlgorithm == mp_Data[i].GetAlgorithm()) return mp_Data[i].GetTranslation(); } return r_Algorithm; }
fix operator=()
#65293#: fix operator=()
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
0091e10d6f45bdde4f788ae0b97f96723ebf7ed0
src/envoy/tcp/mixer/filter.cc
src/envoy/tcp/mixer/filter.cc
/* Copyright 2017 Istio 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 "src/envoy/tcp/mixer/filter.h" #include "common/common/enum_to_int.h" #include "src/envoy/utils/utils.h" using ::google::protobuf::util::Status; using ::istio::mixerclient::CheckResponseInfo; namespace Envoy { namespace Tcp { namespace Mixer { Filter::Filter(Control& control) : control_(control) { ENVOY_LOG(debug, "Called tcp filter: {}", __func__); } Filter::~Filter() { cancelCheck(); ENVOY_LOG(debug, "Called tcp filter : {}", __func__); } void Filter::initializeReadFilterCallbacks( Network::ReadFilterCallbacks& callbacks) { ENVOY_LOG(debug, "Called tcp filter: {}", __func__); filter_callbacks_ = &callbacks; filter_callbacks_->connection().addConnectionCallbacks(*this); start_time_ = std::chrono::system_clock::now(); } void Filter::cancelCheck() { if (state_ != State::Calling) { cancel_check_ = nullptr; } state_ = State::Closed; if (cancel_check_) { ENVOY_LOG(debug, "Cancelling check call"); cancel_check_(); cancel_check_ = nullptr; } } // Makes a Check() call to Mixer. void Filter::callCheck() { handler_ = control_.controller()->CreateRequestHandler(); state_ = State::Calling; filter_callbacks_->connection().readDisable(true); calling_check_ = true; cancel_check_ = handler_->Check(this, [this](const CheckResponseInfo& info) { completeCheck(info.response_status); }); calling_check_ = false; } // Network::ReadFilter Network::FilterStatus Filter::onData(Buffer::Instance& data, bool) { if (state_ == State::NotStarted) { // By waiting to invoke the callCheck() at onData(), the call to Mixer // will have sufficient SSL information to fill the check Request. callCheck(); } ENVOY_CONN_LOG(debug, "Called tcp filter onRead bytes: {}", filter_callbacks_->connection(), data.length()); received_bytes_ += data.length(); return state_ == State::Calling ? Network::FilterStatus::StopIteration : Network::FilterStatus::Continue; } // Network::WriteFilter Network::FilterStatus Filter::onWrite(Buffer::Instance& data, bool) { ENVOY_CONN_LOG(debug, "Called tcp filter onWrite bytes: {}", filter_callbacks_->connection(), data.length()); send_bytes_ += data.length(); return Network::FilterStatus::Continue; } Network::FilterStatus Filter::onNewConnection() { ENVOY_CONN_LOG(debug, "Called tcp filter onNewConnection: remote {}, local {}", filter_callbacks_->connection(), filter_callbacks_->connection().remoteAddress()->asString(), filter_callbacks_->connection().localAddress()->asString()); // Wait until onData() is invoked. return Network::FilterStatus::Continue; } void Filter::completeCheck(const Status& status) { ENVOY_LOG(debug, "Called tcp filter completeCheck: {}", status.ToString()); cancel_check_ = nullptr; if (state_ == State::Closed) { return; } state_ = State::Completed; filter_callbacks_->connection().readDisable(false); if (!status.ok()) { filter_callbacks_->connection().close( Network::ConnectionCloseType::NoFlush); } else { if (!calling_check_) { filter_callbacks_->continueReading(); } report_timer_ = control_.dispatcher().createTimer([this]() { OnReportTimer(); }); report_timer_->enableTimer(control_.config().report_interval_ms()); } } // Network::ConnectionCallbacks void Filter::onEvent(Network::ConnectionEvent event) { if (filter_callbacks_->upstreamHost()) { ENVOY_LOG(debug, "Called tcp filter onEvent: {} upstream {}", enumToInt(event), filter_callbacks_->upstreamHost()->address()->asString()); } else { ENVOY_LOG(debug, "Called tcp filter onEvent: {}", enumToInt(event)); } if (event == Network::ConnectionEvent::RemoteClose || event == Network::ConnectionEvent::LocalClose) { if (state_ != State::Closed && handler_) { if (report_timer_) { report_timer_->disableTimer(); } handler_->Report(this, /* is_final_report */ true); } cancelCheck(); } } bool Filter::GetSourceIpPort(std::string* str_ip, int* port) const { return Utils::GetIpPort(filter_callbacks_->connection().remoteAddress()->ip(), str_ip, port); } bool Filter::GetSourceUser(std::string* user) const { return Utils::GetSourceUser(&filter_callbacks_->connection(), user); } bool Filter::IsMutualTLS() const { return Utils::IsMutualTLS(&filter_callbacks_->connection()); } std::string Filter::GetRequestedServerName() const { return filter_callbacks->connection().requestedServerName() } bool Filter::GetDestinationIpPort(std::string* str_ip, int* port) const { if (filter_callbacks_->upstreamHost() && filter_callbacks_->upstreamHost()->address()) { return Utils::GetIpPort(filter_callbacks_->upstreamHost()->address()->ip(), str_ip, port); } return false; } bool Filter::GetDestinationUID(std::string* uid) const { if (filter_callbacks_->upstreamHost()) { return Utils::GetDestinationUID( filter_callbacks_->upstreamHost()->metadata(), uid); } return false; } void Filter::GetReportInfo( ::istio::control::tcp::ReportData::ReportInfo* data) const { data->received_bytes = received_bytes_; data->send_bytes = send_bytes_; data->duration = std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::system_clock::now() - start_time_); } std::string Filter::GetConnectionId() const { char connection_id_str[32]; StringUtil::itoa(connection_id_str, 32, filter_callbacks_->connection().id()); std::string uuid_connection_id = control_.uuid() + "-"; uuid_connection_id.append(connection_id_str); return uuid_connection_id; } void Filter::OnReportTimer() { handler_->Report(this, /* is_final_report */ false); report_timer_->enableTimer(control_.config().report_interval_ms()); } } // namespace Mixer } // namespace Tcp } // namespace Envoy
/* Copyright 2017 Istio 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 "src/envoy/tcp/mixer/filter.h" #include "common/common/enum_to_int.h" #include "src/envoy/utils/utils.h" using ::google::protobuf::util::Status; using ::istio::mixerclient::CheckResponseInfo; namespace Envoy { namespace Tcp { namespace Mixer { Filter::Filter(Control& control) : control_(control) { ENVOY_LOG(debug, "Called tcp filter: {}", __func__); } Filter::~Filter() { cancelCheck(); ENVOY_LOG(debug, "Called tcp filter : {}", __func__); } void Filter::initializeReadFilterCallbacks( Network::ReadFilterCallbacks& callbacks) { ENVOY_LOG(debug, "Called tcp filter: {}", __func__); filter_callbacks_ = &callbacks; filter_callbacks_->connection().addConnectionCallbacks(*this); start_time_ = std::chrono::system_clock::now(); } void Filter::cancelCheck() { if (state_ != State::Calling) { cancel_check_ = nullptr; } state_ = State::Closed; if (cancel_check_) { ENVOY_LOG(debug, "Cancelling check call"); cancel_check_(); cancel_check_ = nullptr; } } // Makes a Check() call to Mixer. void Filter::callCheck() { handler_ = control_.controller()->CreateRequestHandler(); state_ = State::Calling; filter_callbacks_->connection().readDisable(true); calling_check_ = true; cancel_check_ = handler_->Check(this, [this](const CheckResponseInfo& info) { completeCheck(info.response_status); }); calling_check_ = false; } // Network::ReadFilter Network::FilterStatus Filter::onData(Buffer::Instance& data, bool) { if (state_ == State::NotStarted) { // By waiting to invoke the callCheck() at onData(), the call to Mixer // will have sufficient SSL information to fill the check Request. callCheck(); } ENVOY_CONN_LOG(debug, "Called tcp filter onRead bytes: {}", filter_callbacks_->connection(), data.length()); received_bytes_ += data.length(); return state_ == State::Calling ? Network::FilterStatus::StopIteration : Network::FilterStatus::Continue; } // Network::WriteFilter Network::FilterStatus Filter::onWrite(Buffer::Instance& data, bool) { ENVOY_CONN_LOG(debug, "Called tcp filter onWrite bytes: {}", filter_callbacks_->connection(), data.length()); send_bytes_ += data.length(); return Network::FilterStatus::Continue; } Network::FilterStatus Filter::onNewConnection() { ENVOY_CONN_LOG(debug, "Called tcp filter onNewConnection: remote {}, local {}", filter_callbacks_->connection(), filter_callbacks_->connection().remoteAddress()->asString(), filter_callbacks_->connection().localAddress()->asString()); // Wait until onData() is invoked. return Network::FilterStatus::Continue; } void Filter::completeCheck(const Status& status) { ENVOY_LOG(debug, "Called tcp filter completeCheck: {}", status.ToString()); cancel_check_ = nullptr; if (state_ == State::Closed) { return; } state_ = State::Completed; filter_callbacks_->connection().readDisable(false); if (!status.ok()) { filter_callbacks_->connection().close( Network::ConnectionCloseType::NoFlush); } else { if (!calling_check_) { filter_callbacks_->continueReading(); } report_timer_ = control_.dispatcher().createTimer([this]() { OnReportTimer(); }); report_timer_->enableTimer(control_.config().report_interval_ms()); } } // Network::ConnectionCallbacks void Filter::onEvent(Network::ConnectionEvent event) { if (filter_callbacks_->upstreamHost()) { ENVOY_LOG(debug, "Called tcp filter onEvent: {} upstream {}", enumToInt(event), filter_callbacks_->upstreamHost()->address()->asString()); } else { ENVOY_LOG(debug, "Called tcp filter onEvent: {}", enumToInt(event)); } if (event == Network::ConnectionEvent::RemoteClose || event == Network::ConnectionEvent::LocalClose) { if (state_ != State::Closed && handler_) { if (report_timer_) { report_timer_->disableTimer(); } handler_->Report(this, /* is_final_report */ true); } cancelCheck(); } } bool Filter::GetSourceIpPort(std::string* str_ip, int* port) const { return Utils::GetIpPort(filter_callbacks_->connection().remoteAddress()->ip(), str_ip, port); } bool Filter::GetSourceUser(std::string* user) const { return Utils::GetSourceUser(&filter_callbacks_->connection(), user); } bool Filter::IsMutualTLS() const { return Utils::IsMutualTLS(&filter_callbacks_->connection()); } std::string Filter::GetRequestedServerName() const { return filter_callbacks_->connection().requestedServerName(); } bool Filter::GetDestinationIpPort(std::string* str_ip, int* port) const { if (filter_callbacks_->upstreamHost() && filter_callbacks_->upstreamHost()->address()) { return Utils::GetIpPort(filter_callbacks_->upstreamHost()->address()->ip(), str_ip, port); } return false; } bool Filter::GetDestinationUID(std::string* uid) const { if (filter_callbacks_->upstreamHost()) { return Utils::GetDestinationUID( filter_callbacks_->upstreamHost()->metadata(), uid); } return false; } void Filter::GetReportInfo( ::istio::control::tcp::ReportData::ReportInfo* data) const { data->received_bytes = received_bytes_; data->send_bytes = send_bytes_; data->duration = std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::system_clock::now() - start_time_); } std::string Filter::GetConnectionId() const { char connection_id_str[32]; StringUtil::itoa(connection_id_str, 32, filter_callbacks_->connection().id()); std::string uuid_connection_id = control_.uuid() + "-"; uuid_connection_id.append(connection_id_str); return uuid_connection_id; } void Filter::OnReportTimer() { handler_->Report(this, /* is_final_report */ false); report_timer_->enableTimer(control_.config().report_interval_ms()); } } // namespace Mixer } // namespace Tcp } // namespace Envoy
fix compilation errors
fix compilation errors
C++
apache-2.0
istio/proxy,lizan/proxy,istio/proxy,istio/proxy,lizan/proxy,lizan/proxy,lizan/proxy,istio/proxy
2f3f2e1a45773a478dd10b598ca915e958df3d2a
arsel.cpp
arsel.cpp
// 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 "burg.hpp" #include <algorithm> #include <cmath> #include <cstdio> #include <cstring> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <limits> #include <vector> template <class Real, class In> void process(In& in, Real& mean, std::size_t &order, std::vector<Real>& params, std::vector<Real>& sigma2e, std::vector<Real>& gain, std::vector<Real>& autocor, bool subtract_mean) { // Use burg_method to estimate a hierarchy of AR models from input data params .reserve(order*(order + 1)/2); sigma2e.reserve(order + 1); gain .reserve(order + 1); autocor.reserve(order + 1); const std::size_t N = burg_method(std::istream_iterator<Real>(in), std::istream_iterator<Real>(), mean, order, std::back_inserter(params), std::back_inserter(sigma2e), std::back_inserter(gain), std::back_inserter(autocor), subtract_mean, /* output hierarchy? */ true); // Find the best model according to CIC accounting for subtract_mean. typename std::vector<Real>::difference_type best; if (subtract_mean) { best = select_model<CIC<Burg<mean_subtracted> > >( N, 0u, sigma2e.begin(), sigma2e.end()); } else { best = select_model<CIC<Burg<mean_retained> > >( N, 0u, sigma2e.begin(), sigma2e.end()); } // Trim away everything but the best model std::copy_backward(params.begin() + best*(best+1)/2, params.begin() + best*(best+1)/2 + order, params.begin()); params.resize(best); sigma2e[0] = sigma2e[best]; sigma2e.resize(1); gain [0] = gain [best]; gain .resize(1); autocor.resize(best + 1); } // Provides nice formatting of real-valued quantities to maximum precision template<class CharT, class Traits, class Number> static std::basic_ostream<CharT,Traits>& append_real( std::basic_ostream<CharT,Traits>& os, Number value) { // Compute the displayed precision: // Magic 2 is the width of a sign and a decimal point // Magic 3 is the width of a sign, leading zero, and decimal point using std::pow; static const int append_prec = std::numeric_limits<Number>::digits10; static const int append_width = append_prec + 5; static const double fixedmax = pow(10.0, append_width - append_prec - 2 ); static const double fixedmin = pow(10.0, -(append_width - append_prec - 3)); // Format in fixed or scientific form as appropriate in given width // Care taken to not perturb observable ostream state after function call std::ios::fmtflags savedflags; std::streamsize savedprec; if (value >= fixedmin && value <= fixedmax) { savedflags = os.setf(std::ios::fixed | std::ios::right, std::ios::floatfield | std::ios::adjustfield); savedprec = os.precision(append_prec); } else { savedflags = os.setf(std::ios::scientific | std::ios::right, std::ios::floatfield | std::ios::adjustfield); savedprec = os.precision(append_width - 9); } os << std::setw(append_width) << value; os.precision(savedprec); os.setf(savedflags); return os; } // Test burg_method against synthetic data int main(int argc, char *argv[]) { using namespace std; // Process a possible --subtract-mean flag shifting arguments if needed bool subtract_mean = false; if (argc > 0 && 0 == strcmp("--subtract-mean", argv[1])) { subtract_mean = true; argv[1] = argv[0]; ++argv; --argc; } double mean; size_t order = 512; vector<double> params, sigma2e, gain, autocor; process(cin, mean, order, params, sigma2e, gain, autocor, subtract_mean); append_real(cout << "# Mean ", mean ) << endl; append_real(cout << "# \\sigma^2_\\epsilon ", sigma2e[0] ) << endl; append_real(cout << "# Gain ", gain[0] ) << endl; append_real(cout << "# \\sigma^2_x ", gain[0]*sigma2e[0]) << endl; for (size_t i = 0; i < params.size(); ++i) append_real(cout, params[i]) << endl; return 0; }
// 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 "burg.hpp" #include <algorithm> #include <cmath> #include <cstdio> #include <cstring> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <limits> #include <vector> template <class Real, class In> std::size_t process(In& in, Real& mean, std::size_t &order, std::vector<Real>& params, std::vector<Real>& sigma2e, std::vector<Real>& gain, std::vector<Real>& autocor, bool subtract_mean) { // Use burg_method to estimate a hierarchy of AR models from input data params .reserve(order*(order + 1)/2); sigma2e.reserve(order + 1); gain .reserve(order + 1); autocor.reserve(order + 1); const std::size_t N = burg_method(std::istream_iterator<Real>(in), std::istream_iterator<Real>(), mean, order, std::back_inserter(params), std::back_inserter(sigma2e), std::back_inserter(gain), std::back_inserter(autocor), subtract_mean, /* output hierarchy? */ true); // Find the best model according to CIC accounting for subtract_mean. typename std::vector<Real>::difference_type best; if (subtract_mean) { best = select_model<CIC<Burg<mean_subtracted> > >( N, 0u, sigma2e.begin(), sigma2e.end()); } else { best = select_model<CIC<Burg<mean_retained> > >( N, 0u, sigma2e.begin(), sigma2e.end()); } // Trim away everything but the best model std::copy_backward(params.begin() + best*(best+1)/2, params.begin() + best*(best+1)/2 + order, params.begin()); params.resize(best); sigma2e[0] = sigma2e[best]; sigma2e.resize(1); gain [0] = gain [best]; gain .resize(1); autocor.resize(best + 1); return N; } // Provides nice formatting of real-valued quantities to maximum precision template<class CharT, class Traits, class Number> static std::basic_ostream<CharT,Traits>& append_real( std::basic_ostream<CharT,Traits>& os, Number value) { // Compute the displayed precision: // Magic 2 is the width of a sign and a decimal point // Magic 3 is the width of a sign, leading zero, and decimal point using std::pow; static const int append_prec = std::numeric_limits<Number>::digits10; static const int append_width = append_prec + 5; static const double fixedmax = pow(10.0, append_width - append_prec - 2 ); static const double fixedmin = pow(10.0, -(append_width - append_prec - 3)); // Format in fixed or scientific form as appropriate in given width // Care taken to not perturb observable ostream state after function call std::ios::fmtflags savedflags; std::streamsize savedprec; if (value >= fixedmin && value <= fixedmax) { savedflags = os.setf(std::ios::fixed | std::ios::right, std::ios::floatfield | std::ios::adjustfield); savedprec = os.precision(append_prec); } else { savedflags = os.setf(std::ios::scientific | std::ios::right, std::ios::floatfield | std::ios::adjustfield); savedprec = os.precision(append_width - 9); } os << std::setw(append_width) << value; os.precision(savedprec); os.setf(savedflags); return os; } // Test burg_method against synthetic data int main(int argc, char *argv[]) { using namespace std; // Process a possible --subtract-mean flag shifting arguments if needed bool subtract_mean = false; if (argc > 1 && 0 == strcmp("--subtract-mean", argv[1])) { subtract_mean = true; argv[1] = argv[0]; ++argv; --argc; } double mean; size_t order = 512; vector<double> params, sigma2e, gain, autocor; size_t N = process(cin, mean, order, params, sigma2e, gain, autocor, subtract_mean); append_real(cout << "# N ", N ) << endl; append_real(cout << "# Mean ", mean ) << endl; append_real(cout << "# \\sigma^2_\\epsilon ", sigma2e[0] ) << endl; append_real(cout << "# Gain ", gain[0] ) << endl; append_real(cout << "# \\sigma^2_x ", gain[0]*sigma2e[0]) << endl; for (size_t i = 0; i < params.size(); ++i) append_real(cout, params[i]) << endl; return 0; }
correct off-by-one in argc processing
correct off-by-one in argc processing
C++
mpl-2.0
RhysU/ar,RhysU/ar
0cbe92af6c6eb150688d92de187f6777d5768368
src/core/ext/filters/client_channel/xds/xds_bootstrap.cc
src/core/ext/filters/client_channel/xds/xds_bootstrap.cc
// // Copyright 2019 gRPC authors. // // 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 <grpc/support/port_platform.h> #include "src/core/ext/filters/client_channel/xds/xds_bootstrap.h" #include <errno.h> #include <stdlib.h> #include <grpc/support/string_util.h> #include "src/core/lib/gpr/env.h" #include "src/core/lib/iomgr/load_file.h" #include "src/core/lib/slice/slice_internal.h" namespace grpc_core { std::unique_ptr<XdsBootstrap> XdsBootstrap::ReadFromFile(grpc_error** error) { grpc_core::UniquePtr<char> path(gpr_getenv("GRPC_XDS_BOOTSTRAP")); if (path == nullptr) { *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "GRPC_XDS_BOOTSTRAP env var not set"); return nullptr; } grpc_slice contents; *error = grpc_load_file(path.get(), /*add_null_terminator=*/true, &contents); if (*error != GRPC_ERROR_NONE) return nullptr; Json json = Json::Parse(StringViewFromSlice(contents), error); grpc_slice_unref_internal(contents); if (*error != GRPC_ERROR_NONE) return nullptr; return grpc_core::MakeUnique<XdsBootstrap>(std::move(json), error); } XdsBootstrap::XdsBootstrap(Json json, grpc_error** error) { if (json.type() != Json::Type::OBJECT) { *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "malformed JSON in bootstrap file"); return; } InlinedVector<grpc_error*, 1> error_list; auto it = json.mutable_object()->find("xds_servers"); if (it == json.mutable_object()->end()) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"xds_servers\" field not present")); } else if (it->second.type() != Json::Type::ARRAY) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"xds_servers\" field is not an array")); } else { grpc_error* parse_error = ParseXdsServerList(&it->second); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } it = json.mutable_object()->find("node"); if (it != json.mutable_object()->end()) { if (it->second.type() != Json::Type::OBJECT) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"node\" field is not an object")); } else { grpc_error* parse_error = ParseNode(&it->second); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } } *error = GRPC_ERROR_CREATE_FROM_VECTOR("errors parsing xds bootstrap file", &error_list); } grpc_error* XdsBootstrap::ParseXdsServerList(Json* json) { InlinedVector<grpc_error*, 1> error_list; size_t idx = 0; for (Json& child : *json->mutable_array()) { if (child.type() != Json::Type::OBJECT) { char* msg; gpr_asprintf(&msg, "array element %" PRIuPTR " is not an object", idx); error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg)); } else { grpc_error* parse_error = ParseXdsServer(&child, idx); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } } return GRPC_ERROR_CREATE_FROM_VECTOR("errors parsing \"xds_servers\" array", &error_list); } grpc_error* XdsBootstrap::ParseXdsServer(Json* json, size_t idx) { InlinedVector<grpc_error*, 1> error_list; servers_.emplace_back(); XdsServer& server = servers_[servers_.size() - 1]; auto it = json->mutable_object()->find("server_uri"); if (it == json->mutable_object()->end()) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"server_uri\" field not present")); } else if (it->second.type() != Json::Type::STRING) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"server_uri\" field is not a string")); } else { server.server_uri = std::move(*it->second.mutable_string_value()); } it = json->mutable_object()->find("channel_creds"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::ARRAY) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"channel_creds\" field is not an array")); } else { grpc_error* parse_error = ParseChannelCredsArray(&it->second, &server); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } } // Can't use GRPC_ERROR_CREATE_FROM_VECTOR() here, because the error // string is not static in this case. if (error_list.empty()) return GRPC_ERROR_NONE; char* msg; gpr_asprintf(&msg, "errors parsing index %" PRIuPTR, idx); grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); for (size_t i = 0; i < error_list.size(); ++i) { error = grpc_error_add_child(error, error_list[i]); } return error; } grpc_error* XdsBootstrap::ParseChannelCredsArray(Json* json, XdsServer* server) { InlinedVector<grpc_error*, 1> error_list; for (size_t i = 0; i < json->mutable_array()->size(); ++i) { Json& child = json->mutable_array()->at(i); if (child.type() != Json::Type::OBJECT) { char* msg; gpr_asprintf(&msg, "array element %" PRIuPTR " is not an object", i); error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg)); } else { grpc_error* parse_error = ParseChannelCreds(&child, i, server); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } } return GRPC_ERROR_CREATE_FROM_VECTOR("errors parsing \"channel_creds\" array", &error_list); } grpc_error* XdsBootstrap::ParseChannelCreds(Json* json, size_t idx, XdsServer* server) { InlinedVector<grpc_error*, 1> error_list; ChannelCreds channel_creds; auto it = json->mutable_object()->find("type"); if (it == json->mutable_object()->end()) { error_list.push_back( GRPC_ERROR_CREATE_FROM_STATIC_STRING("\"type\" field not present")); } else if (it->second.type() != Json::Type::STRING) { error_list.push_back( GRPC_ERROR_CREATE_FROM_STATIC_STRING("\"type\" field is not a string")); } else { channel_creds.type = std::move(*it->second.mutable_string_value()); } it = json->mutable_object()->find("config"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::OBJECT) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"config\" field is not an object")); } else { channel_creds.config = std::move(it->second); } } if (!channel_creds.type.empty()) { server->channel_creds.emplace_back(std::move(channel_creds)); } // Can't use GRPC_ERROR_CREATE_FROM_VECTOR() here, because the error // string is not static in this case. if (error_list.empty()) return GRPC_ERROR_NONE; char* msg; gpr_asprintf(&msg, "errors parsing index %" PRIuPTR, idx); grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); for (size_t i = 0; i < error_list.size(); ++i) { error = grpc_error_add_child(error, error_list[i]); } return error; } grpc_error* XdsBootstrap::ParseNode(Json* json) { InlinedVector<grpc_error*, 1> error_list; node_ = grpc_core::MakeUnique<Node>(); auto it = json->mutable_object()->find("id"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::STRING) { error_list.push_back( GRPC_ERROR_CREATE_FROM_STATIC_STRING("\"id\" field is not a string")); } else { node_->id = std::move(*it->second.mutable_string_value()); } } it = json->mutable_object()->find("cluster"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::STRING) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"cluster\" field is not a string")); } else { node_->cluster = std::move(*it->second.mutable_string_value()); } } it = json->mutable_object()->find("locality"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::OBJECT) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"locality\" field is not an object")); } else { grpc_error* parse_error = ParseLocality(&it->second); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } } it = json->mutable_object()->find("metadata"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::OBJECT) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"metadata\" field is not an object")); } else { node_->metadata = std::move(it->second); } } return GRPC_ERROR_CREATE_FROM_VECTOR("errors parsing \"node\" object", &error_list); } grpc_error* XdsBootstrap::ParseLocality(Json* json) { InlinedVector<grpc_error*, 1> error_list; auto it = json->mutable_object()->find("region"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::STRING) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"region\" field is not a string")); } else { node_->locality_region = std::move(*it->second.mutable_string_value()); } } it = json->mutable_object()->find("zone"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::STRING) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"zone\" field is not a string")); } else { node_->locality_zone = std::move(*it->second.mutable_string_value()); } } it = json->mutable_object()->find("subzone"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::STRING) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"subzone\" field is not a string")); } else { node_->locality_subzone = std::move(*it->second.mutable_string_value()); } } return GRPC_ERROR_CREATE_FROM_VECTOR("errors parsing \"locality\" object", &error_list); } } // namespace grpc_core
// // Copyright 2019 gRPC authors. // // 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 <grpc/support/port_platform.h> #include "src/core/ext/filters/client_channel/xds/xds_bootstrap.h" #include <errno.h> #include <stdlib.h> #include <grpc/support/string_util.h> #include "src/core/lib/gpr/env.h" #include "src/core/lib/iomgr/load_file.h" #include "src/core/lib/slice/slice_internal.h" namespace grpc_core { std::unique_ptr<XdsBootstrap> XdsBootstrap::ReadFromFile(grpc_error** error) { grpc_core::UniquePtr<char> path(gpr_getenv("GRPC_XDS_BOOTSTRAP")); if (path == nullptr) { *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "GRPC_XDS_BOOTSTRAP env var not set"); return nullptr; } grpc_slice contents; *error = grpc_load_file(path.get(), /*add_null_terminator=*/true, &contents); if (*error != GRPC_ERROR_NONE) return nullptr; Json json = Json::Parse(StringViewFromSlice(contents), error); grpc_slice_unref_internal(contents); if (*error != GRPC_ERROR_NONE) return nullptr; return grpc_core::MakeUnique<XdsBootstrap>(std::move(json), error); } XdsBootstrap::XdsBootstrap(Json json, grpc_error** error) { if (json.type() != Json::Type::OBJECT) { *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "malformed JSON in bootstrap file"); return; } InlinedVector<grpc_error*, 1> error_list; auto it = json.mutable_object()->find("xds_servers"); if (it == json.mutable_object()->end()) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"xds_servers\" field not present")); } else if (it->second.type() != Json::Type::ARRAY) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"xds_servers\" field is not an array")); } else { grpc_error* parse_error = ParseXdsServerList(&it->second); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } it = json.mutable_object()->find("node"); if (it != json.mutable_object()->end()) { if (it->second.type() != Json::Type::OBJECT) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"node\" field is not an object")); } else { grpc_error* parse_error = ParseNode(&it->second); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } } *error = GRPC_ERROR_CREATE_FROM_VECTOR("errors parsing xds bootstrap file", &error_list); } grpc_error* XdsBootstrap::ParseXdsServerList(Json* json) { InlinedVector<grpc_error*, 1> error_list; for (size_t i = 0; i < json->mutable_array()->size(); ++i) { Json& child = json->mutable_array()->at(i); if (child.type() != Json::Type::OBJECT) { char* msg; gpr_asprintf(&msg, "array element %" PRIuPTR " is not an object", i); error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg)); gpr_free(msg); } else { grpc_error* parse_error = ParseXdsServer(&child, i); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } } return GRPC_ERROR_CREATE_FROM_VECTOR("errors parsing \"xds_servers\" array", &error_list); } grpc_error* XdsBootstrap::ParseXdsServer(Json* json, size_t idx) { InlinedVector<grpc_error*, 1> error_list; servers_.emplace_back(); XdsServer& server = servers_[servers_.size() - 1]; auto it = json->mutable_object()->find("server_uri"); if (it == json->mutable_object()->end()) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"server_uri\" field not present")); } else if (it->second.type() != Json::Type::STRING) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"server_uri\" field is not a string")); } else { server.server_uri = std::move(*it->second.mutable_string_value()); } it = json->mutable_object()->find("channel_creds"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::ARRAY) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"channel_creds\" field is not an array")); } else { grpc_error* parse_error = ParseChannelCredsArray(&it->second, &server); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } } // Can't use GRPC_ERROR_CREATE_FROM_VECTOR() here, because the error // string is not static in this case. if (error_list.empty()) return GRPC_ERROR_NONE; char* msg; gpr_asprintf(&msg, "errors parsing index %" PRIuPTR, idx); grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); for (size_t i = 0; i < error_list.size(); ++i) { error = grpc_error_add_child(error, error_list[i]); } return error; } grpc_error* XdsBootstrap::ParseChannelCredsArray(Json* json, XdsServer* server) { InlinedVector<grpc_error*, 1> error_list; for (size_t i = 0; i < json->mutable_array()->size(); ++i) { Json& child = json->mutable_array()->at(i); if (child.type() != Json::Type::OBJECT) { char* msg; gpr_asprintf(&msg, "array element %" PRIuPTR " is not an object", i); error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg)); gpr_free(msg); } else { grpc_error* parse_error = ParseChannelCreds(&child, i, server); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } } return GRPC_ERROR_CREATE_FROM_VECTOR("errors parsing \"channel_creds\" array", &error_list); } grpc_error* XdsBootstrap::ParseChannelCreds(Json* json, size_t idx, XdsServer* server) { InlinedVector<grpc_error*, 1> error_list; ChannelCreds channel_creds; auto it = json->mutable_object()->find("type"); if (it == json->mutable_object()->end()) { error_list.push_back( GRPC_ERROR_CREATE_FROM_STATIC_STRING("\"type\" field not present")); } else if (it->second.type() != Json::Type::STRING) { error_list.push_back( GRPC_ERROR_CREATE_FROM_STATIC_STRING("\"type\" field is not a string")); } else { channel_creds.type = std::move(*it->second.mutable_string_value()); } it = json->mutable_object()->find("config"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::OBJECT) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"config\" field is not an object")); } else { channel_creds.config = std::move(it->second); } } if (!channel_creds.type.empty()) { server->channel_creds.emplace_back(std::move(channel_creds)); } // Can't use GRPC_ERROR_CREATE_FROM_VECTOR() here, because the error // string is not static in this case. if (error_list.empty()) return GRPC_ERROR_NONE; char* msg; gpr_asprintf(&msg, "errors parsing index %" PRIuPTR, idx); grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); for (size_t i = 0; i < error_list.size(); ++i) { error = grpc_error_add_child(error, error_list[i]); } return error; } grpc_error* XdsBootstrap::ParseNode(Json* json) { InlinedVector<grpc_error*, 1> error_list; node_ = grpc_core::MakeUnique<Node>(); auto it = json->mutable_object()->find("id"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::STRING) { error_list.push_back( GRPC_ERROR_CREATE_FROM_STATIC_STRING("\"id\" field is not a string")); } else { node_->id = std::move(*it->second.mutable_string_value()); } } it = json->mutable_object()->find("cluster"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::STRING) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"cluster\" field is not a string")); } else { node_->cluster = std::move(*it->second.mutable_string_value()); } } it = json->mutable_object()->find("locality"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::OBJECT) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"locality\" field is not an object")); } else { grpc_error* parse_error = ParseLocality(&it->second); if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error); } } it = json->mutable_object()->find("metadata"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::OBJECT) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"metadata\" field is not an object")); } else { node_->metadata = std::move(it->second); } } return GRPC_ERROR_CREATE_FROM_VECTOR("errors parsing \"node\" object", &error_list); } grpc_error* XdsBootstrap::ParseLocality(Json* json) { InlinedVector<grpc_error*, 1> error_list; auto it = json->mutable_object()->find("region"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::STRING) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"region\" field is not a string")); } else { node_->locality_region = std::move(*it->second.mutable_string_value()); } } it = json->mutable_object()->find("zone"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::STRING) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"zone\" field is not a string")); } else { node_->locality_zone = std::move(*it->second.mutable_string_value()); } } it = json->mutable_object()->find("subzone"); if (it != json->mutable_object()->end()) { if (it->second.type() != Json::Type::STRING) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "\"subzone\" field is not a string")); } else { node_->locality_subzone = std::move(*it->second.mutable_string_value()); } } return GRPC_ERROR_CREATE_FROM_VECTOR("errors parsing \"locality\" object", &error_list); } } // namespace grpc_core
Fix bugs in xds bootstrap file parsing.
Fix bugs in xds bootstrap file parsing.
C++
apache-2.0
nicolasnoble/grpc,stanley-cheung/grpc,donnadionne/grpc,donnadionne/grpc,vjpai/grpc,grpc/grpc,firebase/grpc,jtattermusch/grpc,stanley-cheung/grpc,donnadionne/grpc,donnadionne/grpc,grpc/grpc,grpc/grpc,stanley-cheung/grpc,nicolasnoble/grpc,donnadionne/grpc,ctiller/grpc,ejona86/grpc,ejona86/grpc,nicolasnoble/grpc,jtattermusch/grpc,jboeuf/grpc,grpc/grpc,jtattermusch/grpc,ctiller/grpc,donnadionne/grpc,vjpai/grpc,nicolasnoble/grpc,ejona86/grpc,jtattermusch/grpc,donnadionne/grpc,jboeuf/grpc,nicolasnoble/grpc,donnadionne/grpc,donnadionne/grpc,grpc/grpc,ctiller/grpc,jboeuf/grpc,jboeuf/grpc,nicolasnoble/grpc,firebase/grpc,jtattermusch/grpc,grpc/grpc,stanley-cheung/grpc,jboeuf/grpc,jboeuf/grpc,vjpai/grpc,ejona86/grpc,jtattermusch/grpc,stanley-cheung/grpc,firebase/grpc,firebase/grpc,ejona86/grpc,nicolasnoble/grpc,grpc/grpc,grpc/grpc,ejona86/grpc,firebase/grpc,grpc/grpc,vjpai/grpc,ctiller/grpc,ctiller/grpc,donnadionne/grpc,stanley-cheung/grpc,donnadionne/grpc,stanley-cheung/grpc,stanley-cheung/grpc,jtattermusch/grpc,ejona86/grpc,jboeuf/grpc,ctiller/grpc,jtattermusch/grpc,jboeuf/grpc,ejona86/grpc,jboeuf/grpc,ctiller/grpc,jtattermusch/grpc,jtattermusch/grpc,vjpai/grpc,firebase/grpc,grpc/grpc,ejona86/grpc,jboeuf/grpc,firebase/grpc,nicolasnoble/grpc,firebase/grpc,grpc/grpc,ctiller/grpc,firebase/grpc,donnadionne/grpc,nicolasnoble/grpc,vjpai/grpc,vjpai/grpc,grpc/grpc,firebase/grpc,ejona86/grpc,ctiller/grpc,ctiller/grpc,jtattermusch/grpc,nicolasnoble/grpc,vjpai/grpc,firebase/grpc,stanley-cheung/grpc,jtattermusch/grpc,ctiller/grpc,vjpai/grpc,jboeuf/grpc,stanley-cheung/grpc,ctiller/grpc,vjpai/grpc,vjpai/grpc,ejona86/grpc,jboeuf/grpc,nicolasnoble/grpc,vjpai/grpc,stanley-cheung/grpc,ejona86/grpc,stanley-cheung/grpc,firebase/grpc,nicolasnoble/grpc
abb74cd25b51708a97a43fedbdca2f37587ac625
tamer/dtamer.cc
tamer/dtamer.cc
/* Copyright (c) 2007-2014, Eddie Kohler * Copyright (c) 2007, Regents of the University of California * * 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, subject to the conditions * listed in the Tamer LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Tamer LICENSE file; the license in that file is * legally binding. */ #include "config.h" #include <tamer/tamer.hh> #include "dinternal.hh" #include <sys/select.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <string.h> namespace tamer { namespace { using tamerpriv::make_fd_callback; using tamerpriv::fd_callback_driver; using tamerpriv::fd_callback_fd; class driver_tamer : public driver { public: driver_tamer(); ~driver_tamer(); virtual void at_fd(int fd, int action, event<int> e); virtual void at_time(const timeval &expiry, event<> e, bool bg); virtual void at_asap(event<> e); virtual void at_preblock(event<> e); virtual void kill_fd(int fd); virtual void loop(loop_flags flags); virtual void break_loop(); private: struct fdp { inline fdp(driver_tamer*, int) { } }; union xfd_set { fd_set fds; char s[1]; uint64_t q[1]; }; enum { fdreadnow = fdread + 2, fdwritenow = fdwrite + 2 }; tamerpriv::driver_fdset<fdp> fds_; unsigned fdbound_; xfd_set* fdset_[4]; unsigned fdset_fdcap_; tamerpriv::driver_timerset timers_; tamerpriv::driver_asapset asap_; tamerpriv::driver_asapset preblock_; bool loop_state_; static void fd_disinterest(void* arg); void initialize_fdsets(); void update_fds(); int find_bad_fds(); }; driver_tamer::driver_tamer() : fdbound_(0), fdset_fdcap_(0), loop_state_(false) { fdset_[0] = fdset_[1] = fdset_[2] = fdset_[3] = (xfd_set*) 0; initialize_fdsets(); } driver_tamer::~driver_tamer() { for (int i = 0; i < 4; ++i) delete[] reinterpret_cast<char*>(fdset_[i]); } void driver_tamer::initialize_fdsets() { assert(!fdset_fdcap_); fdset_fdcap_ = sizeof(xfd_set) * 8; // make multiple of 8B assert(FD_SETSIZE <= fdset_fdcap_); assert((fdset_fdcap_ % 64) == 0); for (int i = 0; i < 4; ++i) { fdset_[i] = reinterpret_cast<xfd_set*>(new char[fdset_fdcap_ / 8]); if (i < fdreadnow) memset(fdset_[i], 0, fdset_fdcap_ / 8); } } void driver_tamer::fd_disinterest(void* arg) { driver_tamer* d = static_cast<driver_tamer*>(fd_callback_driver(arg)); d->fds_.push_change(fd_callback_fd(arg)); } void driver_tamer::at_fd(int fd, int action, event<int> e) { assert(fd >= 0); if (e && (action == 0 || action == 1)) { fds_.expand(this, fd); tamerpriv::driver_fd<fdp>& x = fds_[fd]; x.e[action] += TAMER_MOVE(e); tamerpriv::simple_event::at_trigger(x.e[action].__get_simple(), fd_disinterest, make_fd_callback(this, fd)); fds_.push_change(fd); } } void driver_tamer::kill_fd(int fd) { if (fd >= 0 && fd < fds_.size()) { tamerpriv::driver_fd<fdp> &x = fds_[fd]; x.e[0].trigger(-ECANCELED); x.e[1].trigger(-ECANCELED); fds_.push_change(fd); } } void driver_tamer::update_fds() { int fd; while ((fd = fds_.pop_change()) >= 0) { tamerpriv::driver_fd<fdp>& x = fds_[fd]; if ((unsigned) fd >= fdset_fdcap_) { unsigned ncap = fdset_fdcap_ * 2; while (ncap < (unsigned) fd) ncap *= 2; for (int acti = 0; acti < 4; ++acti) { xfd_set *x = reinterpret_cast<xfd_set*>(new char[ncap / 8]); if (acti < 2) { memcpy(x, fdset_[acti], fdset_fdcap_ / 8); memset(&x->s[fdset_fdcap_ / 8], 0, (ncap - fdset_fdcap_) / 8); } delete[] reinterpret_cast<char*>(fdset_[acti]); fdset_[acti] = x; } fdset_fdcap_ = ncap; } for (int action = 0; action < 2; ++action) if (x.e[action]) FD_SET(fd, &fdset_[action]->fds); else FD_CLR(fd, &fdset_[action]->fds); if (x.e[0] || x.e[1]) { if ((unsigned) fd >= fdbound_) fdbound_ = fd + 1; } else if ((unsigned) fd + 1 == fdbound_) do { --fdbound_; } while (fdbound_ > 0 && !fds_[fdbound_ - 1].e[0] && !fds_[fdbound_ - 1].e[1]); } } void driver_tamer::at_time(const timeval &expiry, event<> e, bool bg) { if (e) timers_.push(expiry, e.__release_simple(), bg); } void driver_tamer::at_asap(event<> e) { if (e) asap_.push(e.__release_simple()); } void driver_tamer::at_preblock(event<> e) { if (e) preblock_.push(e.__release_simple()); } void driver_tamer::loop(loop_flags flags) { if (flags == loop_forever) loop_state_ = true; again: // process asap events while (!preblock_.empty()) preblock_.pop_trigger(); run_unblocked(); // fix file descriptors if (fds_.has_change()) update_fds(); // determine timeout struct timeval to, *toptr; timers_.cull(); if (!asap_.empty() || (!timers_.empty() && !timercmp(&timers_.expiry(), &recent(), >)) || (!timers_.empty() && tamerpriv::time_type == time_virtual) || sig_any_active || has_unblocked()) { timerclear(&to); toptr = &to; } else if (!timers_.has_foreground() && fdbound_ == 0 && sig_nforeground == 0) // no foreground events! return; else if (!timers_.empty()) { timersub(&timers_.expiry(), &recent(), &to); toptr = &to; } else toptr = 0; // select! int nfds = fdbound_; if (sig_pipe[0] > nfds) nfds = sig_pipe[0] + 1; if (nfds > 0) { memcpy(fdset_[fdreadnow], fdset_[fdread], ((nfds + 63) & ~63) >> 3); memcpy(fdset_[fdwritenow], fdset_[fdwrite], ((nfds + 63) & ~63) >> 3); if (sig_pipe[0] >= 0) FD_SET(sig_pipe[0], &fdset_[fdreadnow]->fds); } if (nfds > 0 || !toptr || to.tv_sec != 0 || to.tv_usec != 0) { nfds = select(nfds, &fdset_[fdreadnow]->fds, &fdset_[fdwritenow]->fds, 0, toptr); if (nfds == -1 && errno == EBADF) nfds = find_bad_fds(); } // process signals set_recent(); if (sig_any_active) dispatch_signals(); // process fd events if (nfds > 0) { for (unsigned fd = 0; fd < fdbound_; ++fd) { tamerpriv::driver_fd<fdp> &x = fds_[fd]; for (int action = 0; action < 2; ++action) if (FD_ISSET(fd, &fdset_[action + 2]->fds) && x.e[action]) x.e[action].trigger(0); } run_unblocked(); } else if (!timers_.empty() && tamerpriv::time_type == time_virtual) tamerpriv::recent = timers_.expiry(); // process timer events while (!timers_.empty() && !timercmp(&timers_.expiry(), &recent(), >)) timers_.pop_trigger(); run_unblocked(); // process asap events while (!asap_.empty()) asap_.pop_trigger(); run_unblocked(); // check flags if (loop_state_) goto again; } int driver_tamer::find_bad_fds() { // first, combine all file descriptors from read & write unsigned nbytes = ((fdbound_ + 63) & ~63) >> 3; memcpy(fdset_[fdreadnow], fdset_[fdread], nbytes); for (unsigned i = 0; i < nbytes / 8; ++i) fdset_[fdreadnow]->q[i] |= fdset_[fdwrite]->q[i]; // use binary search to find a bad file descriptor int l = 0, r = (fdbound_ + 7) & ~7; while (r - l > 1) { int m = l + ((r - l) >> 1); memset(fdset_[fdwritenow], 0, l); memcpy(&fdset_[fdwritenow]->s[l], &fdset_[fdreadnow]->s[l], m - l); struct timeval tv = {0, 0}; int nfds = select(m << 3, &fdset_[fdwritenow]->fds, 0, 0, &tv); if (nfds == -1 && errno == EBADF) r = m; else if (nfds != -1) l = m; } // down to <= 8 file descriptors; test them one by one // clear result sets memset(fdset_[fdreadnow], 0, nbytes); memset(fdset_[fdwritenow], 0, nbytes); // set up result sets int nfds = 0; for (int f = l * 8; f != r * 8; ++f) { int fr = FD_ISSET(f, &fdset_[fdread]->fds); int fw = FD_ISSET(f, &fdset_[fdwrite]->fds); if ((fr || fw) && fcntl(f, F_GETFL) == -1 && errno == EBADF) { if (fr) FD_SET(f, &fdset_[fdreadnow]->fds); if (fw) FD_SET(f, &fdset_[fdwritenow]->fds); ++nfds; } } return nfds; } void driver_tamer::break_loop() { loop_state_ = false; } } // namespace driver *driver::make_tamer() { return new driver_tamer; } } // namespace tamer
/* Copyright (c) 2007-2014, Eddie Kohler * Copyright (c) 2007, Regents of the University of California * * 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, subject to the conditions * listed in the Tamer LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Tamer LICENSE file; the license in that file is * legally binding. */ #include "config.h" #include <tamer/tamer.hh> #include "dinternal.hh" #include <sys/select.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <string.h> namespace tamer { namespace { using tamerpriv::make_fd_callback; using tamerpriv::fd_callback_driver; using tamerpriv::fd_callback_fd; class driver_tamer : public driver { public: driver_tamer(); ~driver_tamer(); virtual void at_fd(int fd, int action, event<int> e); virtual void at_time(const timeval &expiry, event<> e, bool bg); virtual void at_asap(event<> e); virtual void at_preblock(event<> e); virtual void kill_fd(int fd); virtual void loop(loop_flags flags); virtual void break_loop(); private: struct fdp { inline fdp(driver_tamer*, int) { } }; union xfd_set { fd_set fds; char s[1]; uint64_t q[1]; }; enum { fdreadnow = fdread + 2, fdwritenow = fdwrite + 2 }; tamerpriv::driver_fdset<fdp> fds_; unsigned fdbound_; xfd_set* fdset_[4]; unsigned fdset_fdcap_; tamerpriv::driver_timerset timers_; tamerpriv::driver_asapset asap_; tamerpriv::driver_asapset preblock_; bool loop_state_; static void fd_disinterest(void* arg); void initialize_fdsets(); void update_fds(); int find_bad_fds(); }; driver_tamer::driver_tamer() : fdbound_(0), fdset_fdcap_(0), loop_state_(false) { fdset_[0] = fdset_[1] = fdset_[2] = fdset_[3] = (xfd_set*) 0; initialize_fdsets(); } driver_tamer::~driver_tamer() { for (int i = 0; i < 4; ++i) delete[] reinterpret_cast<char*>(fdset_[i]); } void driver_tamer::initialize_fdsets() { assert(!fdset_fdcap_); fdset_fdcap_ = sizeof(xfd_set) * 8; // make multiple of 8B assert(FD_SETSIZE <= fdset_fdcap_); assert((fdset_fdcap_ % 64) == 0); for (int i = 0; i < 4; ++i) { fdset_[i] = reinterpret_cast<xfd_set*>(new char[fdset_fdcap_ / 8]); if (i < fdreadnow) memset(fdset_[i], 0, fdset_fdcap_ / 8); } } void driver_tamer::fd_disinterest(void* arg) { driver_tamer* d = static_cast<driver_tamer*>(fd_callback_driver(arg)); d->fds_.push_change(fd_callback_fd(arg)); } void driver_tamer::at_fd(int fd, int action, event<int> e) { assert(fd >= 0); if (e && (action == 0 || action == 1)) { fds_.expand(this, fd); tamerpriv::driver_fd<fdp>& x = fds_[fd]; x.e[action] += TAMER_MOVE(e); tamerpriv::simple_event::at_trigger(x.e[action].__get_simple(), fd_disinterest, make_fd_callback(this, fd)); fds_.push_change(fd); } } void driver_tamer::kill_fd(int fd) { if (fd >= 0 && fd < fds_.size()) { tamerpriv::driver_fd<fdp> &x = fds_[fd]; x.e[0].trigger(-ECANCELED); x.e[1].trigger(-ECANCELED); fds_.push_change(fd); } } void driver_tamer::update_fds() { int fd; while ((fd = fds_.pop_change()) >= 0) { tamerpriv::driver_fd<fdp>& x = fds_[fd]; if ((unsigned) fd >= fdset_fdcap_) { unsigned ncap = fdset_fdcap_ * 2; while (ncap < (unsigned) fd) ncap *= 2; for (int acti = 0; acti < 4; ++acti) { xfd_set *x = reinterpret_cast<xfd_set*>(new char[ncap / 8]); if (acti < 2) { memcpy(x, fdset_[acti], fdset_fdcap_ / 8); memset(&x->s[fdset_fdcap_ / 8], 0, (ncap - fdset_fdcap_) / 8); } delete[] reinterpret_cast<char*>(fdset_[acti]); fdset_[acti] = x; } fdset_fdcap_ = ncap; } for (int action = 0; action < 2; ++action) if (x.e[action]) FD_SET(fd, &fdset_[action]->fds); else FD_CLR(fd, &fdset_[action]->fds); if (x.e[0] || x.e[1]) { if ((unsigned) fd >= fdbound_) fdbound_ = fd + 1; } else if ((unsigned) fd + 1 == fdbound_) do { --fdbound_; } while (fdbound_ > 0 && !fds_[fdbound_ - 1].e[0] && !fds_[fdbound_ - 1].e[1]); } } void driver_tamer::at_time(const timeval &expiry, event<> e, bool bg) { if (e) timers_.push(expiry, e.__release_simple(), bg); } void driver_tamer::at_asap(event<> e) { if (e) asap_.push(e.__release_simple()); } void driver_tamer::at_preblock(event<> e) { if (e) preblock_.push(e.__release_simple()); } void driver_tamer::loop(loop_flags flags) { if (flags == loop_forever) loop_state_ = true; again: // process asap events while (!preblock_.empty()) preblock_.pop_trigger(); run_unblocked(); // fix file descriptors if (fds_.has_change()) update_fds(); // determine timeout struct timeval to, *toptr; timers_.cull(); if (!asap_.empty() || (!timers_.empty() && !timercmp(&timers_.expiry(), &recent(), >)) || (!timers_.empty() && tamerpriv::time_type == time_virtual) || sig_any_active || has_unblocked()) { timerclear(&to); toptr = &to; } else if (!timers_.has_foreground() && fdbound_ == 0 && sig_nforeground == 0) // no foreground events! return; else if (!timers_.empty()) { timersub(&timers_.expiry(), &recent(), &to); toptr = &to; } else toptr = 0; // select! int nfds = fdbound_; if (sig_pipe[0] > nfds) nfds = sig_pipe[0] + 1; if (nfds > 0) { memcpy(fdset_[fdreadnow], fdset_[fdread], ((nfds + 63) & ~63) >> 3); memcpy(fdset_[fdwritenow], fdset_[fdwrite], ((nfds + 63) & ~63) >> 3); if (sig_pipe[0] >= 0) FD_SET(sig_pipe[0], &fdset_[fdreadnow]->fds); } if (nfds > 0 || !toptr || to.tv_sec != 0 || to.tv_usec != 0) { nfds = select(nfds, &fdset_[fdreadnow]->fds, &fdset_[fdwritenow]->fds, 0, toptr); if (nfds == -1 && errno == EBADF) nfds = find_bad_fds(); } // process signals set_recent(); if (sig_any_active) dispatch_signals(); // process fd events if (nfds > 0) { for (unsigned fd = 0; fd < fdbound_; ++fd) { tamerpriv::driver_fd<fdp> &x = fds_[fd]; for (int action = 0; action < 2; ++action) if (FD_ISSET(fd, &fdset_[action + 2]->fds) && x.e[action]) x.e[action].trigger(0); } run_unblocked(); } // process timer events if (!timers_.empty() && tamerpriv::time_type == time_virtual && nfds == 0) tamerpriv::recent = timers_.expiry(); while (!timers_.empty() && !timercmp(&timers_.expiry(), &recent(), >)) timers_.pop_trigger(); run_unblocked(); // process asap events while (!asap_.empty()) asap_.pop_trigger(); run_unblocked(); // check flags if (loop_state_) goto again; } int driver_tamer::find_bad_fds() { // first, combine all file descriptors from read & write unsigned nbytes = ((fdbound_ + 63) & ~63) >> 3; memcpy(fdset_[fdreadnow], fdset_[fdread], nbytes); for (unsigned i = 0; i < nbytes / 8; ++i) fdset_[fdreadnow]->q[i] |= fdset_[fdwrite]->q[i]; // use binary search to find a bad file descriptor int l = 0, r = (fdbound_ + 7) & ~7; while (r - l > 1) { int m = l + ((r - l) >> 1); memset(fdset_[fdwritenow], 0, l); memcpy(&fdset_[fdwritenow]->s[l], &fdset_[fdreadnow]->s[l], m - l); struct timeval tv = {0, 0}; int nfds = select(m << 3, &fdset_[fdwritenow]->fds, 0, 0, &tv); if (nfds == -1 && errno == EBADF) r = m; else if (nfds != -1) l = m; } // down to <= 8 file descriptors; test them one by one // clear result sets memset(fdset_[fdreadnow], 0, nbytes); memset(fdset_[fdwritenow], 0, nbytes); // set up result sets int nfds = 0; for (int f = l * 8; f != r * 8; ++f) { int fr = FD_ISSET(f, &fdset_[fdread]->fds); int fw = FD_ISSET(f, &fdset_[fdwrite]->fds); if ((fr || fw) && fcntl(f, F_GETFL) == -1 && errno == EBADF) { if (fr) FD_SET(f, &fdset_[fdreadnow]->fds); if (fw) FD_SET(f, &fdset_[fdwritenow]->fds); ++nfds; } } return nfds; } void driver_tamer::break_loop() { loop_state_ = false; } } // namespace driver *driver::make_tamer() { return new driver_tamer; } } // namespace tamer
Improve the way in which virtual time is advanced.
Improve the way in which virtual time is advanced. Fixes a bug in non-virtual time.
C++
bsd-3-clause
kohler/tamer,kohler/tamer,kohler/tamer,kohler/tamer
9079a780f4b62638b06dfa0a8d18d87903199682
src/msgpack_wrapper.cc
src/msgpack_wrapper.cc
/* * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <sstream> #include "msgpack_wrapper.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/prettywriter.h" #include "xchange/rapidjson.hpp" #include "log.h" MsgPack::MsgPack() : handler(std::make_shared<object_handle>()), obj(handler->obj) { } MsgPack::MsgPack(const std::shared_ptr<object_handle>& unpacked, msgpack::object& o) : handler(unpacked), obj(o) { } MsgPack::MsgPack(const msgpack::object& o, std::unique_ptr<msgpack::zone>&& z) : handler(std::make_shared<object_handle>(o, std::move(z))), obj(handler->obj) { } MsgPack::MsgPack(msgpack::unpacked& u) : handler(std::make_shared<object_handle>(u.get(), std::move(u.zone()))), obj(handler->obj) { } MsgPack::MsgPack(const std::string& buffer) : handler(make_handler(buffer)), obj(handler->obj) { } MsgPack::MsgPack(const rapidjson::Document& doc) : handler(make_handler(doc)), obj(handler->obj) { } MsgPack::MsgPack(MsgPack&& other) noexcept : handler(std::move(other.handler)), obj(handler->obj) { } MsgPack::MsgPack(const MsgPack& other) : handler(other.handler), obj(handler->obj) { } std::shared_ptr<MsgPack::object_handle> MsgPack::make_handler() { return std::make_shared<MsgPack::object_handle>(); } std::shared_ptr<MsgPack::object_handle> MsgPack::make_handler(const std::string& buffer) { msgpack::unpacked u; msgpack::unpack(&u, buffer.data(), buffer.size()); return std::make_shared<MsgPack::object_handle>(u.get(), msgpack::move(u.zone())); } std::shared_ptr<MsgPack::object_handle> MsgPack::make_handler(const rapidjson::Document& doc) { auto zone(std::make_unique<msgpack::zone>()); msgpack::object obj(doc, *zone.get()); return std::make_shared<MsgPack::object_handle>(obj, msgpack::move(zone)); } MsgPack MsgPack::operator[](const MsgPack& o) { if (o.obj.type == msgpack::type::STR) { return operator[](std::string(o.obj.via.str.ptr, o.obj.via.str.size)); } if (o.obj.type == msgpack::type::POSITIVE_INTEGER) { return operator[](static_cast<uint32_t>(o.obj.via.u64)); } throw msgpack::type_error(); } MsgPack MsgPack::operator[](const std::string& key) { if (obj.type == msgpack::type::NIL) { obj.type = msgpack::type::MAP; obj.via.map.ptr = nullptr; obj.via.map.size = 0; obj.via.map.m_alloc = 0; } if (obj.type == msgpack::type::MAP) { const msgpack::object_kv* pend(obj.via.map.ptr + obj.via.map.size); for (auto p = obj.via.map.ptr; p != pend; ++p) { if (p->key.type == msgpack::type::STR) { if (key.compare(std::string(p->key.via.str.ptr, p->key.via.str.size)) == 0) { return MsgPack(handler, p->val); } } } expand_map(); msgpack::object_kv* np(obj.via.map.ptr + obj.via.map.size); msgpack::detail::unpack_str(handler->user, key.data(), (uint32_t)key.size(), np->key); msgpack::detail::unpack_nil(np->val); msgpack::detail::unpack_map_item(obj, np->key, np->val); return MsgPack(handler, np->val); } throw msgpack::type_error(); } MsgPack MsgPack::operator[](uint32_t off) { if (obj.type == msgpack::type::NIL) { obj.type = msgpack::type::ARRAY; obj.via.array.ptr = nullptr; obj.via.array.size = 0; obj.via.array.m_alloc = 0; } if (obj.type == msgpack::type::ARRAY) { auto r_size = off + 1; if (obj.via.array.size < r_size) { expand_array(r_size); // Initialize new elements. const msgpack::object* npend(obj.via.array.ptr + r_size); for (auto np = obj.via.array.ptr + obj.via.array.size; np != npend; ++np) { msgpack::detail::unpack_nil(*np); msgpack::detail::unpack_array_item(obj, *np); } } return MsgPack(handler, obj.via.array.ptr[off]); } throw msgpack::type_error(); } MsgPack MsgPack::at(const MsgPack& o) const { if (o.obj.type == msgpack::type::STR) { return at(std::string(o.obj.via.str.ptr, o.obj.via.str.size)); } if (o.obj.type == msgpack::type::POSITIVE_INTEGER) { return at(static_cast<uint32_t>(o.obj.via.u64)); } throw msgpack::type_error(); } MsgPack MsgPack::at(const std::string& key) const { if (obj.type == msgpack::type::NIL) { throw std::out_of_range(key); } if (obj.type == msgpack::type::MAP) { const msgpack::object_kv* pend(obj.via.map.ptr + obj.via.map.size); for (auto p = obj.via.map.ptr; p != pend; ++p) { if (p->key.type == msgpack::type::STR) { if (key == std::string(p->key.via.str.ptr, p->key.via.str.size)) { return MsgPack(handler, p->val); } } } throw std::out_of_range(key); } throw msgpack::type_error(); } MsgPack MsgPack::at(uint32_t off) const { if (obj.type == msgpack::type::NIL) { throw std::out_of_range(std::to_string(off)); } if (obj.type == msgpack::type::ARRAY) { if (off < obj.via.array.size) { return MsgPack(handler, obj.via.array.ptr[off]); } throw std::out_of_range(std::to_string(off)); } throw msgpack::type_error(); } std::string MsgPack::key() const { if (obj.via.map.ptr->key.type == msgpack::type::STR) { return std::string(obj.via.map.ptr->key.via.str.ptr, obj.via.map.ptr->key.via.str.size); } return std::string(); } std::string MsgPack::to_json_string(bool prettify) { if (prettify) { rapidjson::Document doc = to_json(); rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); return std::string(buffer.GetString(), buffer.GetSize()); } else { std::ostringstream oss; oss << obj; return oss.str(); } } rapidjson::Document MsgPack::to_json() { rapidjson::Document doc; obj.convert(&doc); return doc; } std::string MsgPack::to_string() { msgpack::sbuffer sbuf; msgpack::pack(&sbuf, obj); return std::string(sbuf.data(), sbuf.size()); } void MsgPack::expand_map() { if (obj.via.map.m_alloc == obj.via.map.size) { size_t nsize = obj.via.map.m_alloc > 0 ? obj.via.map.m_alloc * 2 : MSGPACK_MAP_INIT_SIZE; const msgpack::object_kv* p(obj.via.map.ptr); const msgpack::object_kv* pend(obj.via.map.ptr + obj.via.map.size); msgpack::detail::unpack_map()(handler->user, nsize, obj); // Copy previous memory. for ( ; p != pend; ++p) { msgpack::detail::unpack_map_item(obj, p->key, p->val); } obj.via.map.m_alloc = nsize; } } void MsgPack::expand_array(size_t r_size) { if (obj.via.array.m_alloc < r_size) { size_t nsize = obj.via.array.m_alloc > 0 ? obj.via.array.m_alloc * 2 : MSGPACK_ARRAY_INIT_SIZE; while (nsize < r_size) { nsize *= 2; } const msgpack::object* p(obj.via.array.ptr); const msgpack::object* pend(obj.via.array.ptr + obj.via.array.size); msgpack::detail::unpack_array()(handler->user, nsize, obj); // Copy previous memory. for ( ; p != pend; ++p) { msgpack::detail::unpack_array_item(obj, *p); } obj.via.array.m_alloc = nsize; } } size_t MsgPack::capacity() const noexcept { switch (obj.type) { case msgpack::type::MAP: return obj.via.map.m_alloc; break; case msgpack::type::ARRAY: return obj.via.array.m_alloc; break; default: return 0; } } bool MsgPack::erase(const std::string& key) { if (obj.type == msgpack::type::MAP) { size_t size = obj.via.map.size; const msgpack::object_kv* pend(obj.via.map.ptr + obj.via.map.size); for (auto p = obj.via.map.ptr; p != pend; ++p) { if (p->key.type == msgpack::type::STR) { --size; if (key.compare(std::string(p->key.via.str.ptr, p->key.via.str.size)) == 0) { //msgpack::object_kv* aux; //memcpy(aux, p + 1, size*sizeof(msgpack::object)); memcpy(p, p + 1, size * sizeof(msgpack::object_kv)); --obj.via.map.size; return true; } } } return false; } throw msgpack::type_error(); } namespace msgpack { MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) { namespace adaptor { const msgpack::object& convert<MsgPack>::operator()(const msgpack::object& o, MsgPack& v) const { v = MsgPack(o, std::make_unique<msgpack::zone>()); return o; } template <typename Stream> msgpack::packer<Stream>& pack<MsgPack>::operator()(msgpack::packer<Stream>& o, const MsgPack& v) const { o << v; return o; } void object<MsgPack>::operator()(msgpack::object& o, const MsgPack& v) const { msgpack::object obj(v.obj); o.type = obj.type; o.via = obj.via; } void object_with_zone<MsgPack>::operator()(msgpack::object::with_zone& o, const MsgPack& v) const { msgpack::object obj(v.obj, o.zone); o.type = obj.type; o.via = obj.via; } } // namespace adaptor } // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) } // namespace msgpack
/* * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <sstream> #include "msgpack_wrapper.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/prettywriter.h" #include "xchange/rapidjson.hpp" #include "log.h" MsgPack::MsgPack() : handler(std::make_shared<object_handle>()), obj(handler->obj) { } MsgPack::MsgPack(const std::shared_ptr<object_handle>& unpacked, msgpack::object& o) : handler(unpacked), obj(o) { } MsgPack::MsgPack(const msgpack::object& o, std::unique_ptr<msgpack::zone>&& z) : handler(std::make_shared<object_handle>(o, std::move(z))), obj(handler->obj) { } MsgPack::MsgPack(msgpack::unpacked& u) : handler(std::make_shared<object_handle>(u.get(), std::move(u.zone()))), obj(handler->obj) { } MsgPack::MsgPack(const std::string& buffer) : handler(make_handler(buffer)), obj(handler->obj) { } MsgPack::MsgPack(const rapidjson::Document& doc) : handler(make_handler(doc)), obj(handler->obj) { } MsgPack::MsgPack(MsgPack&& other) noexcept : handler(std::move(other.handler)), obj(handler->obj) { } MsgPack::MsgPack(const MsgPack& other) : handler(other.handler), obj(handler->obj) { } std::shared_ptr<MsgPack::object_handle> MsgPack::make_handler() { return std::make_shared<MsgPack::object_handle>(); } std::shared_ptr<MsgPack::object_handle> MsgPack::make_handler(const std::string& buffer) { msgpack::unpacked u; msgpack::unpack(&u, buffer.data(), buffer.size()); return std::make_shared<MsgPack::object_handle>(u.get(), msgpack::move(u.zone())); } std::shared_ptr<MsgPack::object_handle> MsgPack::make_handler(const rapidjson::Document& doc) { auto zone(std::make_unique<msgpack::zone>()); msgpack::object obj(doc, *zone.get()); return std::make_shared<MsgPack::object_handle>(obj, msgpack::move(zone)); } MsgPack MsgPack::operator[](const MsgPack& o) { if (o.obj.type == msgpack::type::STR) { return operator[](std::string(o.obj.via.str.ptr, o.obj.via.str.size)); } if (o.obj.type == msgpack::type::POSITIVE_INTEGER) { return operator[](static_cast<uint32_t>(o.obj.via.u64)); } throw msgpack::type_error(); } MsgPack MsgPack::operator[](const std::string& key) { if (obj.type == msgpack::type::NIL) { obj.type = msgpack::type::MAP; obj.via.map.ptr = nullptr; obj.via.map.size = 0; obj.via.map.m_alloc = 0; } if (obj.type == msgpack::type::MAP) { const msgpack::object_kv* pend(obj.via.map.ptr + obj.via.map.size); for (auto p = obj.via.map.ptr; p != pend; ++p) { if (p->key.type == msgpack::type::STR) { if (key.compare(std::string(p->key.via.str.ptr, p->key.via.str.size)) == 0) { return MsgPack(handler, p->val); } } } expand_map(); msgpack::object_kv* np(obj.via.map.ptr + obj.via.map.size); msgpack::detail::unpack_str(handler->user, key.data(), (uint32_t)key.size(), np->key); msgpack::detail::unpack_nil(np->val); msgpack::detail::unpack_map_item(obj, np->key, np->val); return MsgPack(handler, np->val); } throw msgpack::type_error(); } MsgPack MsgPack::operator[](uint32_t off) { if (obj.type == msgpack::type::NIL) { obj.type = msgpack::type::ARRAY; obj.via.array.ptr = nullptr; obj.via.array.size = 0; obj.via.array.m_alloc = 0; } if (obj.type == msgpack::type::ARRAY) { auto r_size = off + 1; if (obj.via.array.size < r_size) { expand_array(r_size); // Initialize new elements. const msgpack::object* npend(obj.via.array.ptr + r_size); for (auto np = obj.via.array.ptr + obj.via.array.size; np != npend; ++np) { msgpack::detail::unpack_nil(*np); msgpack::detail::unpack_array_item(obj, *np); } } return MsgPack(handler, obj.via.array.ptr[off]); } throw msgpack::type_error(); } MsgPack MsgPack::at(const MsgPack& o) const { if (o.obj.type == msgpack::type::STR) { return at(std::string(o.obj.via.str.ptr, o.obj.via.str.size)); } if (o.obj.type == msgpack::type::POSITIVE_INTEGER) { return at(static_cast<uint32_t>(o.obj.via.u64)); } throw msgpack::type_error(); } MsgPack MsgPack::at(const std::string& key) const { if (obj.type == msgpack::type::NIL) { throw std::out_of_range(key); } if (obj.type == msgpack::type::MAP) { const msgpack::object_kv* pend(obj.via.map.ptr + obj.via.map.size); for (auto p = obj.via.map.ptr; p != pend; ++p) { if (p->key.type == msgpack::type::STR) { if (key == std::string(p->key.via.str.ptr, p->key.via.str.size)) { return MsgPack(handler, p->val); } } } throw std::out_of_range(key); } throw msgpack::type_error(); } MsgPack MsgPack::at(uint32_t off) const { if (obj.type == msgpack::type::NIL) { throw std::out_of_range(std::to_string(off)); } if (obj.type == msgpack::type::ARRAY) { if (off < obj.via.array.size) { return MsgPack(handler, obj.via.array.ptr[off]); } throw std::out_of_range(std::to_string(off)); } throw msgpack::type_error(); } std::string MsgPack::key() const { if (obj.via.map.ptr->key.type == msgpack::type::STR) { return std::string(obj.via.map.ptr->key.via.str.ptr, obj.via.map.ptr->key.via.str.size); } return std::string(); } std::string MsgPack::to_json_string(bool prettify) { if (prettify) { rapidjson::Document doc = to_json(); rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); return std::string(buffer.GetString(), buffer.GetSize()); } else { std::ostringstream oss; oss << obj; return oss.str(); } } rapidjson::Document MsgPack::to_json() { rapidjson::Document doc; obj.convert(&doc); return doc; } std::string MsgPack::to_string() { msgpack::sbuffer sbuf; msgpack::pack(&sbuf, obj); return std::string(sbuf.data(), sbuf.size()); } void MsgPack::expand_map() { if (obj.via.map.m_alloc == obj.via.map.size) { size_t nsize = obj.via.map.m_alloc > 0 ? obj.via.map.m_alloc * 2 : MSGPACK_MAP_INIT_SIZE; const msgpack::object_kv* p(obj.via.map.ptr); const msgpack::object_kv* pend(obj.via.map.ptr + obj.via.map.size); msgpack::detail::unpack_map()(handler->user, nsize, obj); // Copy previous memory. for ( ; p != pend; ++p) { msgpack::detail::unpack_map_item(obj, p->key, p->val); } obj.via.map.m_alloc = nsize; } } void MsgPack::expand_array(size_t r_size) { if (obj.via.array.m_alloc < r_size) { size_t nsize = obj.via.array.m_alloc > 0 ? obj.via.array.m_alloc * 2 : MSGPACK_ARRAY_INIT_SIZE; while (nsize < r_size) { nsize *= 2; } const msgpack::object* p(obj.via.array.ptr); const msgpack::object* pend(obj.via.array.ptr + obj.via.array.size); msgpack::detail::unpack_array()(handler->user, nsize, obj); // Copy previous memory. for ( ; p != pend; ++p) { msgpack::detail::unpack_array_item(obj, *p); } obj.via.array.m_alloc = nsize; } } size_t MsgPack::capacity() const noexcept { switch (obj.type) { case msgpack::type::MAP: return obj.via.map.m_alloc; break; case msgpack::type::ARRAY: return obj.via.array.m_alloc; break; default: return 0; } } bool MsgPack::erase(const std::string& key) { if (obj.type == msgpack::type::MAP) { size_t size = obj.via.map.size; const msgpack::object_kv* pend(obj.via.map.ptr + obj.via.map.size); for (auto p = obj.via.map.ptr; p != pend; ++p) { if (p->key.type == msgpack::type::STR) { --size; if (key.compare(std::string(p->key.via.str.ptr, p->key.via.str.size)) == 0) { memcpy(p, p + 1, size * sizeof(msgpack::object_kv)); --obj.via.map.size; return true; } } } return false; } throw msgpack::type_error(); } namespace msgpack { MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) { namespace adaptor { const msgpack::object& convert<MsgPack>::operator()(const msgpack::object& o, MsgPack& v) const { v = MsgPack(o, std::make_unique<msgpack::zone>()); return o; } template <typename Stream> msgpack::packer<Stream>& pack<MsgPack>::operator()(msgpack::packer<Stream>& o, const MsgPack& v) const { o << v; return o; } void object<MsgPack>::operator()(msgpack::object& o, const MsgPack& v) const { msgpack::object obj(v.obj); o.type = obj.type; o.via = obj.via; } void object_with_zone<MsgPack>::operator()(msgpack::object::with_zone& o, const MsgPack& v) const { msgpack::object obj(v.obj, o.zone); o.type = obj.type; o.via = obj.via; } } // namespace adaptor } // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) } // namespace msgpack
Format and delete comment
Format and delete comment
C++
mit
Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand
42420320ac7a221cc78ecb2795bb8b6f2df53c18
src/mtac/Optimizer.cpp
src/mtac/Optimizer.cpp
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <unordered_set> #include <boost/variant.hpp> #include <boost/utility/enable_if.hpp> #include "mtac/Optimizer.hpp" #include "mtac/Program.hpp" #include "mtac/Utils.hpp" //The data-flow problems #include "mtac/GlobalOptimizations.hpp" #include "mtac/ConstantPropagationProblem.hpp" //The optimization visitors #include "mtac/ArithmeticIdentities.hpp" #include "mtac/ReduceInStrength.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/ConstantPropagation.hpp" #include "mtac/CopyPropagation.hpp" #include "mtac/RemoveAssign.hpp" #include "mtac/RemoveMultipleAssign.hpp" #include "mtac/MathPropagation.hpp" #include "Utils.hpp" #include "VisitorUtils.hpp" #include "StringPool.hpp" #include "DebugStopWatch.hpp" using namespace eddic; namespace { static const bool DebugPerf = false; static const bool Debug = false; template<typename Visitor> bool apply_to_all(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("apply to all clean"); Visitor visitor; for(auto& function : program->functions){ for(auto& block : function->getBasicBlocks()){ visit_each(visitor, block->statements); } } return visitor.optimized; } template<typename Visitor> bool apply_to_basic_blocks(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("apply to basic blocks"); bool optimized = false; for(auto& function : program->functions){ for(auto& block : function->getBasicBlocks()){ Visitor visitor; visit_each(visitor, block->statements); optimized |= visitor.optimized; } } return optimized; } template<typename Visitor> typename boost::disable_if<boost::is_void<typename Visitor::result_type>, bool>::type apply_to_basic_blocks_two_pass(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("apply to basic blocks two phase"); bool optimized = false; for(auto& function : program->functions){ for(auto& block : function->getBasicBlocks()){ Visitor visitor; visitor.pass = mtac::Pass::DATA_MINING; //In the first pass, don't care about the return value visit_each(visitor, block->statements); visitor.pass = mtac::Pass::OPTIMIZE; auto it = block->statements.begin(); auto end = block->statements.end(); block->statements.erase( std::remove_if(it, end, [&](mtac::Statement& s){return !visit(visitor, s); }), end); optimized |= visitor.optimized; } } return optimized; } template<typename Visitor> inline typename boost::enable_if<boost::is_void<typename Visitor::result_type>, bool>::type apply_to_basic_blocks_two_pass(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("apply to basic blocks two phase"); bool optimized = false; for(auto& function : program->functions){ for(auto& block : function->getBasicBlocks()){ Visitor visitor; visitor.pass = mtac::Pass::DATA_MINING; visit_each(visitor, block->statements); visitor.pass = mtac::Pass::OPTIMIZE; visit_each(visitor, block->statements); optimized |= visitor.optimized; } } return optimized; } bool remove_dead_basic_blocks(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("Remove dead basic blocks"); bool optimized = false; for(auto& function : program->functions){ std::unordered_set<std::shared_ptr<mtac::BasicBlock>> usage; auto& blocks = function->getBasicBlocks(); unsigned int before = blocks.size(); auto it = blocks.begin(); auto end = blocks.end(); while(it != end){ auto& block = *it; usage.insert(block); if(block->statements.size() > 0){ auto& last = block->statements[block->statements.size() - 1]; if(auto* ptr = boost::get<std::shared_ptr<mtac::Goto>>(&last)){ if(usage.find((*ptr)->block) == usage.end()){ it = std::find(blocks.begin(), blocks.end(), (*ptr)->block); continue; } } else if(auto* ptr = boost::get<std::shared_ptr<mtac::IfFalse>>(&last)){ usage.insert((*ptr)->block); } else if(auto* ptr = boost::get<std::shared_ptr<mtac::If>>(&last)){ usage.insert((*ptr)->block); } } ++it; } //The ENTRY and EXIT blocks should not be removed usage.insert(blocks.front()); usage.insert(blocks.back()); it = blocks.begin(); end = blocks.end(); blocks.erase( std::remove_if(it, end, [&](std::shared_ptr<mtac::BasicBlock>& b){ return usage.find(b) == usage.end(); }), end); if(blocks.size() < before){ optimized = true; } } return optimized; } bool optimize_branches(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("Optimize branches"); bool optimized = false; for(auto& function : program->functions){ for(auto& block : function->getBasicBlocks()){ for(auto& statement : block->statements){ if(auto* ptr = boost::get<std::shared_ptr<mtac::IfFalse>>(&statement)){ if(!(*ptr)->op && boost::get<int>(&(*ptr)->arg1)){ int value = boost::get<int>((*ptr)->arg1); if(value == 0){ auto goto_ = std::make_shared<mtac::Goto>(); goto_->label = (*ptr)->label; goto_->block = (*ptr)->block; statement = goto_; optimized = true; } else if(value == 1){ statement = std::make_shared<mtac::NoOp>(); optimized = true; } } } else if(auto* ptr = boost::get<std::shared_ptr<mtac::If>>(&statement)){ if(!(*ptr)->op && boost::get<int>(&(*ptr)->arg1)){ int value = boost::get<int>((*ptr)->arg1); if(value == 0){ statement = std::make_shared<mtac::NoOp>(); optimized = true; } else if(value == 1){ auto goto_ = std::make_shared<mtac::Goto>(); goto_->label = (*ptr)->label; goto_->block = (*ptr)->block; statement = goto_; optimized = true; } } } } } } return optimized; } template<typename T> bool isParam(T& statement){ return boost::get<std::shared_ptr<mtac::Param>>(&statement); } bool optimize_concat(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> pool){ DebugStopWatch<DebugPerf> timer("Optimize concat"); bool optimized = false; for(auto& function : program->functions){ auto& blocks = function->getBasicBlocks(); auto it = blocks.begin(); auto end = blocks.end(); auto previous = it; //we start at 1 because the first block cannot start with a call to concat ++it; while(it != end){ auto block = *it; if(block->statements.size() > 0){ if(auto* ptr = boost::get<std::shared_ptr<mtac::Call>>(&block->statements[0])){ if((*ptr)->function == "concat"){ //The params are on the previous block auto& paramBlock = *previous; //Must have at least four params if(paramBlock->statements.size() >= 4){ auto size = paramBlock->statements.size(); auto& statement1 = paramBlock->statements[size - 4]; auto& statement2 = paramBlock->statements[size - 3]; auto& statement3 = paramBlock->statements[size - 2]; auto& statement4 = paramBlock->statements[size - 1]; if(isParam(statement1) && isParam(statement2) && isParam(statement3) && isParam(statement4)){ auto& quadruple1 = boost::get<std::shared_ptr<mtac::Param>>(statement1); auto& quadruple3 = boost::get<std::shared_ptr<mtac::Param>>(statement3); if(boost::get<std::string>(&quadruple1->arg) && boost::get<std::string>(&quadruple3->arg)){ std::string firstValue = pool->value(boost::get<std::string>(quadruple1->arg)); std::string secondValue = pool->value(boost::get<std::string>(quadruple3->arg)); //Remove the quotes firstValue.resize(firstValue.size() - 1); secondValue.erase(0, 1); //Compute the reuslt of the concatenation std::string result = firstValue + secondValue; std::string label = pool->label(result); int length = result.length() - 2; auto ret1 = (*ptr)->return_; auto ret2 = (*ptr)->return2_; //remove the call to concat block->statements.erase(block->statements.begin()); //Insert assign with the concatenated value block->statements.insert(block->statements.begin(), std::make_shared<mtac::Quadruple>(ret1, label, mtac::Operator::ASSIGN)); block->statements.insert(block->statements.begin()+1, std::make_shared<mtac::Quadruple>(ret2, length, mtac::Operator::ASSIGN)); //Remove the four params from the previous basic block paramBlock->statements.erase(paramBlock->statements.end() - 4, paramBlock->statements.end()); optimized = true; } } } } } } previous = it; ++it; } } return optimized; } bool remove_needless_jumps(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("Remove needless jumps"); bool optimized = false; for(auto& function : program->functions){ auto& blocks = function->getBasicBlocks(); auto it = blocks.begin(); auto end = blocks.end(); while(it != end){ auto& block = *it; if(block->statements.size() > 0){ auto& last = block->statements[block->statements.size() - 1]; if(auto* ptr = boost::get<std::shared_ptr<mtac::Goto>>(&last)){ auto next = it; ++next; //If the target block is the next in the list if((*ptr)->block == *next){ block->statements.pop_back(); optimized = true; } } } ++it; } } return optimized; } bool merge_basic_blocks(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("Merge basic blocks"); bool optimized = false; for(auto& function : program->functions){ std::unordered_set<std::shared_ptr<mtac::BasicBlock>> usage; computeBlockUsage(function, usage); auto& blocks = function->getBasicBlocks(); auto it = blocks.begin(); //The ENTRY Basic block should not been merged ++it; while(it != blocks.end()){ auto& block = *it; if(block->statements.size() > 0){ auto& last = block->statements[block->statements.size() - 1]; bool merge = false; if(boost::get<std::shared_ptr<mtac::Quadruple>>(&last)){ merge = true; } else if(auto* ptr = boost::get<std::shared_ptr<mtac::Call>>(&last)){ merge = safe(*ptr); } else if(boost::get<std::shared_ptr<mtac::NoOp>>(&last)){ merge = true; } auto next = it; ++next; if(merge && next != blocks.end() && (*next)->index != -2){ //Only if the next block is not used because we will remove its label if(usage.find(*next) == usage.end()){ if(auto* ptr = boost::get<std::shared_ptr<mtac::Call>>(&(*(*next)->statements.begin()))){ if(!safe(*ptr)){ ++it; continue; } } block->statements.insert(block->statements.end(), (*next)->statements.begin(), (*next)->statements.end()); it = blocks.erase(next); optimized = true; --it; continue; } } } ++it; } } return optimized; } template<bool Enabled, int i> bool debug(bool b){ if(Enabled){ if(b){ std::cout << "optimization " << i << " returned true" << std::endl; } else { std::cout << "optimization " << i << " returned false" << std::endl; } } return b; } template<typename Problem> bool data_flow_optimization(std::shared_ptr<mtac::Program> program){ Problem problem; bool optimized = false; for(auto& function : program->functions){ auto graph = mtac::build_control_flow_graph(function); auto results = mtac::data_flow(graph, problem); //Once the data-flow problem is fixed, statements can be optimized for(auto& block : function->getBasicBlocks()){ for(auto& statement : block->statements){ optimized |= problem.optimize(statement, results); } } } return optimized; } } void mtac::Optimizer::optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> pool) const { bool optimized; do { optimized = false; //Optimize using arithmetic identities optimized |= debug<Debug, 1>(apply_to_all<ArithmeticIdentities>(program)); //Reduce arithtmetic instructions in strength optimized |= debug<Debug, 2>(apply_to_all<ReduceInStrength>(program)); //Constant folding optimized |= debug<Debug, 3>(apply_to_all<ConstantFolding>(program)); //Global constant propagation optimized |= debug<Debug, 4>(data_flow_optimization<ConstantPropagationProblem>(program)); //Constant propagation optimized |= debug<Debug, 5>(apply_to_basic_blocks<ConstantPropagation>(program)); //Offset Constant propagation optimized |= debug<Debug, 6>(apply_to_basic_blocks<OffsetConstantPropagation>(program)); //Copy propagation optimized |= debug<Debug, 7>(apply_to_basic_blocks<CopyPropagation>(program)); //Offset Copy propagation optimized |= debug<Debug, 8>(apply_to_basic_blocks<OffsetCopyPropagation>(program)); //Propagate math optimized |= debug<Debug, 9>(apply_to_basic_blocks_two_pass<MathPropagation>(program)); //Remove unused assignations optimized |= debug<Debug, 10>(apply_to_basic_blocks_two_pass<RemoveAssign>(program)); //Remove unused assignations optimized |= debug<Debug, 11>(apply_to_basic_blocks_two_pass<RemoveMultipleAssign>(program)); //Optimize branches optimized |= debug<Debug, 12>(optimize_branches(program)); //Optimize concatenations optimized |= debug<Debug, 13>(optimize_concat(program, pool)); //Remove dead basic blocks (unreachable code) optimized |= debug<Debug, 14>(remove_dead_basic_blocks(program)); //Remove needless jumps optimized |= debug<Debug, 15>(remove_needless_jumps(program)); //Merge basic blocks optimized |= debug<Debug, 16>(merge_basic_blocks(program)); } while (optimized); }
//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <unordered_set> #include <boost/variant.hpp> #include <boost/utility/enable_if.hpp> #include "mtac/Optimizer.hpp" #include "mtac/Program.hpp" #include "mtac/Utils.hpp" //The data-flow problems #include "mtac/GlobalOptimizations.hpp" #include "mtac/ConstantPropagationProblem.hpp" //The optimization visitors #include "mtac/ArithmeticIdentities.hpp" #include "mtac/ReduceInStrength.hpp" #include "mtac/ConstantFolding.hpp" #include "mtac/ConstantPropagation.hpp" #include "mtac/CopyPropagation.hpp" #include "mtac/RemoveAssign.hpp" #include "mtac/RemoveMultipleAssign.hpp" #include "mtac/MathPropagation.hpp" #include "Utils.hpp" #include "VisitorUtils.hpp" #include "StringPool.hpp" #include "DebugStopWatch.hpp" using namespace eddic; namespace { static const bool DebugPerf = false; static const bool Debug = false; template<typename Visitor> bool apply_to_all(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("apply to all clean"); Visitor visitor; for(auto& function : program->functions){ for(auto& block : function->getBasicBlocks()){ visit_each(visitor, block->statements); } } return visitor.optimized; } template<typename Visitor> bool apply_to_basic_blocks(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("apply to basic blocks"); bool optimized = false; for(auto& function : program->functions){ for(auto& block : function->getBasicBlocks()){ Visitor visitor; visit_each(visitor, block->statements); optimized |= visitor.optimized; } } return optimized; } template<typename Visitor> typename boost::disable_if<boost::is_void<typename Visitor::result_type>, bool>::type apply_to_basic_blocks_two_pass(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("apply to basic blocks two phase"); bool optimized = false; for(auto& function : program->functions){ for(auto& block : function->getBasicBlocks()){ Visitor visitor; visitor.pass = mtac::Pass::DATA_MINING; //In the first pass, don't care about the return value visit_each(visitor, block->statements); visitor.pass = mtac::Pass::OPTIMIZE; auto it = block->statements.begin(); auto end = block->statements.end(); block->statements.erase( std::remove_if(it, end, [&](mtac::Statement& s){return !visit(visitor, s); }), end); optimized |= visitor.optimized; } } return optimized; } template<typename Visitor> inline typename boost::enable_if<boost::is_void<typename Visitor::result_type>, bool>::type apply_to_basic_blocks_two_pass(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("apply to basic blocks two phase"); bool optimized = false; for(auto& function : program->functions){ for(auto& block : function->getBasicBlocks()){ Visitor visitor; visitor.pass = mtac::Pass::DATA_MINING; visit_each(visitor, block->statements); visitor.pass = mtac::Pass::OPTIMIZE; visit_each(visitor, block->statements); optimized |= visitor.optimized; } } return optimized; } bool remove_dead_basic_blocks(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("Remove dead basic blocks"); bool optimized = false; for(auto& function : program->functions){ std::unordered_set<std::shared_ptr<mtac::BasicBlock>> usage; auto& blocks = function->getBasicBlocks(); unsigned int before = blocks.size(); auto it = blocks.begin(); auto end = blocks.end(); while(it != end){ auto& block = *it; usage.insert(block); if(block->statements.size() > 0){ auto& last = block->statements[block->statements.size() - 1]; if(auto* ptr = boost::get<std::shared_ptr<mtac::Goto>>(&last)){ if(usage.find((*ptr)->block) == usage.end()){ it = std::find(blocks.begin(), blocks.end(), (*ptr)->block); continue; } } else if(auto* ptr = boost::get<std::shared_ptr<mtac::IfFalse>>(&last)){ usage.insert((*ptr)->block); } else if(auto* ptr = boost::get<std::shared_ptr<mtac::If>>(&last)){ usage.insert((*ptr)->block); } } ++it; } //The ENTRY and EXIT blocks should not be removed usage.insert(blocks.front()); usage.insert(blocks.back()); it = blocks.begin(); end = blocks.end(); blocks.erase( std::remove_if(it, end, [&](std::shared_ptr<mtac::BasicBlock>& b){ return usage.find(b) == usage.end(); }), end); if(blocks.size() < before){ optimized = true; } } return optimized; } bool optimize_branches(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("Optimize branches"); bool optimized = false; for(auto& function : program->functions){ for(auto& block : function->getBasicBlocks()){ for(auto& statement : block->statements){ if(auto* ptr = boost::get<std::shared_ptr<mtac::IfFalse>>(&statement)){ if(!(*ptr)->op && boost::get<int>(&(*ptr)->arg1)){ int value = boost::get<int>((*ptr)->arg1); if(value == 0){ auto goto_ = std::make_shared<mtac::Goto>(); goto_->label = (*ptr)->label; goto_->block = (*ptr)->block; statement = goto_; optimized = true; } else if(value == 1){ statement = std::make_shared<mtac::NoOp>(); optimized = true; } } } else if(auto* ptr = boost::get<std::shared_ptr<mtac::If>>(&statement)){ if(!(*ptr)->op && boost::get<int>(&(*ptr)->arg1)){ int value = boost::get<int>((*ptr)->arg1); if(value == 0){ statement = std::make_shared<mtac::NoOp>(); optimized = true; } else if(value == 1){ auto goto_ = std::make_shared<mtac::Goto>(); goto_->label = (*ptr)->label; goto_->block = (*ptr)->block; statement = goto_; optimized = true; } } } } } } return optimized; } template<typename T> bool isParam(T& statement){ return boost::get<std::shared_ptr<mtac::Param>>(&statement); } bool optimize_concat(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> pool){ DebugStopWatch<DebugPerf> timer("Optimize concat"); bool optimized = false; for(auto& function : program->functions){ auto& blocks = function->getBasicBlocks(); auto it = blocks.begin(); auto end = blocks.end(); auto previous = it; //we start at 1 because the first block cannot start with a call to concat ++it; while(it != end){ auto block = *it; if(block->statements.size() > 0){ if(auto* ptr = boost::get<std::shared_ptr<mtac::Call>>(&block->statements[0])){ if((*ptr)->function == "concat"){ //The params are on the previous block auto& paramBlock = *previous; //Must have at least four params if(paramBlock->statements.size() >= 4){ auto size = paramBlock->statements.size(); auto& statement1 = paramBlock->statements[size - 4]; auto& statement2 = paramBlock->statements[size - 3]; auto& statement3 = paramBlock->statements[size - 2]; auto& statement4 = paramBlock->statements[size - 1]; if(isParam(statement1) && isParam(statement2) && isParam(statement3) && isParam(statement4)){ auto& quadruple1 = boost::get<std::shared_ptr<mtac::Param>>(statement1); auto& quadruple3 = boost::get<std::shared_ptr<mtac::Param>>(statement3); if(boost::get<std::string>(&quadruple1->arg) && boost::get<std::string>(&quadruple3->arg)){ std::string firstValue = pool->value(boost::get<std::string>(quadruple1->arg)); std::string secondValue = pool->value(boost::get<std::string>(quadruple3->arg)); //Remove the quotes firstValue.resize(firstValue.size() - 1); secondValue.erase(0, 1); //Compute the reuslt of the concatenation std::string result = firstValue + secondValue; std::string label = pool->label(result); int length = result.length() - 2; auto ret1 = (*ptr)->return_; auto ret2 = (*ptr)->return2_; //remove the call to concat block->statements.erase(block->statements.begin()); //Insert assign with the concatenated value block->statements.insert(block->statements.begin(), std::make_shared<mtac::Quadruple>(ret1, label, mtac::Operator::ASSIGN)); block->statements.insert(block->statements.begin()+1, std::make_shared<mtac::Quadruple>(ret2, length, mtac::Operator::ASSIGN)); //Remove the four params from the previous basic block paramBlock->statements.erase(paramBlock->statements.end() - 4, paramBlock->statements.end()); optimized = true; } } } } } } previous = it; ++it; } } return optimized; } bool remove_needless_jumps(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("Remove needless jumps"); bool optimized = false; for(auto& function : program->functions){ auto& blocks = function->getBasicBlocks(); auto it = blocks.begin(); auto end = blocks.end(); while(it != end){ auto& block = *it; if(block->statements.size() > 0){ auto& last = block->statements[block->statements.size() - 1]; if(auto* ptr = boost::get<std::shared_ptr<mtac::Goto>>(&last)){ auto next = it; ++next; //If the target block is the next in the list if((*ptr)->block == *next){ block->statements.pop_back(); optimized = true; } } } ++it; } } return optimized; } bool merge_basic_blocks(std::shared_ptr<mtac::Program> program){ DebugStopWatch<DebugPerf> timer("Merge basic blocks"); bool optimized = false; for(auto& function : program->functions){ std::unordered_set<std::shared_ptr<mtac::BasicBlock>> usage; computeBlockUsage(function, usage); auto& blocks = function->getBasicBlocks(); auto it = blocks.begin(); //The ENTRY Basic block should not been merged ++it; while(it != blocks.end()){ auto& block = *it; if(block->statements.size() > 0){ auto& last = block->statements[block->statements.size() - 1]; bool merge = false; if(boost::get<std::shared_ptr<mtac::Quadruple>>(&last)){ merge = true; } else if(auto* ptr = boost::get<std::shared_ptr<mtac::Call>>(&last)){ merge = safe(*ptr); } else if(boost::get<std::shared_ptr<mtac::NoOp>>(&last)){ merge = true; } auto next = it; ++next; if(merge && next != blocks.end() && (*next)->index != -2){ //Only if the next block is not used because we will remove its label if(usage.find(*next) == usage.end()){ if(auto* ptr = boost::get<std::shared_ptr<mtac::Call>>(&(*(*next)->statements.begin()))){ if(!safe(*ptr)){ ++it; continue; } } block->statements.insert(block->statements.end(), (*next)->statements.begin(), (*next)->statements.end()); it = blocks.erase(next); optimized = true; --it; continue; } } } ++it; } } return optimized; } template<bool Enabled, int i> bool debug(bool b){ if(Enabled){ if(b){ std::cout << "optimization " << i << " returned true" << std::endl; } else { std::cout << "optimization " << i << " returned false" << std::endl; } } return b; } template<typename Problem> bool data_flow_optimization(std::shared_ptr<mtac::Program> program){ Problem problem; bool optimized = false; for(auto& function : program->functions){ auto graph = mtac::build_control_flow_graph(function); auto results = mtac::data_flow(graph, problem); //Once the data-flow problem is fixed, statements can be optimized for(auto& block : function->getBasicBlocks()){ for(auto& statement : block->statements){ optimized |= problem.optimize(statement, results); } } } return optimized; } } void mtac::Optimizer::optimize(std::shared_ptr<mtac::Program> program, std::shared_ptr<StringPool> pool) const { bool optimized; do { optimized = false; //Optimize using arithmetic identities optimized |= debug<Debug, 1>(apply_to_all<ArithmeticIdentities>(program)); //Reduce arithtmetic instructions in strength optimized |= debug<Debug, 2>(apply_to_all<ReduceInStrength>(program)); //Constant folding optimized |= debug<Debug, 3>(apply_to_all<ConstantFolding>(program)); //Global constant propagation optimized |= debug<Debug, 4>(data_flow_optimization<ConstantPropagationProblem>(program)); //Offset Constant propagation optimized |= debug<Debug, 6>(apply_to_basic_blocks<OffsetConstantPropagation>(program)); //Copy propagation optimized |= debug<Debug, 7>(apply_to_basic_blocks<CopyPropagation>(program)); //Offset Copy propagation optimized |= debug<Debug, 8>(apply_to_basic_blocks<OffsetCopyPropagation>(program)); //Propagate math optimized |= debug<Debug, 9>(apply_to_basic_blocks_two_pass<MathPropagation>(program)); //Remove unused assignations optimized |= debug<Debug, 10>(apply_to_basic_blocks_two_pass<RemoveAssign>(program)); //Remove unused assignations optimized |= debug<Debug, 11>(apply_to_basic_blocks_two_pass<RemoveMultipleAssign>(program)); //Optimize branches optimized |= debug<Debug, 12>(optimize_branches(program)); //Optimize concatenations optimized |= debug<Debug, 13>(optimize_concat(program, pool)); //Remove dead basic blocks (unreachable code) optimized |= debug<Debug, 14>(remove_dead_basic_blocks(program)); //Remove needless jumps optimized |= debug<Debug, 15>(remove_needless_jumps(program)); //Merge basic blocks optimized |= debug<Debug, 16>(merge_basic_blocks(program)); } while (optimized); }
Disable the old constant propagation system
Disable the old constant propagation system
C++
mit
wichtounet/eddic,vogelsgesang/eddic,vogelsgesang/eddic,wichtounet/eddic,wichtounet/eddic,vogelsgesang/eddic
77440946edca28384bb3aa1791688c8ebcdab4d3
chrome/browser/translate/translate_infobar_delegate2.cc
chrome/browser/translate/translate_infobar_delegate2.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/translate/translate_infobar_delegate2.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/translate/translate_infobar_view.h" #include "chrome/browser/translate/translate_manager2.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" // static TranslateInfoBarDelegate2* TranslateInfoBarDelegate2::CreateInstance( Type type, TranslateErrors::Type error, TabContents* tab_contents, const std::string& original_language, const std::string& target_language) { if (!TranslateManager2::IsSupportedLanguage(original_language) || !TranslateManager2::IsSupportedLanguage(target_language)) { return NULL; } return new TranslateInfoBarDelegate2(type, error, tab_contents, original_language, target_language); } TranslateInfoBarDelegate2::TranslateInfoBarDelegate2( Type type, TranslateErrors::Type error, TabContents* tab_contents, const std::string& original_language, const std::string& target_language) : InfoBarDelegate(tab_contents), type_(type), background_animation_(NONE), tab_contents_(tab_contents), original_language_index_(-1), target_language_index_(-1), error_(error), infobar_view_(NULL), prefs_(tab_contents_->profile()->GetPrefs()) { DCHECK((type_ != TRANSLATION_ERROR && error == TranslateErrors::NONE) || (type_ == TRANSLATION_ERROR && error != TranslateErrors::NONE)); std::vector<std::string> language_codes; TranslateManager2::GetSupportedLanguages(&language_codes); languages_.reserve(language_codes.size()); for (std::vector<std::string>::const_iterator iter = language_codes.begin(); iter != language_codes.end(); ++iter) { std::string language_code = *iter; if (language_code == original_language) original_language_index_ = iter - language_codes.begin(); else if (language_code == target_language) target_language_index_ = iter - language_codes.begin(); string16 language_name = GetLanguageDisplayableName(language_code); // Insert the language in languages_ in alphabetical order. std::vector<LanguageNamePair>::iterator iter2; for (iter2 = languages_.begin(); iter2 != languages_.end(); ++iter2) { if (language_name.compare(iter2->second) < 0) break; } languages_.insert(iter2, LanguageNamePair(language_code, language_name)); } DCHECK(original_language_index_ != -1); DCHECK(target_language_index_ != -1); } int TranslateInfoBarDelegate2::GetLanguageCount() const { return static_cast<int>(languages_.size()); } const std::string& TranslateInfoBarDelegate2::GetLanguageCodeAt( int index) const { DCHECK(index >=0 && index < GetLanguageCount()); return languages_[index].first; } const string16& TranslateInfoBarDelegate2::GetLanguageDisplayableNameAt( int index) const { DCHECK(index >=0 && index < GetLanguageCount()); return languages_[index].second; } const std::string& TranslateInfoBarDelegate2::GetOriginalLanguageCode() const { return GetLanguageCodeAt(original_language_index()); } const std::string& TranslateInfoBarDelegate2::GetTargetLanguageCode() const { return GetLanguageCodeAt(target_language_index()); } void TranslateInfoBarDelegate2::SetOriginalLanguage(int language_index) { DCHECK(language_index < static_cast<int>(languages_.size())); original_language_index_ = language_index; if (infobar_view_) infobar_view_->OriginalLanguageChanged(); if (type_ == AFTER_TRANSLATE) Translate(); } void TranslateInfoBarDelegate2::SetTargetLanguage(int language_index) { DCHECK(language_index < static_cast<int>(languages_.size())); target_language_index_ = language_index; if (infobar_view_) infobar_view_->TargetLanguageChanged(); if (type_ == AFTER_TRANSLATE) Translate(); } bool TranslateInfoBarDelegate2::IsError() { return type_ == TRANSLATION_ERROR; } void TranslateInfoBarDelegate2::Translate() { Singleton<TranslateManager2>::get()->TranslatePage( tab_contents_, GetLanguageCodeAt(original_language_index()), GetLanguageCodeAt(target_language_index())); } void TranslateInfoBarDelegate2::RevertTranslation() { Singleton<TranslateManager2>::get()->RevertTranslation(tab_contents_); tab_contents_->RemoveInfoBar(this); } void TranslateInfoBarDelegate2::TranslationDeclined() { // Remember that the user declined the translation so as to prevent showing a // translate infobar for that page again. (TranslateManager initiates // translations when getting a LANGUAGE_DETERMINED from the page, which // happens when a load stops. That could happen multiple times, including // after the user already declined the translation.) tab_contents_->language_state().set_translation_declined(true); } void TranslateInfoBarDelegate2::InfoBarDismissed() { if (type_ != BEFORE_TRANSLATE) return; // The user closed the infobar without clicking the translate button. TranslationDeclined(); UMA_HISTOGRAM_COUNTS("Translate.DeclineTranslateCloseInfobar", 1); } SkBitmap* TranslateInfoBarDelegate2::GetIcon() const { return ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_INFOBAR_TRANSLATE); } InfoBarDelegate::Type TranslateInfoBarDelegate2::GetInfoBarType() { return InfoBarDelegate::PAGE_ACTION_TYPE; } bool TranslateInfoBarDelegate2::IsLanguageBlacklisted() { const std::string& original_lang = GetLanguageCodeAt(original_language_index()); return prefs_.IsLanguageBlacklisted(original_lang); } void TranslateInfoBarDelegate2::ToggleLanguageBlacklist() { const std::string& original_lang = GetLanguageCodeAt(original_language_index()); if (prefs_.IsLanguageBlacklisted(original_lang)) { prefs_.RemoveLanguageFromBlacklist(original_lang); } else { prefs_.BlacklistLanguage(original_lang); tab_contents_->RemoveInfoBar(this); } } bool TranslateInfoBarDelegate2::IsSiteBlacklisted() { std::string host = GetPageHost(); return !host.empty() && prefs_.IsSiteBlacklisted(host); } void TranslateInfoBarDelegate2::ToggleSiteBlacklist() { std::string host = GetPageHost(); if (host.empty()) return; if (prefs_.IsSiteBlacklisted(host)) { prefs_.RemoveSiteFromBlacklist(host); } else { prefs_.BlacklistSite(host); tab_contents_->RemoveInfoBar(this); } } bool TranslateInfoBarDelegate2::ShouldAlwaysTranslate() { return prefs_.IsLanguagePairWhitelisted(GetOriginalLanguageCode(), GetTargetLanguageCode()); } void TranslateInfoBarDelegate2::ToggleAlwaysTranslate() { std::string original_lang = GetOriginalLanguageCode(); std::string target_lang = GetTargetLanguageCode(); if (prefs_.IsLanguagePairWhitelisted(original_lang, target_lang)) prefs_.RemoveLanguagePairFromWhitelist(original_lang, target_lang); else prefs_.WhitelistLanguagePair(original_lang, target_lang); } string16 TranslateInfoBarDelegate2::GetMessageInfoBarText() { switch (type_) { case TRANSLATING: return l10n_util::GetStringFUTF16( IDS_TRANSLATE_INFOBAR_TRANSLATING_TO, GetLanguageDisplayableNameAt(target_language_index_)); case TRANSLATION_ERROR: switch (error_) { case TranslateErrors::NETWORK: return l10n_util::GetStringUTF16( IDS_TRANSLATE_INFOBAR_ERROR_CANT_CONNECT); case TranslateErrors::INITIALIZATION_ERROR: case TranslateErrors::TRANSLATION_ERROR: return l10n_util::GetStringUTF16( IDS_TRANSLATE_INFOBAR_ERROR_CANT_TRANSLATE); default: NOTREACHED(); return string16(); } default: NOTREACHED(); return string16(); } } string16 TranslateInfoBarDelegate2::GetMessageInfoBarButtonText() { switch (type_) { case TRANSLATING: return string16(); case TRANSLATION_ERROR: return l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_RETRY); default: NOTREACHED(); return string16(); } } void TranslateInfoBarDelegate2::MessageInfoBarButtonPressed() { DCHECK(type_ == TRANSLATION_ERROR); Singleton<TranslateManager2>::get()->TranslatePage( tab_contents_, GetLanguageCodeAt(original_language_index()), GetLanguageCodeAt(target_language_index())); } void TranslateInfoBarDelegate2::UpdateBackgroundAnimation( TranslateInfoBarDelegate2* previous_infobar) { if (!previous_infobar || previous_infobar->IsError() == IsError()) { background_animation_ = NONE; return; } background_animation_ = IsError() ? NORMAL_TO_ERROR : ERROR_TO_NORMAL; } std::string TranslateInfoBarDelegate2::GetPageHost() { NavigationEntry* entry = tab_contents_->controller().GetActiveEntry(); return entry ? entry->url().HostNoBrackets() : std::string(); } // static string16 TranslateInfoBarDelegate2::GetLanguageDisplayableName( const std::string& language_code) { return l10n_util::GetDisplayNameForLocale( language_code, g_browser_process->GetApplicationLocale(), true); } // static void TranslateInfoBarDelegate2::GetAfterTranslateStrings( std::vector<string16>* strings, bool* swap_languages) { DCHECK(strings); DCHECK(swap_languages); std::vector<size_t> offsets; string16 text = l10n_util::GetStringFUTF16(IDS_TRANSLATE_INFOBAR_AFTER_MESSAGE, string16(), string16(), &offsets); DCHECK(offsets.size() == 2U); if (offsets[0] > offsets[1]) { // Target language comes before source. int tmp = offsets[0]; offsets[0] = offsets[0]; offsets[1] = tmp; *swap_languages = true; } else { *swap_languages = false; } strings->push_back(text.substr(0, offsets[0])); strings->push_back(text.substr(offsets[0], offsets[1])); strings->push_back(text.substr(offsets[1])); } #if !defined(OS_WIN) && !defined(OS_CHROMEOS) // Necessary so we link OK on Mac and Linux while the new translate infobars // are being ported to these platforms. InfoBar* TranslateInfoBarDelegate2::CreateInfoBar() { return NULL; } #endif
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include "chrome/browser/translate/translate_infobar_delegate2.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/translate/translate_infobar_view.h" #include "chrome/browser/translate/translate_manager2.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" // static TranslateInfoBarDelegate2* TranslateInfoBarDelegate2::CreateInstance( Type type, TranslateErrors::Type error, TabContents* tab_contents, const std::string& original_language, const std::string& target_language) { if (!TranslateManager2::IsSupportedLanguage(original_language) || !TranslateManager2::IsSupportedLanguage(target_language)) { return NULL; } return new TranslateInfoBarDelegate2(type, error, tab_contents, original_language, target_language); } TranslateInfoBarDelegate2::TranslateInfoBarDelegate2( Type type, TranslateErrors::Type error, TabContents* tab_contents, const std::string& original_language, const std::string& target_language) : InfoBarDelegate(tab_contents), type_(type), background_animation_(NONE), tab_contents_(tab_contents), original_language_index_(-1), target_language_index_(-1), error_(error), infobar_view_(NULL), prefs_(tab_contents_->profile()->GetPrefs()) { DCHECK((type_ != TRANSLATION_ERROR && error == TranslateErrors::NONE) || (type_ == TRANSLATION_ERROR && error != TranslateErrors::NONE)); std::vector<std::string> language_codes; TranslateManager2::GetSupportedLanguages(&language_codes); languages_.reserve(language_codes.size()); for (std::vector<std::string>::const_iterator iter = language_codes.begin(); iter != language_codes.end(); ++iter) { std::string language_code = *iter; if (language_code == original_language) original_language_index_ = iter - language_codes.begin(); else if (language_code == target_language) target_language_index_ = iter - language_codes.begin(); string16 language_name = GetLanguageDisplayableName(language_code); // Insert the language in languages_ in alphabetical order. std::vector<LanguageNamePair>::iterator iter2; for (iter2 = languages_.begin(); iter2 != languages_.end(); ++iter2) { if (language_name.compare(iter2->second) < 0) break; } languages_.insert(iter2, LanguageNamePair(language_code, language_name)); } DCHECK(original_language_index_ != -1); DCHECK(target_language_index_ != -1); } int TranslateInfoBarDelegate2::GetLanguageCount() const { return static_cast<int>(languages_.size()); } const std::string& TranslateInfoBarDelegate2::GetLanguageCodeAt( int index) const { DCHECK(index >=0 && index < GetLanguageCount()); return languages_[index].first; } const string16& TranslateInfoBarDelegate2::GetLanguageDisplayableNameAt( int index) const { DCHECK(index >=0 && index < GetLanguageCount()); return languages_[index].second; } const std::string& TranslateInfoBarDelegate2::GetOriginalLanguageCode() const { return GetLanguageCodeAt(original_language_index()); } const std::string& TranslateInfoBarDelegate2::GetTargetLanguageCode() const { return GetLanguageCodeAt(target_language_index()); } void TranslateInfoBarDelegate2::SetOriginalLanguage(int language_index) { DCHECK(language_index < static_cast<int>(languages_.size())); original_language_index_ = language_index; if (infobar_view_) infobar_view_->OriginalLanguageChanged(); if (type_ == AFTER_TRANSLATE) Translate(); } void TranslateInfoBarDelegate2::SetTargetLanguage(int language_index) { DCHECK(language_index < static_cast<int>(languages_.size())); target_language_index_ = language_index; if (infobar_view_) infobar_view_->TargetLanguageChanged(); if (type_ == AFTER_TRANSLATE) Translate(); } bool TranslateInfoBarDelegate2::IsError() { return type_ == TRANSLATION_ERROR; } void TranslateInfoBarDelegate2::Translate() { Singleton<TranslateManager2>::get()->TranslatePage( tab_contents_, GetLanguageCodeAt(original_language_index()), GetLanguageCodeAt(target_language_index())); } void TranslateInfoBarDelegate2::RevertTranslation() { Singleton<TranslateManager2>::get()->RevertTranslation(tab_contents_); tab_contents_->RemoveInfoBar(this); } void TranslateInfoBarDelegate2::TranslationDeclined() { // Remember that the user declined the translation so as to prevent showing a // translate infobar for that page again. (TranslateManager initiates // translations when getting a LANGUAGE_DETERMINED from the page, which // happens when a load stops. That could happen multiple times, including // after the user already declined the translation.) tab_contents_->language_state().set_translation_declined(true); } void TranslateInfoBarDelegate2::InfoBarDismissed() { if (type_ != BEFORE_TRANSLATE) return; // The user closed the infobar without clicking the translate button. TranslationDeclined(); UMA_HISTOGRAM_COUNTS("Translate.DeclineTranslateCloseInfobar", 1); } SkBitmap* TranslateInfoBarDelegate2::GetIcon() const { return ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_INFOBAR_TRANSLATE); } InfoBarDelegate::Type TranslateInfoBarDelegate2::GetInfoBarType() { return InfoBarDelegate::PAGE_ACTION_TYPE; } bool TranslateInfoBarDelegate2::IsLanguageBlacklisted() { const std::string& original_lang = GetLanguageCodeAt(original_language_index()); return prefs_.IsLanguageBlacklisted(original_lang); } void TranslateInfoBarDelegate2::ToggleLanguageBlacklist() { const std::string& original_lang = GetLanguageCodeAt(original_language_index()); if (prefs_.IsLanguageBlacklisted(original_lang)) { prefs_.RemoveLanguageFromBlacklist(original_lang); } else { prefs_.BlacklistLanguage(original_lang); tab_contents_->RemoveInfoBar(this); } } bool TranslateInfoBarDelegate2::IsSiteBlacklisted() { std::string host = GetPageHost(); return !host.empty() && prefs_.IsSiteBlacklisted(host); } void TranslateInfoBarDelegate2::ToggleSiteBlacklist() { std::string host = GetPageHost(); if (host.empty()) return; if (prefs_.IsSiteBlacklisted(host)) { prefs_.RemoveSiteFromBlacklist(host); } else { prefs_.BlacklistSite(host); tab_contents_->RemoveInfoBar(this); } } bool TranslateInfoBarDelegate2::ShouldAlwaysTranslate() { return prefs_.IsLanguagePairWhitelisted(GetOriginalLanguageCode(), GetTargetLanguageCode()); } void TranslateInfoBarDelegate2::ToggleAlwaysTranslate() { std::string original_lang = GetOriginalLanguageCode(); std::string target_lang = GetTargetLanguageCode(); if (prefs_.IsLanguagePairWhitelisted(original_lang, target_lang)) prefs_.RemoveLanguagePairFromWhitelist(original_lang, target_lang); else prefs_.WhitelistLanguagePair(original_lang, target_lang); } string16 TranslateInfoBarDelegate2::GetMessageInfoBarText() { switch (type_) { case TRANSLATING: return l10n_util::GetStringFUTF16( IDS_TRANSLATE_INFOBAR_TRANSLATING_TO, GetLanguageDisplayableNameAt(target_language_index_)); case TRANSLATION_ERROR: switch (error_) { case TranslateErrors::NETWORK: return l10n_util::GetStringUTF16( IDS_TRANSLATE_INFOBAR_ERROR_CANT_CONNECT); case TranslateErrors::INITIALIZATION_ERROR: case TranslateErrors::TRANSLATION_ERROR: return l10n_util::GetStringUTF16( IDS_TRANSLATE_INFOBAR_ERROR_CANT_TRANSLATE); default: NOTREACHED(); return string16(); } default: NOTREACHED(); return string16(); } } string16 TranslateInfoBarDelegate2::GetMessageInfoBarButtonText() { switch (type_) { case TRANSLATING: return string16(); case TRANSLATION_ERROR: return l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_RETRY); default: NOTREACHED(); return string16(); } } void TranslateInfoBarDelegate2::MessageInfoBarButtonPressed() { DCHECK(type_ == TRANSLATION_ERROR); Singleton<TranslateManager2>::get()->TranslatePage( tab_contents_, GetLanguageCodeAt(original_language_index()), GetLanguageCodeAt(target_language_index())); } void TranslateInfoBarDelegate2::UpdateBackgroundAnimation( TranslateInfoBarDelegate2* previous_infobar) { if (!previous_infobar || previous_infobar->IsError() == IsError()) { background_animation_ = NONE; return; } background_animation_ = IsError() ? NORMAL_TO_ERROR : ERROR_TO_NORMAL; } std::string TranslateInfoBarDelegate2::GetPageHost() { NavigationEntry* entry = tab_contents_->controller().GetActiveEntry(); return entry ? entry->url().HostNoBrackets() : std::string(); } // static string16 TranslateInfoBarDelegate2::GetLanguageDisplayableName( const std::string& language_code) { return l10n_util::GetDisplayNameForLocale( language_code, g_browser_process->GetApplicationLocale(), true); } // static void TranslateInfoBarDelegate2::GetAfterTranslateStrings( std::vector<string16>* strings, bool* swap_languages) { DCHECK(strings); DCHECK(swap_languages); std::vector<size_t> offsets; string16 text = l10n_util::GetStringFUTF16(IDS_TRANSLATE_INFOBAR_AFTER_MESSAGE, string16(), string16(), &offsets); DCHECK(offsets.size() == 2U); if (offsets[0] > offsets[1]) { // Target language comes before source. std::swap(offsets[0], offsets[1]); *swap_languages = true; } else { *swap_languages = false; } strings->push_back(text.substr(0, offsets[0])); strings->push_back(text.substr(offsets[0], offsets[1])); strings->push_back(text.substr(offsets[1])); } #if !defined(OS_WIN) && !defined(OS_CHROMEOS) // Necessary so we link OK on Mac and Linux while the new translate infobars // are being ported to these platforms. InfoBar* TranslateInfoBarDelegate2::CreateInfoBar() { return NULL; } #endif
fix wrong assignment in swap in TranslateInfoBarDelegate2::GetAfterTranslateStrings.
Coverity: fix wrong assignment in swap in TranslateInfoBarDelegate2::GetAfterTranslateStrings. CID=10888 BUG=none TEST=builds Review URL: http://codereview.chromium.org/2850007 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@50010 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
yitian134/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,adobe/chromium
d6e8e213c0b374444bb5f0c04fda54197869b655
srtcore/tsbpd_time.cpp
srtcore/tsbpd_time.cpp
/* * SRT - Secure, Reliable, Transport * Copyright (c) 2021 Haivision Systems Inc. * * 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 "tsbpd_time.h" #include "logging.h" #include "logger_defs.h" #include "packet.h" using namespace srt_logging; using namespace srt::sync; namespace srt { #if SRT_DEBUG_TRACE_DRIFT class drift_logger { using steady_clock = srt::sync::steady_clock; public: drift_logger() {} ~drift_logger() { ScopedLock lck(m_mtx); m_fout.close(); } void trace(unsigned ackack_timestamp, int rtt_us, int64_t drift_sample, int64_t drift, int64_t overdrift, const std::chrono::steady_clock::time_point& tsbpd_base) { using namespace srt::sync; ScopedLock lck(m_mtx); create_file(); // std::string str_tnow = srt::sync::FormatTime(steady_clock::now()); // str_tnow.resize(str_tnow.size() - 7); // remove trailing ' [STDY]' part std::string str_tbase = srt::sync::FormatTime(tsbpd_base); str_tbase.resize(str_tbase.size() - 7); // remove trailing ' [STDY]' part // m_fout << str_tnow << ","; m_fout << count_microseconds(steady_clock::now() - m_start_time) << ","; m_fout << ackack_timestamp << ","; m_fout << rtt_us << ","; m_fout << drift_sample << ","; m_fout << drift << ","; m_fout << overdrift << ","; m_fout << str_tbase << "\n"; m_fout.flush(); } private: void print_header() { m_fout << "usElapsedStd,usAckAckTimestampStd,"; m_fout << "usRTTStd,usDriftSampleStd,usDriftStd,usOverdriftStd,TSBPDBase\n"; } void create_file() { if (m_fout.is_open()) return; m_start_time = srt::sync::steady_clock::now(); std::string str_tnow = srt::sync::FormatTimeSys(m_start_time); str_tnow.resize(str_tnow.size() - 7); // remove trailing ' [SYST]' part while (str_tnow.find(':') != std::string::npos) { str_tnow.replace(str_tnow.find(':'), 1, 1, '_'); } const std::string fname = "drift_trace_" + str_tnow + ".csv"; m_fout.open(fname, std::ofstream::out); if (!m_fout) std::cerr << "IPE: Failed to open " << fname << "!!!\n"; print_header(); } private: srt::sync::Mutex m_mtx; std::ofstream m_fout; srt::sync::steady_clock::time_point m_start_time; }; drift_logger g_drift_logger; #endif // SRT_DEBUG_TRACE_DRIFT bool CTsbpdTime::addDriftSample(uint32_t usPktTimestamp, int usRTTSample, steady_clock::duration& w_udrift, steady_clock::time_point& w_newtimebase) { if (!m_bTsbPdMode) return false; const time_point tsNow = steady_clock::now(); ScopedLock lck(m_mtxRW); // Remember the first RTT sample measured. Ideally we need RTT0 - the one from the handshaking phase, // because TSBPD base is initialized there. But HS-based RTT is not yet implemented. // Take the first one assuming it is close to RTT0. if (m_iFirstRTT == -1) { m_iFirstRTT = usRTTSample; } // A change in network delay has to be taken into account. The only way to get some estimation of it // is to estimate RTT change and assume that the change of the one way network delay is // approximated by the half of the RTT change. const duration tdRTTDelta = microseconds_from((usRTTSample - m_iFirstRTT) / 2); const steady_clock::duration tdDrift = tsNow - getPktTsbPdBaseTime(usPktTimestamp) - tdRTTDelta; const bool updated = m_DriftTracer.update(count_microseconds(tdDrift)); if (updated) { IF_HEAVY_LOGGING(const steady_clock::time_point oldbase = m_tsTsbPdTimeBase); steady_clock::duration overdrift = microseconds_from(m_DriftTracer.overdrift()); m_tsTsbPdTimeBase += overdrift; HLOGC(brlog.Debug, log << "DRIFT=" << FormatDuration(tdDrift) << " AVG=" << (m_DriftTracer.drift() / 1000.0) << "ms, TB: " << FormatTime(oldbase) << " EXCESS: " << FormatDuration(overdrift) << " UPDATED TO: " << FormatTime(m_tsTsbPdTimeBase)); } else { HLOGC(brlog.Debug, log << "DRIFT=" << FormatDuration(tdDrift) << " TB REMAINS: " << FormatTime(m_tsTsbPdTimeBase)); } w_udrift = tdDrift; w_newtimebase = m_tsTsbPdTimeBase; #if SRT_DEBUG_TRACE_DRIFT g_drift_logger.trace(usPktTimestamp, usRTTSample, count_microseconds(tdDrift), m_DriftTracer.drift(), m_DriftTracer.overdrift(), m_tsTsbPdTimeBase); #endif return updated; } void CTsbpdTime::setTsbPdMode(const steady_clock::time_point& timebase, bool wrap, duration delay) { m_bTsbPdMode = true; m_bTsbPdWrapCheck = wrap; // Timebase passed here comes is calculated as: // Tnow - hspkt.m_iTimeStamp // where hspkt is the packet with SRT_CMD_HSREQ message. // // This function is called in the HSREQ reception handler only. m_tsTsbPdTimeBase = timebase; m_tdTsbPdDelay = delay; } void CTsbpdTime::applyGroupTime(const steady_clock::time_point& timebase, bool wrp, uint32_t delay, const steady_clock::duration& udrift) { // Same as setTsbPdMode, but predicted to be used for group members. // This synchronizes the time from the INTERNAL TIMEBASE of an existing // socket's internal timebase. This is required because the initial time // base stays always the same, whereas the internal timebase undergoes // adjustment as the 32-bit timestamps in the sockets wrap. The socket // newly added to the group must get EXACTLY the same internal timebase // or otherwise the TsbPd time calculation will ship different results // on different member sockets. m_bTsbPdMode = true; m_tsTsbPdTimeBase = timebase; m_bTsbPdWrapCheck = wrp; m_tdTsbPdDelay = microseconds_from(delay); m_DriftTracer.forceDrift(count_microseconds(udrift)); } void CTsbpdTime::applyGroupDrift(const steady_clock::time_point& timebase, bool wrp, const steady_clock::duration& udrift) { // This is only when a drift was updated on one of the group members. HLOGC(brlog.Debug, log << "rcv-buffer: group synch uDRIFT: " << m_DriftTracer.drift() << " -> " << FormatDuration(udrift) << " TB: " << FormatTime(m_tsTsbPdTimeBase) << " -> " << FormatTime(timebase)); m_tsTsbPdTimeBase = timebase; m_bTsbPdWrapCheck = wrp; m_DriftTracer.forceDrift(count_microseconds(udrift)); } CTsbpdTime::time_point CTsbpdTime::getTsbPdTimeBase(uint32_t timestamp_us) const { const uint64_t carryover_us = (m_bTsbPdWrapCheck && timestamp_us < TSBPD_WRAP_PERIOD) ? uint64_t(CPacket::MAX_TIMESTAMP) + 1 : 0; return (m_tsTsbPdTimeBase + microseconds_from(carryover_us)); } CTsbpdTime::time_point CTsbpdTime::getPktTsbPdTime(uint32_t usPktTimestamp) const { return getPktTsbPdBaseTime(usPktTimestamp) + m_tdTsbPdDelay + microseconds_from(m_DriftTracer.drift()); } CTsbpdTime::time_point CTsbpdTime::getPktTsbPdBaseTime(uint32_t usPktTimestamp) const { return getTsbPdTimeBase(usPktTimestamp) + microseconds_from(usPktTimestamp); } void CTsbpdTime::updateTsbPdTimeBase(uint32_t usPktTimestamp) { if (m_bTsbPdWrapCheck) { // Wrap check period. if ((usPktTimestamp >= TSBPD_WRAP_PERIOD) && (usPktTimestamp <= (TSBPD_WRAP_PERIOD * 2))) { /* Exiting wrap check period (if for packet delivery head) */ m_bTsbPdWrapCheck = false; m_tsTsbPdTimeBase += microseconds_from(int64_t(CPacket::MAX_TIMESTAMP) + 1); LOGC(tslog.Debug, log << "tsbpd wrap period ends with ts=" << usPktTimestamp << " - NEW TIME BASE: " << FormatTime(m_tsTsbPdTimeBase) << " drift: " << m_DriftTracer.drift() << "us"); } return; } // Check if timestamp is in the last 30 seconds before reaching the MAX_TIMESTAMP. if (usPktTimestamp > (CPacket::MAX_TIMESTAMP - TSBPD_WRAP_PERIOD)) { // Approching wrap around point, start wrap check period (if for packet delivery head) m_bTsbPdWrapCheck = true; LOGC(tslog.Debug, log << "tsbpd wrap period begins with ts=" << usPktTimestamp << " drift: " << m_DriftTracer.drift() << "us."); } } void CTsbpdTime::getInternalTimeBase(time_point& w_tb, bool& w_wrp, duration& w_udrift) const { ScopedLock lck(m_mtxRW); w_tb = m_tsTsbPdTimeBase; w_udrift = microseconds_from(m_DriftTracer.drift()); w_wrp = m_bTsbPdWrapCheck; } } // namespace srt
/* * SRT - Secure, Reliable, Transport * Copyright (c) 2021 Haivision Systems Inc. * * 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 "tsbpd_time.h" #include "logging.h" #include "logger_defs.h" #include "packet.h" using namespace srt_logging; using namespace srt::sync; namespace srt { #if SRT_DEBUG_TRACE_DRIFT class drift_logger { typedef srt::sync::steady_clock steady_clock; public: drift_logger() {} ~drift_logger() { ScopedLock lck(m_mtx); m_fout.close(); } void trace(unsigned ackack_timestamp, int rtt_us, int64_t drift_sample, int64_t drift, int64_t overdrift, const srt::sync::steady_clock::time_point& tsbpd_base) { using namespace srt::sync; ScopedLock lck(m_mtx); create_file(); // std::string str_tnow = srt::sync::FormatTime(steady_clock::now()); // str_tnow.resize(str_tnow.size() - 7); // remove trailing ' [STDY]' part std::string str_tbase = srt::sync::FormatTime(tsbpd_base); str_tbase.resize(str_tbase.size() - 7); // remove trailing ' [STDY]' part // m_fout << str_tnow << ","; m_fout << count_microseconds(steady_clock::now() - m_start_time) << ","; m_fout << ackack_timestamp << ","; m_fout << rtt_us << ","; m_fout << drift_sample << ","; m_fout << drift << ","; m_fout << overdrift << ","; m_fout << str_tbase << "\n"; m_fout.flush(); } private: void print_header() { m_fout << "usElapsedStd,usAckAckTimestampStd,"; m_fout << "usRTTStd,usDriftSampleStd,usDriftStd,usOverdriftStd,TSBPDBase\n"; } void create_file() { if (m_fout.is_open()) return; m_start_time = srt::sync::steady_clock::now(); std::string str_tnow = srt::sync::FormatTimeSys(m_start_time); str_tnow.resize(str_tnow.size() - 7); // remove trailing ' [SYST]' part while (str_tnow.find(':') != std::string::npos) { str_tnow.replace(str_tnow.find(':'), 1, 1, '_'); } const std::string fname = "drift_trace_" + str_tnow + ".csv"; m_fout.open(fname, std::ofstream::out); if (!m_fout) std::cerr << "IPE: Failed to open " << fname << "!!!\n"; print_header(); } private: srt::sync::Mutex m_mtx; std::ofstream m_fout; srt::sync::steady_clock::time_point m_start_time; }; drift_logger g_drift_logger; #endif // SRT_DEBUG_TRACE_DRIFT bool CTsbpdTime::addDriftSample(uint32_t usPktTimestamp, int usRTTSample, steady_clock::duration& w_udrift, steady_clock::time_point& w_newtimebase) { if (!m_bTsbPdMode) return false; const time_point tsNow = steady_clock::now(); ScopedLock lck(m_mtxRW); // Remember the first RTT sample measured. Ideally we need RTT0 - the one from the handshaking phase, // because TSBPD base is initialized there. But HS-based RTT is not yet implemented. // Take the first one assuming it is close to RTT0. if (m_iFirstRTT == -1) { m_iFirstRTT = usRTTSample; } // A change in network delay has to be taken into account. The only way to get some estimation of it // is to estimate RTT change and assume that the change of the one way network delay is // approximated by the half of the RTT change. const duration tdRTTDelta = microseconds_from((usRTTSample - m_iFirstRTT) / 2); const steady_clock::duration tdDrift = tsNow - getPktTsbPdBaseTime(usPktTimestamp) - tdRTTDelta; const bool updated = m_DriftTracer.update(count_microseconds(tdDrift)); if (updated) { IF_HEAVY_LOGGING(const steady_clock::time_point oldbase = m_tsTsbPdTimeBase); steady_clock::duration overdrift = microseconds_from(m_DriftTracer.overdrift()); m_tsTsbPdTimeBase += overdrift; HLOGC(brlog.Debug, log << "DRIFT=" << FormatDuration(tdDrift) << " AVG=" << (m_DriftTracer.drift() / 1000.0) << "ms, TB: " << FormatTime(oldbase) << " EXCESS: " << FormatDuration(overdrift) << " UPDATED TO: " << FormatTime(m_tsTsbPdTimeBase)); } else { HLOGC(brlog.Debug, log << "DRIFT=" << FormatDuration(tdDrift) << " TB REMAINS: " << FormatTime(m_tsTsbPdTimeBase)); } w_udrift = tdDrift; w_newtimebase = m_tsTsbPdTimeBase; #if SRT_DEBUG_TRACE_DRIFT g_drift_logger.trace(usPktTimestamp, usRTTSample, count_microseconds(tdDrift), m_DriftTracer.drift(), m_DriftTracer.overdrift(), m_tsTsbPdTimeBase); #endif return updated; } void CTsbpdTime::setTsbPdMode(const steady_clock::time_point& timebase, bool wrap, duration delay) { m_bTsbPdMode = true; m_bTsbPdWrapCheck = wrap; // Timebase passed here comes is calculated as: // Tnow - hspkt.m_iTimeStamp // where hspkt is the packet with SRT_CMD_HSREQ message. // // This function is called in the HSREQ reception handler only. m_tsTsbPdTimeBase = timebase; m_tdTsbPdDelay = delay; } void CTsbpdTime::applyGroupTime(const steady_clock::time_point& timebase, bool wrp, uint32_t delay, const steady_clock::duration& udrift) { // Same as setTsbPdMode, but predicted to be used for group members. // This synchronizes the time from the INTERNAL TIMEBASE of an existing // socket's internal timebase. This is required because the initial time // base stays always the same, whereas the internal timebase undergoes // adjustment as the 32-bit timestamps in the sockets wrap. The socket // newly added to the group must get EXACTLY the same internal timebase // or otherwise the TsbPd time calculation will ship different results // on different member sockets. m_bTsbPdMode = true; m_tsTsbPdTimeBase = timebase; m_bTsbPdWrapCheck = wrp; m_tdTsbPdDelay = microseconds_from(delay); m_DriftTracer.forceDrift(count_microseconds(udrift)); } void CTsbpdTime::applyGroupDrift(const steady_clock::time_point& timebase, bool wrp, const steady_clock::duration& udrift) { // This is only when a drift was updated on one of the group members. HLOGC(brlog.Debug, log << "rcv-buffer: group synch uDRIFT: " << m_DriftTracer.drift() << " -> " << FormatDuration(udrift) << " TB: " << FormatTime(m_tsTsbPdTimeBase) << " -> " << FormatTime(timebase)); m_tsTsbPdTimeBase = timebase; m_bTsbPdWrapCheck = wrp; m_DriftTracer.forceDrift(count_microseconds(udrift)); } CTsbpdTime::time_point CTsbpdTime::getTsbPdTimeBase(uint32_t timestamp_us) const { const uint64_t carryover_us = (m_bTsbPdWrapCheck && timestamp_us < TSBPD_WRAP_PERIOD) ? uint64_t(CPacket::MAX_TIMESTAMP) + 1 : 0; return (m_tsTsbPdTimeBase + microseconds_from(carryover_us)); } CTsbpdTime::time_point CTsbpdTime::getPktTsbPdTime(uint32_t usPktTimestamp) const { return getPktTsbPdBaseTime(usPktTimestamp) + m_tdTsbPdDelay + microseconds_from(m_DriftTracer.drift()); } CTsbpdTime::time_point CTsbpdTime::getPktTsbPdBaseTime(uint32_t usPktTimestamp) const { return getTsbPdTimeBase(usPktTimestamp) + microseconds_from(usPktTimestamp); } void CTsbpdTime::updateTsbPdTimeBase(uint32_t usPktTimestamp) { if (m_bTsbPdWrapCheck) { // Wrap check period. if ((usPktTimestamp >= TSBPD_WRAP_PERIOD) && (usPktTimestamp <= (TSBPD_WRAP_PERIOD * 2))) { /* Exiting wrap check period (if for packet delivery head) */ m_bTsbPdWrapCheck = false; m_tsTsbPdTimeBase += microseconds_from(int64_t(CPacket::MAX_TIMESTAMP) + 1); LOGC(tslog.Debug, log << "tsbpd wrap period ends with ts=" << usPktTimestamp << " - NEW TIME BASE: " << FormatTime(m_tsTsbPdTimeBase) << " drift: " << m_DriftTracer.drift() << "us"); } return; } // Check if timestamp is in the last 30 seconds before reaching the MAX_TIMESTAMP. if (usPktTimestamp > (CPacket::MAX_TIMESTAMP - TSBPD_WRAP_PERIOD)) { // Approching wrap around point, start wrap check period (if for packet delivery head) m_bTsbPdWrapCheck = true; LOGC(tslog.Debug, log << "tsbpd wrap period begins with ts=" << usPktTimestamp << " drift: " << m_DriftTracer.drift() << "us."); } } void CTsbpdTime::getInternalTimeBase(time_point& w_tb, bool& w_wrp, duration& w_udrift) const { ScopedLock lck(m_mtxRW); w_tb = m_tsTsbPdTimeBase; w_udrift = microseconds_from(m_DriftTracer.drift()); w_wrp = m_bTsbPdWrapCheck; } } // namespace srt
Fix build error when -DSRT_DEBUG_TRACE_DRIFT=1
[core] Fix build error when -DSRT_DEBUG_TRACE_DRIFT=1
C++
mpl-2.0
ethouris/srt,ethouris/srt,Cinegy/srt,Cinegy/srt,ethouris/srt,Cinegy/srt,Haivision/srt,ethouris/srt,Haivision/srt,Haivision/srt,Cinegy/srt,Haivision/srt
240434342bd6facc12a44ba056c4f952c030fb00
startuplaunch_macx.cpp
startuplaunch_macx.cpp
#include "startuplaunch.h" #include <QDesktopServices> StartupLaunch::StartupLaunch() { } bool StartupLaunch::addOnStartup(QString name, QString executable, QString comments) { qWarning() << " add to startup not yet implemented on macx"; return false; } bool StartupLaunch::removeFromStartup(QString name) { qWarning() << " remove from startup not yet implemented on macx"; return false; } bool StartupLaunch::isOnStartup(QString name) { qWarning() << " is on startup not yet implemented on macx"; return false; }
#include "startuplaunch.h" #include <QDesktopServices> StartupLaunch::StartupLaunch() { } bool StartupLaunch::addOnStartup(QString name, QString executable, QString comments) { QString autostartPath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation)+"/Library/LaunchAgents"; if(false==QDir().exists(autostartPath)) QDir().mkdir(autostartPath); QString filepath = autostartPath+"/"+name.toLower()+".plist"; QFile file(filepath); if(false==file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) { qWarning() << "Startuplaunch : impossible to open " << filepath; return false; } QTextStream out(&file); out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl << "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" << endl << "<plist version=\"1.0\">" << endl << "<dict>" << endl << "<key>Label</key>" << endl << "<string>me.boxti.boxtime</string>" << endl << "<key>RunAtLoad</key>" << endl << "<true/>" << endl << "<key>Program</key>" << endl << "<string>/Applications/boxtime.app/Contents/MacOS/boxtime</string>" << endl << "</dict>" << endl << "</plist>" << endl; file.close(); qDebug() << name << " added to startup " << executable; return true; } bool StartupLaunch::removeFromStartup(QString name) { qDebug() << name << " removed from startup"; return QFile::remove(QDesktopServices::storageLocation(QDesktopServices::HomeLocation)+QString("/Library/LaunchAgents/")+name.toLower()+QString(".plist")); } bool StartupLaunch::isOnStartup(QString name) { return QFile::exists(QDesktopServices::storageLocation(QDesktopServices::HomeLocation)+QString("/Library/LaunchAgents/")+name.toLower()+QString(".desktopplist")); }
Add basic implementation for MacOS X
Add basic implementation for MacOS X
C++
bsd-2-clause
jdauphant/startuplaunch-qt
3350f3bdf37945270d6cfb56a8e4f03fcb928648
cubits/stencil.inl
cubits/stencil.inl
/* ----------------------------------------------------------------------------- * * Kernel : Stencil * Copyright : [2008..2010] Manuel M T Chakravarty, Gabriele Keller, Sean Lee, Trevor L. McDonell * License : BSD3 * * Maintainer : Trevor L. McDonell <[email protected]> * Stability : experimental * * Apply the function to each element of the array that takes a neighborhood of * elements as its input. Each thread processes multiple elements, striding the * array by the grid size. * * To improve performance, the input array is bound as a texture reference so * that reads are cached. Note that the input array is still passed in to the * kernel as an argument, and also passed around through various functions, but * never actually used. This is simply an artefact of reusing generated functions * such as 'gather' for optimised version of specific kernel operations (e.g. 1D * and 2D stencil operations). * * ---------------------------------------------------------------------------*/ #if defined(BOUNDARY_CLAMP) || defined(BOUNDARY_MIRROR) || defined(BOUNDARY_WRAP) /* * Bounds check handling for Clamp, Mirror and Wrap. Peforms an index projection. */ static __inline__ __device__ DIM1 project_for_bounds(DIM1 sh, DIM1 ix) { if (ix < 0) { #if defined(BOUNDARY_CLAMP) return 0; #elif defined(BOUNDARY_MIRROR) return 0 - ix - 1; #elif defined(BOUNDARY_WRAP) return sh - ix; #else #error "project_for_bounds - only support CLAMP, MIRROR and WRAP." #endif } else if (ix >= sh) { #if defined(BOUNDARY_CLAMP) return sh - 1; #elif defined(BOUNDARY_MIRROR) return (sh - 1) - (ix - sh); #elif defined(BOUNDARY_WRAP) return ix - sh; #else #error "project_for_bounds - only support CLAMP, MIRROR and WRAP." #endif } else { return ix; } } static __inline__ __device__ DIM2 project_for_bounds(DIM2 sh, DIM2 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM3 project_for_bounds(DIM3 sh, DIM3 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM4 project_for_bounds(DIM4 sh, DIM4 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM5 project_for_bounds(DIM5 sh, DIM5 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM6 project_for_bounds(DIM6 sh, DIM6 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM7 project_for_bounds(DIM7 sh, DIM7 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM8 project_for_bounds(DIM8 sh, DIM8 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM9 project_for_bounds(DIM9 sh, DIM9 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } #else /* * Bounds check handling for Constant. */ static __inline__ __device__ TyIn0 get0_for_constant_bounds(ArrIn0 d_in0, DIM1 sh, DIM1 ix) { if (ix < 0) return boundary_const(); else if (ix >= sh) return boundary_const(); else return tex_get0(ix); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(ArrIn0 d_in0, DIM2 sh, DIM2 ix) { if (ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(ArrIn0 d_in0, DIM3 sh, DIM3 ix) { if (ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(ArrIn0 d_in0, DIM4 sh, DIM4 ix) { if (ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(ArrIn0 d_in0, DIM5 sh, DIM5 ix) { if (ix.a4 < 0 || ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a4 >= sh.a4 || ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(ArrIn0 d_in0, DIM6 sh, DIM6 ix) { if (ix.a5 < 0 || ix.a4 < 0 || ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a5 >= sh.a5 || ix.a4 >= sh.a4 || ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(ArrIn0 d_in0, DIM7 sh, DIM7 ix) { if (ix.a6 < 0 || ix.a5 < 0 || ix.a4 < 0 || ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a6 >= sh.a6 || ix.a5 >= sh.a5 || ix.a4 >= sh.a4 || ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(ArrIn0 d_in0, DIM8 sh, DIM8 ix) { if (ix.a7 < 0 || ix.a6 < 0 || ix.a5 < 0 || ix.a4 < 0 || ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a7 >= sh.a7 || ix.a6 >= sh.a6 || ix.a5 >= sh.a5 || ix.a4 >= sh.a4 || ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(ArrIn0 d_in0, DIM9 sh, DIM9 ix) { if (ix.a8 < 0 || ix.a7 < 0 || ix.a6 < 0 || ix.a5 < 0 || ix.a4 < 0 || ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a8 >= sh.a8 || ix.a7 >= sh.a7 || ix.a6 >= sh.a6 || ix.a5 >= sh.a5 || ix.a4 >= sh.a4 || ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } #endif /* * Getter function that handles indexing outside the array boundary. */ static inline __attribute__((device)) TyIn0 get0_for_stencil(ArrIn0 d_in0, ArrDimIn0 sh, ArrDimIn0 ix) { #if defined(BOUNDARY_CLAMP) || defined(BOUNDARY_MIRROR) || defined(BOUNDARY_WRAP) return tex_get0(toIndex(sh, project_for_bounds(sh, ix))); #else return get0_for_constant_bounds(d_in0, sh, ix); #endif } /* * The kernel. */ extern "C" __global__ void stencil ( ArrOut d_out, const ArrIn0 d_in0, const ArrDimIn0 d_in0_shape ) { Ix idx; const Ix gridSize = __umul24(blockDim.x, gridDim.x); for (idx = __umul24(blockDim.x, blockIdx.x) + threadIdx.x; idx < size(d_in0_shape); idx += gridSize) { set(d_out, idx, apply(gather0(d_in0, fromIndex(d_in0_shape, idx), d_in0_shape))); } }
/* ----------------------------------------------------------------------------- * * Kernel : Stencil * Copyright : [2008..2010] Manuel M T Chakravarty, Gabriele Keller, Sean Lee, Trevor L. McDonell * License : BSD3 * * Maintainer : Trevor L. McDonell <[email protected]> * Stability : experimental * * Apply the function to each element of the array that takes a neighborhood of * elements as its input. Each thread processes multiple elements, striding the * array by the grid size. * * To improve performance, the input array is bound as a texture reference so * that reads are cached. Note that the input array is still passed in to the * kernel as an argument, and also passed around through various functions, but * never actually used. This is simply an artefact of reusing generated functions * such as 'gather' for optimised version of specific kernel operations (e.g. 1D * and 2D stencil operations). * * ---------------------------------------------------------------------------*/ #if defined(BOUNDARY_CLAMP) || defined(BOUNDARY_MIRROR) || defined(BOUNDARY_WRAP) /* * Bounds check handling for Clamp, Mirror and Wrap. Peforms an index projection. */ static __inline__ __device__ DIM1 project_for_bounds(const DIM1 sh, const DIM1 ix) { if (ix < 0) { #if defined(BOUNDARY_CLAMP) return 0; #elif defined(BOUNDARY_MIRROR) return 0 - ix - 1; #elif defined(BOUNDARY_WRAP) return sh - ix; #else #error "project_for_bounds - only support CLAMP, MIRROR and WRAP." #endif } else if (ix >= sh) { #if defined(BOUNDARY_CLAMP) return sh - 1; #elif defined(BOUNDARY_MIRROR) return (sh - 1) - (ix - sh); #elif defined(BOUNDARY_WRAP) return ix - sh; #else #error "project_for_bounds - only support CLAMP, MIRROR and WRAP." #endif } else { return ix; } } static __inline__ __device__ DIM2 project_for_bounds(const DIM2 sh, const DIM2 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM3 project_for_bounds(const DIM3 sh, const DIM3 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM4 project_for_bounds(const DIM4 sh, const DIM4 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM5 project_for_bounds(const DIM5 sh, const DIM5 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM6 project_for_bounds(const DIM6 sh, const DIM6 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM7 project_for_bounds(const DIM7 sh, const DIM7 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM8 project_for_bounds(const DIM8 sh, const DIM8 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } static __inline__ __device__ DIM9 project_for_bounds(const DIM9 sh, const DIM9 ix) { return indexCons(project_for_bounds(indexTail(sh), indexTail(ix)), project_for_bounds(indexHead(sh), indexHead(ix))); } #else /* * Bounds check handling for Constant. */ static __inline__ __device__ TyIn0 get0_for_constant_bounds(const ArrIn0 d_in0, const DIM1 sh, const DIM1 ix) { if (ix < 0) return boundary_const(); else if (ix >= sh) return boundary_const(); else return tex_get0(ix); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(const ArrIn0 d_in0, const DIM2 sh, const DIM2 ix) { if (ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(const ArrIn0 d_in0, const DIM3 sh, const DIM3 ix) { if (ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(const ArrIn0 d_in0, const DIM4 sh, const DIM4 ix) { if (ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(const ArrIn0 d_in0, const DIM5 sh, const DIM5 ix) { if (ix.a4 < 0 || ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a4 >= sh.a4 || ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(const ArrIn0 d_in0, const DIM6 sh, const DIM6 ix) { if (ix.a5 < 0 || ix.a4 < 0 || ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a5 >= sh.a5 || ix.a4 >= sh.a4 || ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(const ArrIn0 d_in0, const DIM7 sh, const DIM7 ix) { if (ix.a6 < 0 || ix.a5 < 0 || ix.a4 < 0 || ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a6 >= sh.a6 || ix.a5 >= sh.a5 || ix.a4 >= sh.a4 || ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(const ArrIn0 d_in0, const DIM8 sh, const DIM8 ix) { if (ix.a7 < 0 || ix.a6 < 0 || ix.a5 < 0 || ix.a4 < 0 || ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a7 >= sh.a7 || ix.a6 >= sh.a6 || ix.a5 >= sh.a5 || ix.a4 >= sh.a4 || ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } static __inline__ __device__ TyIn0 get0_for_constant_bounds(const ArrIn0 d_in0, const DIM9 sh, const DIM9 ix) { if (ix.a8 < 0 || ix.a7 < 0 || ix.a6 < 0 || ix.a5 < 0 || ix.a4 < 0 || ix.a3 < 0 || ix.a2 < 0 || ix.a1 < 0 || ix.a0 < 0) return boundary_const(); else if (ix.a8 >= sh.a8 || ix.a7 >= sh.a7 || ix.a6 >= sh.a6 || ix.a5 >= sh.a5 || ix.a4 >= sh.a4 || ix.a3 >= sh.a3 || ix.a2 >= sh.a2 || ix.a1 >= sh.a1 || ix.a0 >= sh.a0) return boundary_const(); else return tex_get0(toIndex(sh, ix)); } #endif /* * Getter function that handles indexing outside the array boundary. */ static inline __attribute__((device)) TyIn0 get0_for_stencil(ArrIn0 d_in0, ArrDimIn0 sh, ArrDimIn0 ix) { #if defined(BOUNDARY_CLAMP) || defined(BOUNDARY_MIRROR) || defined(BOUNDARY_WRAP) return tex_get0(toIndex(sh, project_for_bounds(sh, ix))); #else return get0_for_constant_bounds(d_in0, sh, ix); #endif } /* * The kernel. */ extern "C" __global__ void stencil ( ArrOut d_out, const ArrIn0 d_in0, const ArrDimIn0 d_in0_shape ) { Ix idx; const Ix gridSize = __umul24(blockDim.x, gridDim.x); for (idx = __umul24(blockDim.x, blockIdx.x) + threadIdx.x; idx < size(d_in0_shape); idx += gridSize) { set(d_out, idx, apply(gather0(d_in0, fromIndex(d_in0_shape, idx), d_in0_shape))); } }
Add 'const' qualifier to stencil functions.
Add 'const' qualifier to stencil functions. Ignore-this: 91152f8d6c12b2d85b132dff1ace2f81 darcs-hash:20110104235901-c3ac2-eebc5ddb76cb388a2ed2a7840ee21bf9ad61db18.gz
C++
bsd-3-clause
wilbowma/accelerate,wilbowma/accelerate,sjfloat/accelerate,robeverest/accelerate,rrnewton/accelerate,robeverest/accelerate
1b9b8406dc6faee07a4e1c91d4015572e2220563
OOInteraction/src/commands/CAddCalleesToView.cpp
OOInteraction/src/commands/CAddCalleesToView.cpp
/*********************************************************************************************************************** ** ** Copyright (c) 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "CAddCalleesToView.h" #include "VisualizationBase/src/items/ViewItem.h" #include "OOModel/src/declarations/Method.h" #include "OOModel/src/expressions/MethodCallExpression.h" namespace OOInteraction { CAddCalleesToView::CAddCalleesToView() :CommandWithDefaultArguments("addCallees", {""}) { } bool CAddCalleesToView::canInterpret(Visualization::Item* source, Visualization::Item* target, const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& cursor) { bool canInterpret = CommandWithDefaultArguments::canInterpret(source, target, commandTokens, cursor); auto ancestor = source->findAncestorWithNode(); if (!ancestor) return false; else return canInterpret && DCast<OOModel::Method>(ancestor->node()); } Interaction::CommandResult* CAddCalleesToView::executeWithArguments(Visualization::Item* source, Visualization::Item*, const QStringList& arguments, const std::unique_ptr<Visualization::Cursor>&) { auto ancestor = source->findAncestorWithNode(); auto name = arguments.at(0); auto view = ancestor->scene()->currentViewItem(); if (view) { auto callees_ = callees(ancestor->node()); auto pos = view->positionOfItem(ancestor->parent()); if (callees_.size() > 0) { Model::Node* actualNode; //TODO@cyril What if it is in the view, but not as a top-level item? if (pos.x() == -1) { view->insertColumn(0); actualNode = view->insertNode(ancestor->node(), 0, 0); pos = view->positionOfNode(actualNode); } else actualNode = ancestor->parent()->node(); view->insertColumn(pos.x() + 1); auto row = 0; //Make the first callee appear at the same height as the method view->addSpacing(pos.x() + 1, row++, actualNode); for (auto callee : callees_) view->insertNode(callee, pos.x() + 1, row++); } return new Interaction::CommandResult(); } else return new Interaction::CommandResult(new Interaction::CommandError("View " + name + " does not exist")); } QSet<OOModel::Method*> CAddCalleesToView::callees(Model::Node* parent) { QSet<OOModel::Method*> result; for (auto child : parent->children()) { if (auto call = DCast<OOModel::MethodCallExpression>(child)) if (call->methodDefinition()) result.insert(call->methodDefinition()); result.unite(callees(child)); } return result; } QString CAddCalleesToView::description(Visualization::Item*, Visualization::Item*, const QStringList&, const std::unique_ptr<Visualization::Cursor>&) { return "Add the callees of the current method to the current view"; } }
/*********************************************************************************************************************** ** ** Copyright (c) 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "CAddCalleesToView.h" #include "VisualizationBase/src/items/ViewItem.h" #include "OOModel/src/declarations/Method.h" #include "OOModel/src/expressions/MethodCallExpression.h" namespace OOInteraction { CAddCalleesToView::CAddCalleesToView() :CommandWithDefaultArguments("addCallees", {""}) { } bool CAddCalleesToView::canInterpret(Visualization::Item* source, Visualization::Item* target, const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& cursor) { bool canInterpret = CommandWithDefaultArguments::canInterpret(source, target, commandTokens, cursor); auto ancestor = source->findAncestorWithNode(); if (!ancestor) return false; else return canInterpret && DCast<OOModel::Method>(ancestor->node()); } Interaction::CommandResult* CAddCalleesToView::executeWithArguments(Visualization::Item* source, Visualization::Item*, const QStringList& arguments, const std::unique_ptr<Visualization::Cursor>&) { auto ancestor = source->findAncestorWithNode(); auto name = arguments.at(0); auto view = ancestor->scene()->currentViewItem(); if (view) { auto callees_ = callees(ancestor->node()); auto pos = view->positionOfItem(ancestor->parent()); if (callees_.size() > 0) { Model::Node* actualNode{}; //TODO@cyril What if it is in the view, but not as a top-level item? if (pos.x() == -1) { view->insertColumn(0); actualNode = view->insertNode(ancestor->node(), 0, 0); pos = view->positionOfNode(actualNode); } else actualNode = ancestor->parent()->node(); view->insertColumn(pos.x() + 1); auto row = 0; //Make the first callee appear at the same height as the method view->addSpacing(pos.x() + 1, row++, actualNode); for (auto callee : callees_) view->insertNode(callee, pos.x() + 1, row++); } return new Interaction::CommandResult(); } else return new Interaction::CommandResult(new Interaction::CommandError("View " + name + " does not exist")); } QSet<OOModel::Method*> CAddCalleesToView::callees(Model::Node* parent) { QSet<OOModel::Method*> result; for (auto child : parent->children()) { if (auto call = DCast<OOModel::MethodCallExpression>(child)) if (call->methodDefinition()) result.insert(call->methodDefinition()); result.unite(callees(child)); } return result; } QString CAddCalleesToView::description(Visualization::Item*, Visualization::Item*, const QStringList&, const std::unique_ptr<Visualization::Cursor>&) { return "Add the callees of the current method to the current view"; } }
Initialize to null.
Initialize to null.
C++
bsd-3-clause
lukedirtwalker/Envision,mgalbier/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,mgalbier/Envision,BalzGuenat/Envision,dimitar-asenov/Envision,mgalbier/Envision,lukedirtwalker/Envision,mgalbier/Envision,Vaishal-shah/Envision,BalzGuenat/Envision,BalzGuenat/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,Vaishal-shah/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,mgalbier/Envision,Vaishal-shah/Envision,dimitar-asenov/Envision,BalzGuenat/Envision,BalzGuenat/Envision,BalzGuenat/Envision,mgalbier/Envision,lukedirtwalker/Envision
f4ca71153ff7f416d5f0f1be28fcd5c642a483cc
Ouroboros/Source/oBase/tests/TESTcompression.cpp
Ouroboros/Source/oBase/tests/TESTcompression.cpp
/************************************************************************** * The MIT License * * Copyright (c) 2013 Antony Arciuolo. * * [email protected] * * * * Permission is hereby granted, free of charge, to any person obtaining * * a copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to * * the following conditions: * * * * The above copyright notice and this permission notice shall be * * included in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #include <oBase/gzip.h> #include <oBase/lzma.h> #include <oBase/snappy.h> #include <oBase/finally.h> #include <oBase/path.h> #include <oBase/throw.h> #include <oBase/timer.h> #include <oCore/filesystem.h> #include "../../test_services.h" namespace ouro { namespace tests { static void TestCompress(const void* _pSourceBuffer, size_t _SizeofSourceBuffer, compress_fn _Compress, decompress_fn _Decompress, size_t* _pCompressedSize) { size_t maxCompressedSize = _Compress(nullptr, 0, _pSourceBuffer, _SizeofSourceBuffer); void* compressed = new char[maxCompressedSize]; finally OSEFreeCompressed([&] { if (compressed) delete [] compressed; }); *_pCompressedSize = _Compress(compressed, maxCompressedSize, _pSourceBuffer, _SizeofSourceBuffer); oCHECK0(*_pCompressedSize != 0); size_t uncompressedSize = _Decompress(nullptr, 0, compressed, *_pCompressedSize); if (_SizeofSourceBuffer != uncompressedSize) oTHROW(protocol_error, "loaded and uncompressed sizes don't match"); void* uncompressed = malloc(uncompressedSize); finally OSEFreeUncompressed([&] { if (uncompressed) free(uncompressed); }); oCHECK0(0 != _Decompress(uncompressed, uncompressedSize, compressed, *_pCompressedSize)); oCHECK(!memcmp(_pSourceBuffer, uncompressed, uncompressedSize), "memcmp failed between uncompressed and loaded buffers"); } void TESTcompression(test_services& _Services) { static const char* TestPath = "Test/Geometry/buddha.obj"; size_t Size = 0; std::shared_ptr<char> pOBJBuffer = _Services.load_buffer(TestPath, &Size); double timeSnappy, timeLZMA, timeGZip; size_t CompressedSize0, CompressedSize1, CompressedSize2; timer t; TestCompress(pOBJBuffer.get(), Size, snappy_compress, snappy_decompress, &CompressedSize0); timeSnappy = t.seconds(); t.reset(); TestCompress(pOBJBuffer.get(), Size, lzma_compress, lzma_decompress, &CompressedSize1); timeLZMA = t.seconds(); t.reset(); TestCompress(pOBJBuffer.get(), Size, gzip_compress, gzip_decompress, &CompressedSize2); timeGZip = t.seconds(); t.reset(); sstring strUncompressed, strSnappy, strLZMA, strGZip, strSnappyTime, strLZMATime, strGZipTime; format_bytes(strUncompressed, Size, 2); format_bytes(strSnappyTime, CompressedSize0, 2); format_bytes(strLZMATime, CompressedSize1, 2); format_bytes(strGZip, CompressedSize2, 2); format_duration(strSnappyTime, timeSnappy, true); format_duration(strLZMATime, timeLZMA, true); format_duration(strGZipTime, timeGZip, true); _Services.report("Compressed %s from %s to Snappy: %s in %s, LZMA: %s in %s, GZip: %s in %s" , TestPath , strUncompressed.c_str() , strSnappy.c_str() , strSnappyTime.c_str() , strLZMA.c_str() , strLZMATime.c_str() , strGZip.c_str() , strGZipTime.c_str()); } } // namespace tests } // namespace ouro
/************************************************************************** * The MIT License * * Copyright (c) 2013 Antony Arciuolo. * * [email protected] * * * * Permission is hereby granted, free of charge, to any person obtaining * * a copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to * * the following conditions: * * * * The above copyright notice and this permission notice shall be * * included in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #include <oBase/gzip.h> #include <oBase/lzma.h> #include <oBase/snappy.h> #include <oBase/finally.h> #include <oBase/path.h> #include <oBase/throw.h> #include <oBase/timer.h> #include <oCore/filesystem.h> #include "../../test_services.h" namespace ouro { namespace tests { static void TestCompress(const void* _pSourceBuffer, size_t _SizeofSourceBuffer, compress_fn _Compress, decompress_fn _Decompress, size_t* _pCompressedSize) { size_t maxCompressedSize = _Compress(nullptr, 0, _pSourceBuffer, _SizeofSourceBuffer); void* compressed = new char[maxCompressedSize]; finally OSEFreeCompressed([&] { if (compressed) delete [] compressed; }); *_pCompressedSize = _Compress(compressed, maxCompressedSize, _pSourceBuffer, _SizeofSourceBuffer); oCHECK0(*_pCompressedSize != 0); size_t uncompressedSize = _Decompress(nullptr, 0, compressed, *_pCompressedSize); if (_SizeofSourceBuffer != uncompressedSize) oTHROW(protocol_error, "loaded and uncompressed sizes don't match"); void* uncompressed = malloc(uncompressedSize); finally OSEFreeUncompressed([&] { if (uncompressed) free(uncompressed); }); oCHECK0(0 != _Decompress(uncompressed, uncompressedSize, compressed, *_pCompressedSize)); oCHECK(!memcmp(_pSourceBuffer, uncompressed, uncompressedSize), "memcmp failed between uncompressed and loaded buffers"); } void TESTcompression(test_services& _Services) { static const char* TestPath = "Test/Geometry/buddha.obj"; size_t Size = 0; std::shared_ptr<char> pOBJBuffer = _Services.load_buffer(TestPath, &Size); double timeSnappy, timeLZMA, timeGZip; size_t CompressedSize0, CompressedSize1, CompressedSize2; timer t; TestCompress(pOBJBuffer.get(), Size, snappy_compress, snappy_decompress, &CompressedSize0); timeSnappy = t.seconds(); t.reset(); TestCompress(pOBJBuffer.get(), Size, lzma_compress, lzma_decompress, &CompressedSize1); timeLZMA = t.seconds(); t.reset(); TestCompress(pOBJBuffer.get(), Size, gzip_compress, gzip_decompress, &CompressedSize2); timeGZip = t.seconds(); t.reset(); sstring strUncompressed, strSnappy, strLZMA, strGZip, strSnappyTime, strLZMATime, strGZipTime; format_bytes(strUncompressed, Size, 2); format_bytes(strSnappy, CompressedSize0, 2); format_bytes(strLZMA, CompressedSize1, 2); format_bytes(strGZip, CompressedSize2, 2); format_duration(strSnappyTime, timeSnappy, true); format_duration(strLZMATime, timeLZMA, true); format_duration(strGZipTime, timeGZip, true); _Services.report("Compressed %s from %s to Snappy: %s in %s, LZMA: %s in %s, GZip: %s in %s" , TestPath , strUncompressed.c_str() , strSnappy.c_str() , strSnappyTime.c_str() , strLZMA.c_str() , strLZMATime.c_str() , strGZip.c_str() , strGZipTime.c_str()); } } // namespace tests } // namespace ouro
Fix magnitude string destination so reporting is valid.
Fix magnitude string destination so reporting is valid.
C++
mit
jiangzhu1212/oooii,jiangzhu1212/oooii,jiangzhu1212/oooii,jiangzhu1212/oooii,jiangzhu1212/oooii,jiangzhu1212/oooii,jiangzhu1212/oooii,jiangzhu1212/oooii,jiangzhu1212/oooii
45f145a29e70fbf85de877be764dd8f7646da09b
brains.cc
brains.cc
#include "actor.hh" #include "common.hh" #include "logger.hh" Actor* Actor::getClosestActor(int types) { if (visible_actors.empty()) return NULL; if (types == 0) types = ALL; Actor* closest = NULL; int mindist = viewDist+1; for (ActorPtrs::const_iterator it = visible_actors.begin(); it != visible_actors.end(); ++it) { int dist = mindist; if ((*it)->getType(this) & types) { if (closest == NULL || (dist = distance2d(x, y, (*it)->x, (*it)->y)) < mindist) { closest = *it; mindist = dist; } } } return closest; } int Actor::countActors(int types) const { if (visible_actors.empty()) return NULL; if (types == 0) types = ALL; int cnt = 0; for (ActorPtrs::const_iterator it = visible_actors.begin(); it != visible_actors.end(); ++it) if ((*it)->getType(this) & types) cnt++; return cnt; } bool Actor::moveTowards(int tx, int ty) { int dx = 0, dy = 0; if (tx > x) dx = 1; if (tx < x) dx = -1; if (ty > y) dy = 1; if (ty < y) dy = -1; if (this->move(dx, dy)) return true; if (dx && dy) { // Try non-diagonal int tdx = dx, tdy = dy; if (randbool()) dx = 0; else dy = 0; if (this->move(dx,dy)) return true; if (dx) { dx = 0; dy = tdy; } else { dx = tdx; ty = tdy; } if (this->move(dx,dy)) return true; } else if (dx) { // Try diagonal dy = randdir(); if (this->move(dx,dy)) return true; swapdir(dy); if (this->move(dx,dy)) return true; } else if (dy) { // Try diagonal dx = randdir(); if (this->move(dx,dy)) return true; swapdir(dx); if (this->move(dx,dy)) return true; } return false; } void Actor::moveAway(int tx, int ty) { int invx = -(tx - x) + x; int invy = -(ty - y) + y; if (moveTowards(invx, invy)) return; // Try some random directions for (int i = 0; i < 4; i++) { randdir(tx, ty); if (moveTowards(tx,ty)) return; } } void Actor::AI_human() { Actor* target = getClosestActor(EVIL_ACTORS); if (target) { if (target->type != IMP || manhattan_dist(x,y,target->x,target->y) < 3) { moveAway(target->x, target->y); return; } } AI_generic(); } void Actor::AI_demon() { int friendCount = countActors(EVIL_ACTORS); int enemyCount = countActors(GOOD_ACTORS); bool runaway = false; // Seek angels Actor* target = getClosestActor(GOOD_ACTORS); if (target) { // Only attack if superior numbers, right next to the enemy or archdemon if ((type == ARCHDEMON || possessing) && (friendCount > enemyCount || realType == ARCHDEMON || manhattan_dist(x,y,target->x,target->y) <= 1)) { moveTowards(target->x, target->y); return; } else if (!possessing) runaway = true; return; } // Seek humans target = getClosestActor(HUMAN); if (target) { // Remember target targetx = target->x; targety = target->y; moveTowards(target->x, target->y); return; } else if (runaway) moveAway(target->x, target->y); else AI_generic(); } void Actor::AI_angel() { Actor* target = getClosestActor(EVIL_ACTORS); if (!target) target = getClosestActor(HUMAN); if (target && !target->blessed) { // Don't go after blessed people // Remember target targetx = target->x; targety = target->y; // Decloak if near if (type != realType && manhattan_dist(x,y,target->x,target->y) <= 1) { Ability_ConcealDivinity decloak; decloak(this); } // Angels always attack fearlessly (or go blessing) moveTowards(target->x, target->y); return; } // Cloak if (type == realType) { Ability_ConcealDivinity cloak; cloak(this); return; } // Start search AI_generic(); } void Actor::AI_generic() { // Check if there is a door underneath if (getTilePtr()->ch == '/' && randint(1,3) < 3) { Ability_CloseDoor close; close(this); return; } // Go towards a random target if (targetx && targety && manhattan_dist(x,y,targetx,targety) >= 2) { if (moveTowards(targetx,targety)) return; } // Move randomly if (randbool()) { int tx, ty; randdir(tx, ty); this->move(tx, ty); } // Acquire new destination if (randint(realType == HUMAN ? 10 : 2) == 0) { targetx = randint(1, world->getWidth()-2); targety = randint(1, world->getHeight()-2); } }
#include "actor.hh" #include "common.hh" #include "logger.hh" Actor* Actor::getClosestActor(int types) { if (visible_actors.empty()) return NULL; if (types == 0) types = ALL; Actor* closest = NULL; int mindist = viewDist+1; for (ActorPtrs::const_iterator it = visible_actors.begin(); it != visible_actors.end(); ++it) { int dist = mindist; if ((*it)->getType(this) & types) { if (closest == NULL || (dist = distance2d(x, y, (*it)->x, (*it)->y)) < mindist) { closest = *it; mindist = dist; } } } return closest; } int Actor::countActors(int types) const { if (visible_actors.empty()) return NULL; if (types == 0) types = ALL; int cnt = 0; for (ActorPtrs::const_iterator it = visible_actors.begin(); it != visible_actors.end(); ++it) if ((*it)->getType(this) & types) cnt++; return cnt; } bool Actor::moveTowards(int tx, int ty) { int dx = 0, dy = 0; if (tx > x) dx = 1; if (tx < x) dx = -1; if (ty > y) dy = 1; if (ty < y) dy = -1; if (this->move(dx, dy)) return true; if (dx && dy) { // Try non-diagonal int tdx = dx, tdy = dy; if (randbool()) dx = 0; else dy = 0; if (this->move(dx,dy)) return true; if (dx) { dx = 0; dy = tdy; } else { dx = tdx; ty = tdy; } if (this->move(dx,dy)) return true; } else if (dx) { // Try diagonal dy = randdir(); if (this->move(dx,dy)) return true; swapdir(dy); if (this->move(dx,dy)) return true; } else if (dy) { // Try diagonal dx = randdir(); if (this->move(dx,dy)) return true; swapdir(dx); if (this->move(dx,dy)) return true; } return false; } void Actor::moveAway(int tx, int ty) { int invx = -(tx - x) + x; int invy = -(ty - y) + y; if (moveTowards(invx, invy)) return; // Try some random directions for (int i = 0; i < 4; i++) { randdir(tx, ty); if (moveTowards(tx,ty)) return; } } void Actor::AI_human() { Actor* target = getClosestActor(EVIL_ACTORS); if (target) { if (target->type != IMP || manhattan_dist(x,y,target->x,target->y) < 3) { moveAway(target->x, target->y); return; } } AI_generic(); } void Actor::AI_demon() { int friendCount = countActors(EVIL_ACTORS); int enemyCount = countActors(GOOD_ACTORS); bool runaway = false; // Seek angels Actor* target = getClosestActor(GOOD_ACTORS); if (target) { // Only attack if superior numbers, right next to the enemy or archdemon if ((type == ARCHDEMON || possessing) && (friendCount > enemyCount || realType == ARCHDEMON || manhattan_dist(x,y,target->x,target->y) <= 1)) { moveTowards(target->x, target->y); return; } else if (!possessing) { targetx = target->x; targety = target->y; runaway = true; } else { moveAway(target->x, target->y); return; } } // Seek humans target = getClosestActor(HUMAN); if (target) { // Remember target targetx = target->x; targety = target->y; moveTowards(target->x, target->y); return; } else if (runaway) moveAway(targetx, targety); else AI_generic(); } void Actor::AI_angel() { Actor* target = getClosestActor(EVIL_ACTORS); if (!target) target = getClosestActor(HUMAN); if (target && !target->blessed) { // Don't go after blessed people // Remember target targetx = target->x; targety = target->y; // Decloak if near if (type != realType && manhattan_dist(x,y,target->x,target->y) <= 1) { Ability_ConcealDivinity decloak; decloak(this); } // Angels always attack fearlessly (or go blessing) moveTowards(target->x, target->y); return; } // Cloak if (type == realType) { Ability_ConcealDivinity cloak; cloak(this); return; } // Start search AI_generic(); } void Actor::AI_generic() { // Check if there is a door underneath if (getTilePtr()->ch == '/' && randint(1,3) < 3) { Ability_CloseDoor close; close(this); return; } // Go towards a random target if (targetx && targety && manhattan_dist(x,y,targetx,targety) >= 2) { if (moveTowards(targetx,targety)) return; } // Move randomly if (randbool()) { int tx, ty; randdir(tx, ty); this->move(tx, ty); } // Acquire new destination if (randint(realType == HUMAN ? 10 : 2) == 0) { targetx = randint(1, world->getWidth()-2); targety = randint(1, world->getHeight()-2); } }
Fix broken demon AI.
Fix broken demon AI.
C++
mit
tapio/cotc
a2ec1912d7d91d4dcedd0e48dccc1c8138a3cef3
engine/audio/openal/OALAudioDevice.cpp
engine/audio/openal/OALAudioDevice.cpp
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../../core/Setup.h" #if OUZEL_COMPILE_OPENAL #if defined(__APPLE__) # include <TargetConditionals.h> #endif #if TARGET_OS_IOS || TARGET_OS_TV # include <objc/message.h> # include <objc/NSObjCRuntime.h> extern "C" id const AVAudioSessionCategoryAmbient; #endif #include "OALAudioDevice.hpp" #include "OALErrorCategory.hpp" #include "ALCErrorCategory.hpp" #include "../../core/Engine.hpp" #include "../../utils/Log.hpp" #ifndef AL_FORMAT_MONO_FLOAT32 # define AL_FORMAT_MONO_FLOAT32 0x10010 #endif #ifndef AL_FORMAT_STEREO_FLOAT32 # define AL_FORMAT_STEREO_FLOAT32 0x10011 #endif namespace ouzel::audio::openal { namespace { const ErrorCategory openALErrorCategory{}; const alc::ErrorCategory alcErrorCategory{}; } AudioDevice::AudioDevice(const Settings& settings, const std::function<void(std::uint32_t frames, std::uint32_t channels, std::uint32_t sampleRate, std::vector<float>& samples)>& initDataGetter): audio::AudioDevice(Driver::openAL, settings, initDataGetter) { #if TARGET_OS_IOS || TARGET_OS_TV id audioSession = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("AVAudioSession"), sel_getUid("sharedInstance")); // [AVAudioSession sharedInstance] if (!reinterpret_cast<BOOL (*)(id, SEL, id, id)>(&objc_msgSend)(audioSession, sel_getUid("setCategory:error:"), AVAudioSessionCategoryAmbient, nil)) // [audioSession setCategory:AVAudioSessionCategoryAmbient error:nil] throw std::runtime_error("Failed to set audio session category"); id currentRoute = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(audioSession, sel_getUid("currentRoute")); // [audioSession currentRoute] id outputs = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(currentRoute, sel_getUid("outputs")); // [currentRoute outputs] const auto count = reinterpret_cast<NSUInteger (*)(id, SEL)>(&objc_msgSend)(outputs, sel_getUid("count")); // [outputs count] NSUInteger maxChannelCount = 0; for (NSUInteger outputIndex = 0; outputIndex < count; ++outputIndex) { id output = reinterpret_cast<id (*)(id, SEL, NSUInteger)>(&objc_msgSend)(outputs, sel_getUid("objectAtIndex:"), outputIndex); // [outputs objectAtIndex:outputIndex] id channels = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(output, sel_getUid("channels")); // [output channels] const auto channelCount = reinterpret_cast<NSUInteger (*)(id, SEL)>(&objc_msgSend)(channels, sel_getUid("count")); // [channels count] if (channelCount > maxChannelCount) maxChannelCount = channelCount; } if (channels > maxChannelCount) channels = static_cast<std::uint32_t>(maxChannelCount); #endif const auto deviceName = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER); logger.log(Log::Level::info) << "Using " << deviceName << " for audio"; device = alcOpenDevice(deviceName); if (!device) throw std::runtime_error("Failed to open ALC device"); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to create ALC device"); ALCint majorVersion; alcGetIntegerv(device, ALC_MAJOR_VERSION, sizeof(majorVersion), &majorVersion); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to get major version"); apiMajorVersion = static_cast<std::uint16_t>(majorVersion); ALCint minorVersion; alcGetIntegerv(device, ALC_MINOR_VERSION, sizeof(minorVersion), &minorVersion); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to get minor version"); apiMinorVersion = static_cast<std::uint16_t>(minorVersion); logger.log(Log::Level::info) << "OpenAL version " << apiMajorVersion << '.' << apiMinorVersion; context = alcCreateContext(device, nullptr); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to create ALC context"); if (!context) throw std::runtime_error("Failed to create ALC context"); if (!alcMakeContextCurrent(context)) throw std::runtime_error("Failed to make ALC context current"); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to make ALC context current"); const auto audioRenderer = alGetString(AL_RENDERER); if (const auto error = alGetError(); error != AL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenAL renderer, error: " + std::to_string(error); else if (!audioRenderer) logger.log(Log::Level::warning) << "Failed to get OpenAL renderer"; else logger.log(Log::Level::info) << "Using " << audioRenderer << " audio renderer"; std::vector<std::string> extensions; const auto extensionsPtr = alGetString(AL_EXTENSIONS); if (const auto error = alGetError(); error != AL_NO_ERROR || !extensionsPtr) logger.log(Log::Level::warning) << "Failed to get OpenGL extensions"; else extensions = explodeString(std::string(extensionsPtr), ' '); logger.log(Log::Level::all) << "Supported OpenAL extensions: " << extensions; auto float32Supported = false; for (const std::string& extension : extensions) { if (extension == "AL_EXT_float32") float32Supported = true; } alGenSources(1, &sourceId); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL source"); alGenBuffers(static_cast<ALsizei>(bufferIds.size()), bufferIds.data()); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL buffers"); switch (channels) { case 1: { if (float32Supported) { format = AL_FORMAT_MONO_FLOAT32; sampleFormat = SampleFormat::float32; sampleSize = sizeof(float); } else { format = AL_FORMAT_MONO16; sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); } break; } case 2: { if (float32Supported) { format = AL_FORMAT_STEREO_FLOAT32; sampleFormat = SampleFormat::float32; sampleSize = sizeof(float); } else { format = AL_FORMAT_STEREO16; sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); } break; } case 4: { format = alGetEnumValue("AL_FORMAT_QUAD16"); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value"); sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); break; } case 6: { format = alGetEnumValue("AL_FORMAT_51CHN16"); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value"); sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); break; } case 7: { format = alGetEnumValue("AL_FORMAT_61CHN16"); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value"); sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); break; } case 8: { format = alGetEnumValue("AL_FORMAT_71CHN16"); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value"); sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); break; } default: throw std::runtime_error("Invalid channel count"); } } AudioDevice::~AudioDevice() { #if !defined(__EMSCRIPTEN__) running = false; if (audioThread.isJoinable()) audioThread.join(); #endif if (context) { alcMakeContextCurrent(context); if (sourceId) { alSourceStop(sourceId); alSourcei(sourceId, AL_BUFFER, 0); alDeleteSources(1, &sourceId); alGetError(); } for (const auto bufferId : bufferIds) { if (bufferId) { alDeleteBuffers(1, &bufferId); alGetError(); } } alcMakeContextCurrent(nullptr); alcDestroyContext(context); } if (device) alcCloseDevice(device); } void AudioDevice::start() { getData(bufferSize / (channels * sampleSize), data); alBufferData(bufferIds[0], format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); getData(bufferSize / (channels * sampleSize), data); alBufferData(bufferIds[1], format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); alSourceQueueBuffers(sourceId, static_cast<ALsizei>(bufferIds.size()), bufferIds.data()); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to queue OpenAL buffers"); alSourcePlay(sourceId); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to play OpenAL source"); if (!alcMakeContextCurrent(nullptr)) throw std::runtime_error("Failed to unset current ALC context"); #if !defined(__EMSCRIPTEN__) running = true; audioThread = thread::Thread(&AudioDevice::run, this); #endif } void AudioDevice::stop() { #if !defined(__EMSCRIPTEN__) running = false; if (audioThread.isJoinable()) audioThread.join(); #endif if (!alcMakeContextCurrent(context)) throw std::runtime_error("Failed to make ALC context current"); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to make ALC context current"); alSourceStop(sourceId); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to stop OpenAL source"); } void AudioDevice::process() { ALint buffersProcessed; alGetSourcei(sourceId, AL_BUFFERS_PROCESSED, &buffersProcessed); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to get processed buffer count"); // requeue all processed buffers for (ALint i = 0; i < buffersProcessed; ++i) { ALuint buffer; alSourceUnqueueBuffers(sourceId, 1, &buffer); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to unqueue OpenAL buffer"); getData(bufferSize / (channels * sampleSize), data); alBufferData(buffer, format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); alSourceQueueBuffers(sourceId, 1, &buffer); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to queue OpenAL buffer"); } if (buffersProcessed == static_cast<ALint>(bufferIds.size())) { ALint state; alGetSourcei(sourceId, AL_SOURCE_STATE, &state); if (state != AL_PLAYING) { alSourcePlay(sourceId); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to play OpenAL source"); } } } void AudioDevice::run() { thread::setCurrentThreadName("Audio"); if (!alcMakeContextCurrent(context)) throw std::runtime_error("Failed to make ALC context current"); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to make ALC context current"); #if !defined(__EMSCRIPTEN__) while (running) { try { process(); } catch (const std::exception& e) { ouzel::logger.log(ouzel::Log::Level::error) << e.what(); } } #endif } } #endif
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../../core/Setup.h" #if OUZEL_COMPILE_OPENAL #if defined(__APPLE__) # include <TargetConditionals.h> #endif #if TARGET_OS_IOS || TARGET_OS_TV # include <objc/message.h> # include <objc/NSObjCRuntime.h> extern "C" id const AVAudioSessionCategoryAmbient; #endif #include "OALAudioDevice.hpp" #include "OALErrorCategory.hpp" #include "ALCErrorCategory.hpp" #include "../../core/Engine.hpp" #include "../../utils/Log.hpp" #ifndef AL_FORMAT_MONO_FLOAT32 # define AL_FORMAT_MONO_FLOAT32 0x10010 #endif #ifndef AL_FORMAT_STEREO_FLOAT32 # define AL_FORMAT_STEREO_FLOAT32 0x10011 #endif namespace ouzel::audio::openal { namespace { const ErrorCategory openALErrorCategory{}; const alc::ErrorCategory alcErrorCategory{}; } AudioDevice::AudioDevice(const Settings& settings, const std::function<void(std::uint32_t frames, std::uint32_t channels, std::uint32_t sampleRate, std::vector<float>& samples)>& initDataGetter): audio::AudioDevice(Driver::openAL, settings, initDataGetter) { #if TARGET_OS_IOS || TARGET_OS_TV id audioSession = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("AVAudioSession"), sel_getUid("sharedInstance")); // [AVAudioSession sharedInstance] if (!reinterpret_cast<BOOL (*)(id, SEL, id, id)>(&objc_msgSend)(audioSession, sel_getUid("setCategory:error:"), AVAudioSessionCategoryAmbient, nil)) // [audioSession setCategory:AVAudioSessionCategoryAmbient error:nil] throw std::runtime_error("Failed to set audio session category"); id currentRoute = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(audioSession, sel_getUid("currentRoute")); // [audioSession currentRoute] id outputs = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(currentRoute, sel_getUid("outputs")); // [currentRoute outputs] const auto count = reinterpret_cast<NSUInteger (*)(id, SEL)>(&objc_msgSend)(outputs, sel_getUid("count")); // [outputs count] NSUInteger maxChannelCount = 0; for (NSUInteger outputIndex = 0; outputIndex < count; ++outputIndex) { id output = reinterpret_cast<id (*)(id, SEL, NSUInteger)>(&objc_msgSend)(outputs, sel_getUid("objectAtIndex:"), outputIndex); // [outputs objectAtIndex:outputIndex] id channels = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(output, sel_getUid("channels")); // [output channels] const auto channelCount = reinterpret_cast<NSUInteger (*)(id, SEL)>(&objc_msgSend)(channels, sel_getUid("count")); // [channels count] if (channelCount > maxChannelCount) maxChannelCount = channelCount; } if (channels > maxChannelCount) channels = static_cast<std::uint32_t>(maxChannelCount); #endif const auto deviceName = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER); logger.log(Log::Level::info) << "Using " << deviceName << " for audio"; device = alcOpenDevice(deviceName); if (!device) throw std::runtime_error("Failed to open ALC device"); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to create ALC device"); ALCint majorVersion; alcGetIntegerv(device, ALC_MAJOR_VERSION, sizeof(majorVersion), &majorVersion); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to get major version"); apiMajorVersion = static_cast<std::uint16_t>(majorVersion); ALCint minorVersion; alcGetIntegerv(device, ALC_MINOR_VERSION, sizeof(minorVersion), &minorVersion); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to get minor version"); apiMinorVersion = static_cast<std::uint16_t>(minorVersion); logger.log(Log::Level::info) << "OpenAL version " << apiMajorVersion << '.' << apiMinorVersion; context = alcCreateContext(device, nullptr); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to create ALC context"); if (!context) throw std::runtime_error("Failed to create ALC context"); if (!alcMakeContextCurrent(context)) throw std::runtime_error("Failed to make ALC context current"); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to make ALC context current"); const auto audioRenderer = alGetString(AL_RENDERER); if (const auto error = alGetError(); error != AL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenAL renderer, error: " + std::to_string(error); else if (!audioRenderer) logger.log(Log::Level::warning) << "Failed to get OpenAL renderer"; else logger.log(Log::Level::info) << "Using " << audioRenderer << " audio renderer"; std::vector<std::string> extensions; const auto extensionsPtr = alGetString(AL_EXTENSIONS); if (const auto error = alGetError(); error != AL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extensions: " + std::to_string(error); else if (!extensionsPtr) logger.log(Log::Level::warning) << "Failed to get OpenGL extensions"; else extensions = explodeString(std::string(extensionsPtr), ' '); logger.log(Log::Level::all) << "Supported OpenAL extensions: " << extensions; auto float32Supported = false; for (const std::string& extension : extensions) { if (extension == "AL_EXT_float32") float32Supported = true; } alGenSources(1, &sourceId); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL source"); alGenBuffers(static_cast<ALsizei>(bufferIds.size()), bufferIds.data()); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL buffers"); switch (channels) { case 1: { if (float32Supported) { format = AL_FORMAT_MONO_FLOAT32; sampleFormat = SampleFormat::float32; sampleSize = sizeof(float); } else { format = AL_FORMAT_MONO16; sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); } break; } case 2: { if (float32Supported) { format = AL_FORMAT_STEREO_FLOAT32; sampleFormat = SampleFormat::float32; sampleSize = sizeof(float); } else { format = AL_FORMAT_STEREO16; sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); } break; } case 4: { format = alGetEnumValue("AL_FORMAT_QUAD16"); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value"); sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); break; } case 6: { format = alGetEnumValue("AL_FORMAT_51CHN16"); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value"); sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); break; } case 7: { format = alGetEnumValue("AL_FORMAT_61CHN16"); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value"); sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); break; } case 8: { format = alGetEnumValue("AL_FORMAT_71CHN16"); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to create OpenAL enum value"); sampleFormat = SampleFormat::signedInt16; sampleSize = sizeof(std::int16_t); break; } default: throw std::runtime_error("Invalid channel count"); } } AudioDevice::~AudioDevice() { #if !defined(__EMSCRIPTEN__) running = false; if (audioThread.isJoinable()) audioThread.join(); #endif if (context) { alcMakeContextCurrent(context); if (sourceId) { alSourceStop(sourceId); alSourcei(sourceId, AL_BUFFER, 0); alDeleteSources(1, &sourceId); alGetError(); } for (const auto bufferId : bufferIds) { if (bufferId) { alDeleteBuffers(1, &bufferId); alGetError(); } } alcMakeContextCurrent(nullptr); alcDestroyContext(context); } if (device) alcCloseDevice(device); } void AudioDevice::start() { getData(bufferSize / (channels * sampleSize), data); alBufferData(bufferIds[0], format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); getData(bufferSize / (channels * sampleSize), data); alBufferData(bufferIds[1], format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); alSourceQueueBuffers(sourceId, static_cast<ALsizei>(bufferIds.size()), bufferIds.data()); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to queue OpenAL buffers"); alSourcePlay(sourceId); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to play OpenAL source"); if (!alcMakeContextCurrent(nullptr)) throw std::runtime_error("Failed to unset current ALC context"); #if !defined(__EMSCRIPTEN__) running = true; audioThread = thread::Thread(&AudioDevice::run, this); #endif } void AudioDevice::stop() { #if !defined(__EMSCRIPTEN__) running = false; if (audioThread.isJoinable()) audioThread.join(); #endif if (!alcMakeContextCurrent(context)) throw std::runtime_error("Failed to make ALC context current"); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to make ALC context current"); alSourceStop(sourceId); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to stop OpenAL source"); } void AudioDevice::process() { ALint buffersProcessed; alGetSourcei(sourceId, AL_BUFFERS_PROCESSED, &buffersProcessed); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to get processed buffer count"); // requeue all processed buffers for (ALint i = 0; i < buffersProcessed; ++i) { ALuint buffer; alSourceUnqueueBuffers(sourceId, 1, &buffer); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to unqueue OpenAL buffer"); getData(bufferSize / (channels * sampleSize), data); alBufferData(buffer, format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); alSourceQueueBuffers(sourceId, 1, &buffer); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to queue OpenAL buffer"); } if (buffersProcessed == static_cast<ALint>(bufferIds.size())) { ALint state; alGetSourcei(sourceId, AL_SOURCE_STATE, &state); if (state != AL_PLAYING) { alSourcePlay(sourceId); if (const auto error = alGetError(); error != AL_NO_ERROR) throw std::system_error(error, openALErrorCategory, "Failed to play OpenAL source"); } } } void AudioDevice::run() { thread::setCurrentThreadName("Audio"); if (!alcMakeContextCurrent(context)) throw std::runtime_error("Failed to make ALC context current"); if (const auto error = alcGetError(device); error != ALC_NO_ERROR) throw std::system_error(error, alcErrorCategory, "Failed to make ALC context current"); #if !defined(__EMSCRIPTEN__) while (running) { try { process(); } catch (const std::exception& e) { ouzel::logger.log(ouzel::Log::Level::error) << e.what(); } } #endif } } #endif
Print the error if failed to get OpenAL extensions
Print the error if failed to get OpenAL extensions
C++
unlicense
elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
e7a2ec61c5587b3550f1eef6278d2941aaca321f
libraries/blockchain/include/bts/blockchain/config.hpp
libraries/blockchain/include/bts/blockchain/config.hpp
#pragma once #include <stdint.h> /* Comment out this line for a non-test network */ // #define BTS_TEST_NETWORK // #define BTS_TEST_NETWORK_VERSION 10 // autogenerated /** @file bts/blockchain/config.hpp * @brief Defines global constants that determine blockchain behavior */ #define BTS_BLOCKCHAIN_VERSION 4 #define BTS_BLOCKCHAIN_DATABASE_VERSION 10 /** * The address prepended to string representation of * addresses. * * Changing these parameters will result in a hard fork. */ #define BTS_ADDRESS_PREFIX "PLS" #define BTS_BLOCKCHAIN_SYMBOL "PLS" #define BTS_BLOCKCHAIN_NAME "BitShares PLAY" #define BTS_BLOCKCHAIN_DESCRIPTION "BitShares PLAY DryRun Network" #define BTS_BLOCKCHAIN_PRECISION 100000 #define BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE 10000 #define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC int64_t(10) #define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR ((60*60)/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC) #define BTS_BLOCKCHAIN_BLOCKS_PER_DAY (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*int64_t(24)) #define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*int64_t(365)) #define BTS_BLOCKCHAIN_NUM_DELEGATES uint32_t(101) #define BTS_MAX_DELEGATE_PAY_PER_BLOCK int64_t( 50 * BTS_BLOCKCHAIN_PRECISION ) // 50 XTS #define BTS_BLOCKCHAIN_MAX_UNDO_HISTORY ( BTS_BLOCKCHAIN_BLOCKS_PER_HOUR * 2 ) #define BTS_BLOCKCHAIN_MAX_SLATE_SIZE (BTS_BLOCKCHAIN_NUM_DELEGATES + (BTS_BLOCKCHAIN_NUM_DELEGATES/10)) #define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC (60*60*24*2) #define BTS_BLOCKCHAIN_MAX_MEMO_SIZE 19 // bytes #define BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE 32 // bytes #define BTS_BLOCKCHAIN_MAX_EXTENDED_MEMO_SIZE (BTS_BLOCKCHAIN_MAX_MEMO_SIZE + BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE) /** * The maximum amount that can be issued for user assets. * * 10^18 / 2^63 < 1 however, to support representing all share values as a double in * languages like java script, we must stay within the epsilon so * * 10^15 / 2^53 < 1 allows all values to be represented as a double or an int64 */ #define BTS_BLOCKCHAIN_MAX_SHARES (1000*1000*int64_t(1000)*1000*int64_t(1000)) #define BTS_BLOCKCHAIN_MIN_NAME_SIZE 1 #define BTS_BLOCKCHAIN_MAX_NAME_SIZE 63 #define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE (1024*64) #define BTS_BLOCKCHAIN_MAX_SUB_SYMBOL_SIZE 8 // characters #define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE 3 // characters #define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE 12 // characters #define BTS_BLOCKCHAIN_MIN_BURN_FEE BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS #ifdef BTS_TEST_NETWORK #define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC 10 #else #define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC (60*60) // 1 hour #endif #define BTS_BLOCKCHAIN_MIN_FEEDS ((BTS_BLOCKCHAIN_NUM_DELEGATES/2) + 1) #define BTS_BLOCKCHAIN_MINIMUM_SHORT_ORDER_SIZE (BTS_BLOCKCHAIN_PRECISION*100) #define BTS_BLOCKCHAIN_MIN_YIELD_PERIOD_SEC (60*60*24) // 24 hours #define BTS_BLOCKCHAIN_MAX_YIELD_PERIOD_SEC (BTS_BLOCKCHAIN_BLOCKS_PER_YEAR * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC) // 1 year #ifdef BTS_TEST_NETWORK #define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC (2*60*60) // 2 hours #else #define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC (30*24*60*60) // 1 month #endif #define BTS_BLOCKCHAIN_MCALL_D2C_NUMERATOR 1 #define BTS_BLOCKCHAIN_MCALL_D2C_DENOMINATOR 2 // TODO: This stuff only matters for propagation throttling; should go somewhere else #define BTS_BLOCKCHAIN_DEFAULT_RELAY_FEE 10000 // XTS #define BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND 1 // (10) #define BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE 10 // (BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)
#pragma once #include <stdint.h> /* Comment out this line for a non-test network */ // #define BTS_TEST_NETWORK // #define BTS_TEST_NETWORK_VERSION 10 // autogenerated /** @file bts/blockchain/config.hpp * @brief Defines global constants that determine blockchain behavior */ #define BTS_BLOCKCHAIN_VERSION 20 #define BTS_BLOCKCHAIN_DATABASE_VERSION 11 /** * The address prepended to string representation of * addresses. * * Changing these parameters will result in a hard fork. */ #define BTS_ADDRESS_PREFIX "PLS" #define BTS_BLOCKCHAIN_SYMBOL "PLS" #define BTS_BLOCKCHAIN_NAME "BitShares PLAY" #define BTS_BLOCKCHAIN_DESCRIPTION "BitShares PLAY DryRun Network" #define BTS_BLOCKCHAIN_PRECISION 100000 #define BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE 10000 #define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC int64_t(10) #define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR ((60*60)/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC) #define BTS_BLOCKCHAIN_BLOCKS_PER_DAY (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*int64_t(24)) #define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*int64_t(365)) #define BTS_BLOCKCHAIN_NUM_DELEGATES uint32_t(101) #define BTS_MAX_DELEGATE_PAY_PER_BLOCK int64_t( 50 * BTS_BLOCKCHAIN_PRECISION ) // 50 XTS #define BTS_BLOCKCHAIN_MAX_UNDO_HISTORY ( BTS_BLOCKCHAIN_BLOCKS_PER_HOUR * 2 ) #define BTS_BLOCKCHAIN_MAX_SLATE_SIZE (BTS_BLOCKCHAIN_NUM_DELEGATES + (BTS_BLOCKCHAIN_NUM_DELEGATES/10)) #define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC (60*60*24*2) #define BTS_BLOCKCHAIN_MAX_MEMO_SIZE 19 // bytes #define BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE 32 // bytes #define BTS_BLOCKCHAIN_MAX_EXTENDED_MEMO_SIZE (BTS_BLOCKCHAIN_MAX_MEMO_SIZE + BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE) /** * The maximum amount that can be issued for user assets. * * 10^18 / 2^63 < 1 however, to support representing all share values as a double in * languages like java script, we must stay within the epsilon so * * 10^15 / 2^53 < 1 allows all values to be represented as a double or an int64 */ #define BTS_BLOCKCHAIN_MAX_SHARES (1000*1000*int64_t(1000)*1000*int64_t(1000)) #define BTS_BLOCKCHAIN_MIN_NAME_SIZE 1 #define BTS_BLOCKCHAIN_MAX_NAME_SIZE 63 #define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE (1024*64) #define BTS_BLOCKCHAIN_MAX_SUB_SYMBOL_SIZE 8 // characters #define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE 3 // characters #define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE 12 // characters #define BTS_BLOCKCHAIN_MIN_BURN_FEE BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS #ifdef BTS_TEST_NETWORK #define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC 10 #else #define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC (60*60) // 1 hour #endif #define BTS_BLOCKCHAIN_MIN_FEEDS ((BTS_BLOCKCHAIN_NUM_DELEGATES/2) + 1) #define BTS_BLOCKCHAIN_MINIMUM_SHORT_ORDER_SIZE (BTS_BLOCKCHAIN_PRECISION*100) #define BTS_BLOCKCHAIN_MIN_YIELD_PERIOD_SEC (60*60*24) // 24 hours #define BTS_BLOCKCHAIN_MAX_YIELD_PERIOD_SEC (BTS_BLOCKCHAIN_BLOCKS_PER_YEAR * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC) // 1 year #ifdef BTS_TEST_NETWORK #define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC (2*60*60) // 2 hours #else #define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC (30*24*60*60) // 1 month #endif #define BTS_BLOCKCHAIN_MCALL_D2C_NUMERATOR 1 #define BTS_BLOCKCHAIN_MCALL_D2C_DENOMINATOR 2 // TODO: This stuff only matters for propagation throttling; should go somewhere else #define BTS_BLOCKCHAIN_DEFAULT_RELAY_FEE 10000 // XTS #define BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND 1 // (10) #define BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE 10 // (BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)
bump blockchain version
bump blockchain version
C++
unlicense
dacsunlimited/dac_play,bitsuperlab/cpp-play,bitsuperlab/cpp-play,dacsunlimited/dac_play,bitsuperlab/cpp-play,bitsuperlab/cpp-play,dacsunlimited/dac_play,dacsunlimited/dac_play,dacsunlimited/dac_play,bitsuperlab/cpp-play,dacsunlimited/dac_play,bitsuperlab/cpp-play
e6e3fd721f730f03889322090a0251696c91461b
test/misc/stringifier_insert_double.cc
test/misc/stringifier_insert_double.cc
/* ** Copyright 2011 Merethis ** ** This file is part of Centreon Clib. ** ** Centreon Clib is free software: you can redistribute it ** and/or modify it under the terms of the GNU Affero General Public ** License as published by the Free Software Foundation, either version ** 3 of the License, or (at your option) any later version. ** ** Centreon Clib is distributed in the hope that it will be ** useful, but WITHOUT ANY WARRANTY; without even the implied warranty ** of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Affero General Public License for more details. ** ** You should have received a copy of the GNU Affero General Public ** License along with Centreon Clib. If not, see ** <http://www.gnu.org/licenses/>. */ #include <ios> #include <sstream> #include <string.h> #include <float.h> #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check the stringifier insert double. * * @return 0 on success. */ int main() { stringifier buffer; buffer << static_cast<double>(DBL_MIN); buffer << static_cast<double>(DBL_MAX); std::ostringstream oss; oss << std::fixed << DBL_MIN << DBL_MAX; return (strcmp(buffer.data(), oss.str().c_str())); }
/* ** Copyright 2011 Merethis ** ** This file is part of Centreon Clib. ** ** Centreon Clib is free software: you can redistribute it ** and/or modify it under the terms of the GNU Affero General Public ** License as published by the Free Software Foundation, either version ** 3 of the License, or (at your option) any later version. ** ** Centreon Clib is distributed in the hope that it will be ** useful, but WITHOUT ANY WARRANTY; without even the implied warranty ** of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Affero General Public License for more details. ** ** You should have received a copy of the GNU Affero General Public ** License along with Centreon Clib. If not, see ** <http://www.gnu.org/licenses/>. */ #include <float.h> #include <math.h> #include <sstream> #include <stdlib.h> #include "com/centreon/misc/stringifier.hh" using namespace com::centreon::misc; /** * Check that double are properly written by stringifier. * * @param[in] d Double to write and test. * * @return true if check succeed. */ static bool check_double(double d) { stringifier buffer; buffer << d; char* ptr(NULL); double converted(strtod(buffer.data(), &ptr)); return (ptr && !*ptr && (fabs(d - converted) // Roughly 0.1% error margin. <= (fabs(d / 1000) + 2 * DBL_EPSILON))); } /** * Check the stringifier insert double. * * @return 0 on success. */ int main() { return (!check_double(DBL_MIN) || !check_double(DBL_MAX) || !check_double(0.0) || !check_double(1.1) || !check_double(-1.456657563)); }
Fix one unit test.
Fix one unit test.
C++
apache-2.0
centreon/centreon-clib,centreon/centreon-clib,centreon/centreon-clib
e2dacee9cdaf294dbd9e0b03774bf950c5ac68cc
src/pdf/SkPDFUtils.cpp
src/pdf/SkPDFUtils.cpp
/* * Copyright (C) 2011 Google 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 "SkPaint.h" #include "SkPath.h" #include "SkPDFUtils.h" #include "SkStream.h" #include "SkString.h" #include "SkPDFTypes.h" // static SkPDFArray* SkPDFUtils::MatrixToArray(const SkMatrix& matrix) { SkScalar values[6]; if (!matrix.asAffine(values)) { SkMatrix::SetAffineIdentity(values); } SkPDFArray* result = new SkPDFArray; result->reserve(6); for (size_t i = 0; i < SK_ARRAY_COUNT(values); i++) { result->appendScalar(values[i]); } return result; } // static void SkPDFUtils::AppendTransform(const SkMatrix& matrix, SkWStream* content) { SkScalar values[6]; if (!matrix.asAffine(values)) { SkMatrix::SetAffineIdentity(values); } for (size_t i = 0; i < SK_ARRAY_COUNT(values); i++) { SkPDFScalar::Append(values[i], content); content->writeText(" "); } content->writeText("cm\n"); } // static void SkPDFUtils::MoveTo(SkScalar x, SkScalar y, SkWStream* content) { SkPDFScalar::Append(x, content); content->writeText(" "); SkPDFScalar::Append(y, content); content->writeText(" m\n"); } // static void SkPDFUtils::AppendLine(SkScalar x, SkScalar y, SkWStream* content) { SkPDFScalar::Append(x, content); content->writeText(" "); SkPDFScalar::Append(y, content); content->writeText(" l\n"); } // static void SkPDFUtils::AppendCubic(SkScalar ctl1X, SkScalar ctl1Y, SkScalar ctl2X, SkScalar ctl2Y, SkScalar dstX, SkScalar dstY, SkWStream* content) { SkString cmd("y\n"); SkPDFScalar::Append(ctl1X, content); content->writeText(" "); SkPDFScalar::Append(ctl1Y, content); content->writeText(" "); if (ctl2X != dstX || ctl2Y != dstY) { cmd.set("c\n"); SkPDFScalar::Append(ctl2X, content); content->writeText(" "); SkPDFScalar::Append(ctl2Y, content); content->writeText(" "); } SkPDFScalar::Append(dstX, content); content->writeText(" "); SkPDFScalar::Append(dstY, content); content->writeText(" "); content->writeText(cmd.c_str()); } // static void SkPDFUtils::AppendRectangle(const SkRect& rect, SkWStream* content) { // Skia has 0,0 at top left, pdf at bottom left. Do the right thing. SkScalar bottom = SkMinScalar(rect.fBottom, rect.fTop); SkPDFScalar::Append(rect.fLeft, content); content->writeText(" "); SkPDFScalar::Append(bottom, content); content->writeText(" "); SkPDFScalar::Append(rect.width(), content); content->writeText(" "); SkPDFScalar::Append(rect.height(), content); content->writeText(" re\n"); } // static void SkPDFUtils::EmitPath(const SkPath& path, SkWStream* content) { SkPoint args[4]; SkPath::Iter iter(path, false); for (SkPath::Verb verb = iter.next(args); verb != SkPath::kDone_Verb; verb = iter.next(args)) { // args gets all the points, even the implicit first point. switch (verb) { case SkPath::kMove_Verb: MoveTo(args[0].fX, args[0].fY, content); break; case SkPath::kLine_Verb: AppendLine(args[1].fX, args[1].fY, content); break; case SkPath::kQuad_Verb: { // Convert quad to cubic (degree elevation). http://goo.gl/vS4i const SkScalar three = SkIntToScalar(3); args[1].scale(SkIntToScalar(2)); SkScalar ctl1X = SkScalarDiv(args[0].fX + args[1].fX, three); SkScalar ctl1Y = SkScalarDiv(args[0].fY + args[1].fY, three); SkScalar ctl2X = SkScalarDiv(args[2].fX + args[1].fX, three); SkScalar ctl2Y = SkScalarDiv(args[2].fY + args[1].fY, three); AppendCubic(ctl1X, ctl1Y, ctl2X, ctl2Y, args[2].fX, args[2].fY, content); break; } case SkPath::kCubic_Verb: AppendCubic(args[1].fX, args[1].fY, args[2].fX, args[2].fY, args[3].fX, args[3].fY, content); break; case SkPath::kClose_Verb: ClosePath(content); break; default: SkASSERT(false); break; } } } // static void SkPDFUtils::ClosePath(SkWStream* content) { content->writeText("h\n"); } // static void SkPDFUtils::PaintPath(SkPaint::Style style, SkPath::FillType fill, SkWStream* content) { if (style == SkPaint::kFill_Style) content->writeText("f"); else if (style == SkPaint::kStrokeAndFill_Style) content->writeText("B"); else if (style == SkPaint::kStroke_Style) content->writeText("S"); if (style != SkPaint::kStroke_Style) { NOT_IMPLEMENTED(fill == SkPath::kInverseEvenOdd_FillType, false); NOT_IMPLEMENTED(fill == SkPath::kInverseWinding_FillType, false); if (fill == SkPath::kEvenOdd_FillType) content->writeText("*"); } content->writeText("\n"); } // static void SkPDFUtils::StrokePath(SkWStream* content) { SkPDFUtils::PaintPath( SkPaint::kStroke_Style, SkPath::kWinding_FillType, content); } // static void SkPDFUtils::DrawFormXObject(int objectIndex, SkWStream* content) { content->writeText("/X"); content->writeDecAsText(objectIndex); content->writeText(" Do\n"); } // static void SkPDFUtils::ApplyGraphicState(int objectIndex, SkWStream* content) { content->writeText("/G"); content->writeDecAsText(objectIndex); content->writeText(" gs\n"); }
/* * Copyright (C) 2011 Google 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 "SkGeometry.h" #include "SkPaint.h" #include "SkPath.h" #include "SkPDFUtils.h" #include "SkStream.h" #include "SkString.h" #include "SkPDFTypes.h" // static SkPDFArray* SkPDFUtils::MatrixToArray(const SkMatrix& matrix) { SkScalar values[6]; if (!matrix.asAffine(values)) { SkMatrix::SetAffineIdentity(values); } SkPDFArray* result = new SkPDFArray; result->reserve(6); for (size_t i = 0; i < SK_ARRAY_COUNT(values); i++) { result->appendScalar(values[i]); } return result; } // static void SkPDFUtils::AppendTransform(const SkMatrix& matrix, SkWStream* content) { SkScalar values[6]; if (!matrix.asAffine(values)) { SkMatrix::SetAffineIdentity(values); } for (size_t i = 0; i < SK_ARRAY_COUNT(values); i++) { SkPDFScalar::Append(values[i], content); content->writeText(" "); } content->writeText("cm\n"); } // static void SkPDFUtils::MoveTo(SkScalar x, SkScalar y, SkWStream* content) { SkPDFScalar::Append(x, content); content->writeText(" "); SkPDFScalar::Append(y, content); content->writeText(" m\n"); } // static void SkPDFUtils::AppendLine(SkScalar x, SkScalar y, SkWStream* content) { SkPDFScalar::Append(x, content); content->writeText(" "); SkPDFScalar::Append(y, content); content->writeText(" l\n"); } // static void SkPDFUtils::AppendCubic(SkScalar ctl1X, SkScalar ctl1Y, SkScalar ctl2X, SkScalar ctl2Y, SkScalar dstX, SkScalar dstY, SkWStream* content) { SkString cmd("y\n"); SkPDFScalar::Append(ctl1X, content); content->writeText(" "); SkPDFScalar::Append(ctl1Y, content); content->writeText(" "); if (ctl2X != dstX || ctl2Y != dstY) { cmd.set("c\n"); SkPDFScalar::Append(ctl2X, content); content->writeText(" "); SkPDFScalar::Append(ctl2Y, content); content->writeText(" "); } SkPDFScalar::Append(dstX, content); content->writeText(" "); SkPDFScalar::Append(dstY, content); content->writeText(" "); content->writeText(cmd.c_str()); } // static void SkPDFUtils::AppendRectangle(const SkRect& rect, SkWStream* content) { // Skia has 0,0 at top left, pdf at bottom left. Do the right thing. SkScalar bottom = SkMinScalar(rect.fBottom, rect.fTop); SkPDFScalar::Append(rect.fLeft, content); content->writeText(" "); SkPDFScalar::Append(bottom, content); content->writeText(" "); SkPDFScalar::Append(rect.width(), content); content->writeText(" "); SkPDFScalar::Append(rect.height(), content); content->writeText(" re\n"); } // static void SkPDFUtils::EmitPath(const SkPath& path, SkWStream* content) { SkPoint args[4]; SkPath::Iter iter(path, false); for (SkPath::Verb verb = iter.next(args); verb != SkPath::kDone_Verb; verb = iter.next(args)) { // args gets all the points, even the implicit first point. switch (verb) { case SkPath::kMove_Verb: MoveTo(args[0].fX, args[0].fY, content); break; case SkPath::kLine_Verb: AppendLine(args[1].fX, args[1].fY, content); break; case SkPath::kQuad_Verb: { SkPoint cubic[4]; SkConvertQuadToCubic(args, cubic); AppendCubic(cubic[1].fX, cubic[1].fY, cubic[2].fX, cubic[2].fY, cubic[3].fX, cubic[3].fY, content); break; } case SkPath::kCubic_Verb: AppendCubic(args[1].fX, args[1].fY, args[2].fX, args[2].fY, args[3].fX, args[3].fY, content); break; case SkPath::kClose_Verb: ClosePath(content); break; default: SkASSERT(false); break; } } } // static void SkPDFUtils::ClosePath(SkWStream* content) { content->writeText("h\n"); } // static void SkPDFUtils::PaintPath(SkPaint::Style style, SkPath::FillType fill, SkWStream* content) { if (style == SkPaint::kFill_Style) content->writeText("f"); else if (style == SkPaint::kStrokeAndFill_Style) content->writeText("B"); else if (style == SkPaint::kStroke_Style) content->writeText("S"); if (style != SkPaint::kStroke_Style) { NOT_IMPLEMENTED(fill == SkPath::kInverseEvenOdd_FillType, false); NOT_IMPLEMENTED(fill == SkPath::kInverseWinding_FillType, false); if (fill == SkPath::kEvenOdd_FillType) content->writeText("*"); } content->writeText("\n"); } // static void SkPDFUtils::StrokePath(SkWStream* content) { SkPDFUtils::PaintPath( SkPaint::kStroke_Style, SkPath::kWinding_FillType, content); } // static void SkPDFUtils::DrawFormXObject(int objectIndex, SkWStream* content) { content->writeText("/X"); content->writeDecAsText(objectIndex); content->writeText(" Do\n"); } // static void SkPDFUtils::ApplyGraphicState(int objectIndex, SkWStream* content) { content->writeText("/G"); content->writeDecAsText(objectIndex); content->writeText(" gs\n"); }
use SkConvertQuadToCubic()
use SkConvertQuadToCubic() git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@1973 2bbb7eff-a529-9590-31e7-b0007b416f81
C++
bsd-3-clause
Cue/skia,Cue/skia,mrobinson/skia,metajack/skia,metajack/skia,mrobinson/skia,mrobinson/skia,metajack/skia,Cue/skia,metajack/skia,mrobinson/skia,mrobinson/skia,Cue/skia
2fc46c8efbf0f969b3dc8c0c33c9a0bc0b04e13a
test/test_roscpp/src/sim_time_test.cpp
test/test_roscpp/src/sim_time_test.cpp
/* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* Author: Tony Pratkanis */ /* * Subscribe to a topic multiple times */ #include <string> #include <gtest/gtest.h> #include <time.h> #include <stdlib.h> #include "ros/ros.h" #include <roslib/Time.h> int g_argc; char** g_argv; class RosTimeTest : public testing::Test { public: void setTime(ros::Time t) { roslib::Time message; message.rostime = t; pub_.publish(message); } protected: RosTimeTest() { pub_ = nh_.advertise<roslib::Time>("/time", 1); while (pub_.getNumSubscribers() == 0) { ros::Duration(0.01).sleep(); } } ros::NodeHandle nh_; ros::Publisher pub_; }; TEST_F(RosTimeTest, SimTimeTest) { //Get the start time. ros::Time start = ros::Time::now(); //The start time should be zero before a message is published. ASSERT_TRUE(start.isZero()); //Publish a rostime of 42. setTime(ros::Time(42, 0)); //Wait half a second to get the message. ros::WallDuration(0.5).sleep(); //Make sure that it is really set ASSERT_EQ(42.0, ros::Time::now().toSec()); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "sim_time_test"); g_argc = argc; g_argv = argv; return RUN_ALL_TESTS(); }
/* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* Author: Tony Pratkanis */ /* * Subscribe to a topic multiple times */ #include <string> #include <gtest/gtest.h> #include <time.h> #include <stdlib.h> #include "ros/ros.h" #include <roslib/Time.h> #include <roslib/Clock.h> int g_argc; char** g_argv; class RosTimeTest : public testing::Test { public: void setTime(ros::Time t) { roslib::Time message; message.rostime = t; pub_.publish(message); } protected: RosTimeTest() { pub_ = nh_.advertise<roslib::Time>("/time", 1); while (pub_.getNumSubscribers() == 0) { ros::Duration(0.01).sleep(); } } ros::NodeHandle nh_; ros::Publisher pub_; }; TEST_F(RosTimeTest, SimTimeTest) { //Get the start time. ros::Time start = ros::Time::now(); //The start time should be zero before a message is published. ASSERT_TRUE(start.isZero()); //Publish a rostime of 42. setTime(ros::Time(42, 0)); //Wait half a second to get the message. ros::WallDuration(0.5).sleep(); //Make sure that it is really set ASSERT_EQ(42.0, ros::Time::now().toSec()); } class RosClockTest : public testing::Test { public: void setTime(ros::Time t) { roslib::Clock message; message.clock = t; pub_.publish(message); } protected: RosClockTest() { pub_ = nh_.advertise<roslib::Clock>("/clock", 1); while (pub_.getNumSubscribers() == 0) { ros::Duration(0.01).sleep(); } } ros::NodeHandle nh_; ros::Publisher pub_; }; TEST_F(RosClockTest, SimClockTest) { //Get the start time. ros::Time start = ros::Time::now(); //The start time should be zero before a message is published. ASSERT_TRUE(start.isZero()); //Publish a rostime of 42. setTime(ros::Time(42, 0)); //Wait half a second to get the message. ros::WallDuration(0.5).sleep(); //Make sure that it is really set ASSERT_EQ(42.0, ros::Time::now().toSec()); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "sim_time_test"); g_argc = argc; g_argv = argv; return RUN_ALL_TESTS(); }
Add ROS Clock test
Add ROS Clock test
C++
bsd-3-clause
ros/ros,ros/ros,ros/ros
e6db001fdad08718d1e49887f431376af4609c9b
test/test17.cxx
test/test17.cxx
#include <iostream> #include "test_helpers.hxx" using namespace std; using namespace pqxx; // Simple test program for libpqxx. Open connection to database, start // a dummy transaction to gain nontransactional access, and perform a query. namespace { void test_017(transaction_base &T) { connection_base &C(T.conn()); T.abort(); perform( [&C]() { nontransaction T{C}; const auto r = T.exec("SELECT * FROM generate_series(1, 4)"); PQXX_CHECK_EQUAL(r.size(), 4ul, "Weird query result."); T.commit(); }); } } // namespace PQXX_REGISTER_TEST_T(test_017, nontransaction)
#include <iostream> #include "test_helpers.hxx" using namespace std; using namespace pqxx; // Simple test program for libpqxx. Open connection to database, start // a dummy transaction to gain nontransactional access, and perform a query. namespace { void test_017(transaction_base &T) { connection_base &C(T.conn()); T.abort(); perform( [&C]() { nontransaction tx{C}; const auto r = tx.exec("SELECT * FROM generate_series(1, 4)"); PQXX_CHECK_EQUAL(r.size(), 4ul, "Weird query result."); tx.commit(); }); } } // namespace PQXX_REGISTER_TEST_T(test_017, nontransaction)
Fix compile warning.
Fix compile warning.
C++
bsd-3-clause
jtv/libpqxx,jtv/libpqxx,jtv/libpqxx,jtv/libpqxx
1484032156b72072a55d788cb67fb8c935b45fdc
src/kernel/commandhandler.cpp
src/kernel/commandhandler.cpp
/** * This file is part of the boostcache package. * * (c) Azat Khuzhin <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #include "commandhandler.h" #include "commands.h" #include "util/log.h" #include <boost/spirit/include/qi.hpp> #include <boost/algorithm/string/trim.hpp> #include <boost/format.hpp> #include <cstring> const char *CommandHandler::REPLY_FALSE = ":0\r\n"; const char *CommandHandler::REPLY_TRUE = ":1\r\n"; const char *CommandHandler::REPLY_NIL = "$-1\r\n"; const char *CommandHandler::REPLY_OK = "+OK\r\n"; const char *CommandHandler::REPLY_ERROR = "-ERR\r\n"; const char *CommandHandler::REPLY_ERROR_NOTSUPPORTED = "-ERR Not supported\r\n"; namespace qi = boost::spirit::qi; std::string CommandHandler::toReplyString(const std::string &string) { return str(boost::format("$%i\r\n%s\r\n") % string.size() % string); } std::string CommandHandler::toErrorReplyString(const std::string &string) { return str(boost::format("-ERR %s\r\n") % string); } std::string CommandHandler::toInlineReplyString(const std::string &string) { return str(boost::format("+%s\r\n") % string); } bool CommandHandler::feedAndParseCommand(const char *buffer, size_t size) { m_commandString.append(buffer, size); LOG(trace) << "Try to read/parser command(" << m_commandString.length() << ") " "with " << m_numberOfArguments << " arguments, " "for " << this; const char *begin = &m_commandString.c_str()[ m_commandOffset ]; const char *end = &m_commandString.c_str()[ m_commandString.size() ]; if (!begin) { LOG(trace) << "Parse: need more data, for " << this; return true; } // Try to read new command if (m_numberOfArguments < 0) { // We have inline request, because it is not start with '*' if (*begin != '*') { if (!parseInline(begin, end)) { reset(); return true; } } else if (!(begin = parseNumberOfArguments(begin, end))) { LOG(trace) << "Number of arguments: need more data, for " << this; return true; } } if ((m_type == MULTI_BULK) && !parseArguments(begin, end)) { LOG(trace) << "Arguments: need more data, for " << this; return true; } executeCommand(); return false; } bool CommandHandler::parseInline(const char *begin, const char *end) { m_type = INLINE; const char *lfPtr = (const char *)memchr((const void *)begin, '\n', end - begin); if (!lfPtr) { LOG(debug) << "LF not found, for " << this; return false; } m_commandOffset += (lfPtr - begin); // trim if (*(lfPtr-1) == '\r') { --lfPtr; } split(begin, lfPtr, m_commandArguments); if (!m_commandArguments.size() || !m_commandArguments[0].size() /* no command */) { return false; } LOG(trace) << "Have " << m_commandArguments.size() << " arguments, " << "for " << this << " (inline)"; return true; } const char* CommandHandler::parseNumberOfArguments(const char *begin, const char *end) { m_type = MULTI_BULK; const char *lfPtr = (const char *)memchr((const void *)begin, '\n', end - begin); if (!lfPtr) { LOG(debug) << "LF not found, for " << this; return nullptr; } if (!qi::parse((const char* const)begin, lfPtr, '*' >> qi::int_ >> "\r", m_numberOfArguments)) { LOG(debug) << "Don't have number of arguments, for " << this; reset(); return nullptr; } ++lfPtr; // Seek LF m_commandArguments.reserve(m_numberOfArguments); m_numberOfArgumentsLeft = m_numberOfArguments; m_commandOffset += (lfPtr - begin); LOG(trace) << "Have " << m_numberOfArguments << " arguments, " << "for " << this << " (bulk)"; return lfPtr; } bool CommandHandler::parseArguments(const char *begin, const char *end) { const char *argumentsBegin = begin; const char *lfPtr; while (m_numberOfArgumentsLeft && (lfPtr = (const char *)memchr((const void *)argumentsBegin, '\n', end - argumentsBegin))) { if (!qi::parse(argumentsBegin, lfPtr, '$' >> qi::int_ >> "\r", m_lastArgumentLength)) { LOG(debug) << "Can't find valid argument length, for " << this; reset(); break; } LOG(trace) << "Reading " << m_lastArgumentLength << " bytes, for " << this; ++lfPtr; // Seek LF if ((m_lastArgumentLength + 2 /* CRLF */) > (end - lfPtr)) { break; } if (memcmp(lfPtr + m_lastArgumentLength, "\r\n", 2) != 0) { LOG(debug) << "Malfomed end of argument, for " << this; reset(); break; } // Save command argument m_commandArguments.push_back(std::string(lfPtr, m_lastArgumentLength)); LOG(trace) << "Saving " << m_commandArguments.back() << " argument, for " << this; // Update some counters/offsets argumentsBegin = (lfPtr + m_lastArgumentLength + 2); --m_numberOfArgumentsLeft; m_commandOffset += (argumentsBegin - begin); m_lastArgumentLength = -1; } return !m_numberOfArgumentsLeft; } void CommandHandler::executeCommand() { LOG(trace) << "Execute new command, for " << this; /** * TODO: We need here something like vector::pop() method, * but it is slow for vectors. * So need to think on it. * As a temporary decision for one hashtable db I will just not use 0 index. */ Commands &commands = TheCommands::instance(); m_finishCallback((commands.find(m_commandArguments[0], m_commandArguments.size() - 1)) ( m_commandArguments )); reset(); } std::string CommandHandler::toString() const { std::string arguments; int i; for_each(m_commandArguments.begin(), m_commandArguments.end(), [&arguments, &i] (std::string argument) { arguments += "'"; arguments += argument; arguments += "'" "\n"; } ); return arguments; } void CommandHandler::reset() { m_type = NOT_SET; m_commandString.clear(); m_commandOffset = 0; m_numberOfArguments = -1; m_numberOfArgumentsLeft = -1; m_lastArgumentLength = -1; m_commandArguments.clear(); } void CommandHandler::split(const char *begin, const char *end, std::vector<std::string>& destination, char delimiter) { const char *found; while (true) { found = (const char *)memchr((const void *)begin, delimiter, end - begin) ?: end; destination.push_back(std::string(begin, found - begin)); if (found == end) { break; } begin = (found + 1 /* skip delimiter */); } }
/** * This file is part of the boostcache package. * * (c) Azat Khuzhin <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #include "commandhandler.h" #include "commands.h" #include "util/log.h" #include <boost/spirit/include/qi.hpp> #include <boost/algorithm/string/trim.hpp> #include <boost/format.hpp> #include <cstring> const char *CommandHandler::REPLY_FALSE = ":0\r\n"; const char *CommandHandler::REPLY_TRUE = ":1\r\n"; const char *CommandHandler::REPLY_NIL = "$-1\r\n"; const char *CommandHandler::REPLY_OK = "+OK\r\n"; const char *CommandHandler::REPLY_ERROR = "-ERR\r\n"; const char *CommandHandler::REPLY_ERROR_NOTSUPPORTED = "-ERR Not supported\r\n"; namespace qi = boost::spirit::qi; std::string CommandHandler::toReplyString(const std::string &string) { return str(boost::format("$%i\r\n%s\r\n") % string.size() % string); } std::string CommandHandler::toErrorReplyString(const std::string &string) { return str(boost::format("-ERR %s\r\n") % string); } std::string CommandHandler::toInlineReplyString(const std::string &string) { return str(boost::format("+%s\r\n") % string); } bool CommandHandler::feedAndParseCommand(const char *buffer, size_t size) { m_commandString.append(buffer, size); LOG(trace) << "Try to read/parser command(" << m_commandString.length() << ") " "with " << m_numberOfArguments << " arguments, " "for " << this; const char *begin = &m_commandString.c_str()[ m_commandOffset ]; const char *end = &m_commandString.c_str()[ m_commandString.size() ]; if (!begin) { LOG(trace) << "Parse: need more data, for " << this; return true; } // Try to read new command if (m_numberOfArguments < 0) { // We have inline request, because it is not start with '*' if (*begin != '*') { if (!parseInline(begin, end)) { reset(); return true; } } else if (!(begin = parseNumberOfArguments(begin, end))) { LOG(trace) << "Number of arguments: need more data, for " << this; return true; } } if ((m_type == MULTI_BULK) && !parseArguments(begin, end)) { LOG(trace) << "Arguments: need more data, for " << this; return true; } executeCommand(); return false; } bool CommandHandler::parseInline(const char *begin, const char *end) { m_type = INLINE; const char *lfPtr = (const char *)memchr((const void *)begin, '\n', end - begin); if (!lfPtr) { LOG(debug) << "LF not found, for " << this; return false; } m_commandOffset += (lfPtr - begin); // trim if (*(lfPtr-1) == '\r') { --lfPtr; } split(begin, lfPtr, m_commandArguments); if (!m_commandArguments.size() || !m_commandArguments[0].size() /* no command */) { return false; } LOG(trace) << "Have " << m_commandArguments.size() << " arguments, " << "for " << this << " (inline)"; return true; } const char* CommandHandler::parseNumberOfArguments(const char *begin, const char *end) { m_type = MULTI_BULK; const char *lfPtr = (const char *)memchr((const void *)begin, '\n', end - begin); if (!lfPtr) { LOG(debug) << "LF not found, for " << this; return nullptr; } if (!qi::parse((const char* const)begin, lfPtr, '*' >> qi::int_ >> "\r", m_numberOfArguments)) { LOG(debug) << "Don't have number of arguments, for " << this; reset(); return nullptr; } ++lfPtr; // Seek LF m_commandArguments.reserve(m_numberOfArguments); m_numberOfArgumentsLeft = m_numberOfArguments; m_commandOffset += (lfPtr - begin); LOG(trace) << "Have " << m_numberOfArguments << " arguments, " << "for " << this << " (bulk)"; return lfPtr; } bool CommandHandler::parseArguments(const char *begin, const char *end) { const char *argumentsBegin = begin; const char *lfPtr; while (m_numberOfArgumentsLeft && (lfPtr = (const char *)memchr((const void *)argumentsBegin, '\n', end - argumentsBegin))) { if (!qi::parse(argumentsBegin, lfPtr, '$' >> qi::int_ >> "\r", m_lastArgumentLength)) { LOG(debug) << "Can't find valid argument length, for " << this; reset(); break; } LOG(trace) << "Reading " << m_lastArgumentLength << " bytes, for " << this; ++lfPtr; // Seek LF if ((m_lastArgumentLength + 2 /* CRLF */) > (end - lfPtr)) { break; } if (memcmp(lfPtr + m_lastArgumentLength, "\r\n", 2) != 0) { LOG(debug) << "Malfomed end of argument, for " << this; reset(); break; } // Save command argument m_commandArguments.push_back(std::string(lfPtr, m_lastArgumentLength)); LOG(trace) << "Saving " << m_commandArguments.back() << " argument, for " << this; // Update some counters/offsets argumentsBegin = (lfPtr + m_lastArgumentLength + 2); --m_numberOfArgumentsLeft; m_commandOffset += (argumentsBegin - begin); m_lastArgumentLength = -1; } return !m_numberOfArgumentsLeft; } void CommandHandler::executeCommand() { LOG(trace) << "Execute new command, for " << this; /** * TODO: We need here something like vector::pop() method, * but it is slow for vectors. * So need to think on it. * As a temporary decision for one hashtable db I will just not use 0 index. */ Commands &commands = TheCommands::instance(); m_finishCallback((commands.find(m_commandArguments[0], m_commandArguments.size() - 1)) ( m_commandArguments )); reset(); } std::string CommandHandler::toString() const { std::string arguments; int i; for_each(m_commandArguments.begin(), m_commandArguments.end(), [&arguments, &i] (std::string argument) { arguments += "'"; arguments += argument; arguments += "'" "\n"; } ); return arguments; } void CommandHandler::reset() { m_type = NOT_SET; m_commandString.clear(); m_commandOffset = 0; m_numberOfArguments = -1; m_numberOfArgumentsLeft = -1; m_lastArgumentLength = -1; m_commandArguments.clear(); } void CommandHandler::split(const char *begin, const char *end, std::vector<std::string>& destination, char delimiter) { const char *found; while (true) { if (found == end) { break; } found = (const char *)memchr((const void *)begin, delimiter, end - begin) ?: end; destination.push_back(std::string(begin, found - begin)); // trim do { ++found; } while (*found == delimiter); begin = found; } }
trim arguments for inline requests.
[kernel] split(): trim arguments for inline requests.
C++
mit
azat/boostcache,azat/boostcache,azat/boostcache,azat/boostcache
4b27677910166578fe1c3a291073ec51ca9b7976
src/qbencodeparser.cpp
src/qbencodeparser.cpp
#ifndef QT_BOOTSTRAPPED #include <QCoreApplication> #endif #include <QDebug> #include "qbencodeparser_p.h" //#define PARSER_DEBUG #ifdef PARSER_DEBUG static int indent = 0; #define BEGIN qDebug() << QByteArray(4*indent++, ' ').constData() << "pos = " << (bencode - head) << " begin: " #define END qDebug() << QByteArray(4*(--indent), ' ').constData() << "end" #define DEBUG qDebug() << QByteArray(4*indent, ' ').constData() #else #define BEGIN if (1) ; else qDebug() #define END do {} while (0) #define DEBUG if (1) ; else qDebug() #endif #define Return(a) do { state = a; goto Return; } while(0) static const int nestingLimit = 1024; // error strings for the Bencode parser #define BENCODEERR_OK QT_TRANSLATE_NOOP("QBencodeParserError", "no error occurred") #define BENCODEERR_UNTERM_INT QT_TRANSLATE_NOOP("QBencodeParserError", "unterminated integer") #define BENCODEERR_UNTERM_LIST QT_TRANSLATE_NOOP("QBencodeParserError", "unterminated list") #define BENCODEERR_UNTERM_DICT QT_TRANSLATE_NOOP("QBencodeParserError", "unterminated dictionary") #define BENCODEERR_MISS_STRSEP QT_TRANSLATE_NOOP("QBencodeParserError", "string separator is missing after digits") #define BENCODEERR_MISS_KEY QT_TRANSLATE_NOOP("QBencodeParserError", "missing string key inside a dict entry") #define BENCODEERR_MISS_ENTRY QT_TRANSLATE_NOOP("QBencodeParserError", "entry is missing after a key inside a dict") #define BENCODEERR_ILLEGAL_NUM QT_TRANSLATE_NOOP("QBencodeParserError", "illegal number") #define BENCODEERR_ILLEGAL_VAL QT_TRANSLATE_NOOP("QBencodeParserError", "illegal value") #define BENCODEERR_DEEP_NEST QT_TRANSLATE_NOOP("QBencodeParserError", "too deeply nested document") #define BENCODEERR_DOC_LARGE QT_TRANSLATE_NOOP("QBencodeParserError", "too large document") #define BENCODEERR_DOC_INCOM QT_TRANSLATE_NOOP("QBencodeParserError", "document incomplete") #define BENCODEERR_LEAD_ZERO QT_TRANSLATE_NOOP("QBencodeParserError", "leading zero in integer entry") /*! \class QBencodeParseError \brief The QBencodeParseError class is used to report errors during Bencode parsing. */ /*! \enum QBencodeParseError::ParseError This enum describes the type of error that occurred during the parsing of a Bencode document. \value NoError No error occurred \value UnterminatedInteger An integer entry is not correctly terminated with a closing mark 'e' \value UnterminatedList A list entry is not correctly terminated with a closing mark 'e' \value UnterminatedDict A dictionary entry is not correctly terminated with a closing mark 'e' \value MissingStringSeparator A colon separating length from data inside strings is missing \value MissingKey A string typed key was expected but couldn't be found inside a dictionary \value MissingEntry An entry was expect after a key but the dictionary ended. \value IllegalNumber The number is not well formed \value IllegalValue The value is illegal \value DeepNesting The Bencode document is too deeply nested for the parser to parse it \value DocumentTooLarge The Bencode document is too large for the parser to parse it \value DocumentIncomplete The Bencode document is possibily incomplete. (e.g. a string entry with a length pass the end of the document) \value LeadingZero The integer entry has leading zero which is not allowed in Bencode format. This is only raised in strict mode. */ /*! \variable QBencodeParseError::error Contains the type of the parse error. Is equal to QBencodeParseError::NoError if the document was parsed correctly. \sa ParseError, errorString() */ /*! \variable QBencodeParseError::offset Contains the offset in the input data where the parse error occurred. \sa error, errorString() */ /*! Returns the human-readable message appropriate to the reported Bencode parsing error. \sa error */ QString QBencodeParseError::errorString() const { const char *sz = ""; switch (error) { case NoError: sz = BENCODEERR_OK; break; case UnterminatedInteger: sz = BENCODEERR_UNTERM_INT; break; case UnterminatedList: sz = BENCODEERR_UNTERM_LIST; break; case UnterminatedDict: sz = BENCODEERR_UNTERM_DICT; break; case MissingStringSeparator: sz = BENCODEERR_MISS_STRSEP; break; case MissingKey: sz = BENCODEERR_MISS_KEY; break; case MissingEntry: sz = BENCODEERR_MISS_ENTRY; break; case IllegalNumber: sz = BENCODEERR_ILLEGAL_NUM; break; case IllegalValue: sz = BENCODEERR_ILLEGAL_VAL; break; case DeepNesting: sz = BENCODEERR_DEEP_NEST; break; case DocumentTooLarge: sz = BENCODEERR_DOC_LARGE; break; case DocumentIncomplete: sz = BENCODEERR_DOC_INCOM; break; case LeadingZero: sz = BENCODEERR_LEAD_ZERO; break; } #ifndef QT_BOOTSTRAPPED return QCoreApplication::translate("QBencodeParseError", sz); #else return QLatin1String(sz); #endif } using namespace QBencodePrivate; Parser::Parser(const char *ben, int length) : strictMode(false), head(ben), bencode(ben), nestingLevel(0), lastError(QBencodeParseError::NoError) { end = bencode + length; } enum { BeginInteger = 'i', BeginDict = 'd', BeginList = 'l', Digit0 = '0', Digit1 = '1', Digit2 = '2', Digit3 = '3', Digit4 = '4', Digit5 = '5', Digit6 = '6', Digit7 = '7', Digit8 = '8', Digit9 = '9', EndMark = 'e', StringSeparator = ':', }; char Parser::nextToken() { if (reachEnd()) { return 0; } char token = *bencode++; return token; } char Parser::peek() const { if (reachEnd()) { return 0; } return *bencode; } bool Parser::eat(char token) { if (end - bencode >= 1 && bencode[0] == token) { bencode++; return true; } return false; } bool Parser::reachEnd() const { return (bencode >= end); } QBencodeDocument Parser::parse(QBencodeParseError *error, bool strictMode) { #ifdef PARSER_DEBUG indent = 0; qDebug() << ">>>>> parser begin"; #endif this->strictMode = strictMode; if (parseValue()) { if (error) { error->offset = 0; error->error = QBencodeParseError::NoError; } return QBencodeDocument(std::move(currentValue)); } else { #ifdef PARSER_DEBUG qDebug() << ">>>>> parser error"; #endif if (error) { error->offset = bencode - head; error->error = lastError; } return QBencodeDocument(); } } bool Parser::parseValue() { char token = nextToken(); bool ret = false; DEBUG << token << '(' << hex << (uint)token << ')'; switch (token) { case BeginInteger: ret = parseInteger(); break; case BeginList: ret = parseList(); break; case BeginDict: ret = parseDict(); break; case Digit0: case Digit1: case Digit2: case Digit3: case Digit4: case Digit5: case Digit6: case Digit7: case Digit8: case Digit9: ret = parseString(); break; default: lastError = QBencodeParseError::IllegalValue; } return ret; } /* * list = begin-list [ value *( value ) ] end-mark */ bool Parser::parseList() { BEGIN << "parseList"; bool state = true; if (++nestingLevel > nestingLimit) { lastError = QBencodeParseError::DeepNesting; Return(false); } if (reachEnd()) { lastError = QBencodeParseError::UnterminatedList; Return(false); } { QBencodeList values; if (peek() == EndMark) { // empty list nextToken(); } else { while (true) { if (!parseValue()) { Return(false); } values.append(std::move(currentValue)); if (peek() == EndMark) { break; } else if (reachEnd()) { lastError = QBencodeParseError::UnterminatedList; Return(false); } } } currentValue = QBencodeValue(values); DEBUG << "size =" << values.size(); } DEBUG << "pos =" << (bencode - head); Return: END; --nestingLevel; return state; } /* * integer = begin-integer number end-mark */ bool Parser::parseInteger() { BEGIN << "parseInteger" << bencode; qint64 n; if (!parseNumber(&n)) { return false; } // eat EndMark if (!eat(EndMark)) { lastError = QBencodeParseError::UnterminatedInteger; return false; } currentValue = QBencodeValue(n); END; return true; } bool Parser::parseNumber(qint64 *n) { const char *start = bencode; // minus eat('-'); // leading zero check if (strictMode) { int zeroCnt = 0; while (eat('0')) { ++zeroCnt; } if (zeroCnt > 1) { lastError = QBencodeParseError::LeadingZero; return false; } } while (!reachEnd() && *bencode >= '0' && *bencode <= '9') { ++bencode; } QByteArray number(start, bencode - start); DEBUG << "number" << number; bool ok; *n = number.toLongLong(&ok); if (!ok) { lastError = QBencodeParseError::IllegalNumber; return false; } return true; } /* * string = number string-saperator string-data */ bool Parser::parseString() { BEGIN << "parseString" << bencode; // put back begin token, this should be safe as this method is only // called after at least one call to nextToken() --bencode; qint64 len; if (!parseNumber(&len)) { return false; } if (!eat(StringSeparator)) { lastError = QBencodeParseError::MissingStringSeparator; return false; } if (bencode + len > end) { lastError = QBencodeParseError::DocumentIncomplete; return false; } QByteArray string(bencode, len); DEBUG << "string" << string; bencode += len; currentValue = QBencodeValue(string); END; return true; } bool Parser::parseDict() { BEGIN << "parseDict"; bool state = true; if (++nestingLevel > nestingLimit) { lastError = QBencodeParseError::DeepNesting; Return(false); } if (reachEnd()) { lastError = QBencodeParseError::UnterminatedDict; Return(false); } { QBencodeDict entries; bool shouldBeValue = false; QBencodeValue key; if (peek() == EndMark) { // empty dict nextToken(); } else { while (true) { if (!parseValue()) { Return(false); } // FUTURE: check entry sequence in stric mode if (!shouldBeValue) { if (currentValue.type() != QBencodeValue::String) { lastError = QBencodeParseError::MissingKey; Return(false); } key = currentValue; shouldBeValue = true; } else { entries.insert(key.toString(), currentValue); shouldBeValue = false; } if (peek() == EndMark) { if (shouldBeValue) { lastError = QBencodeParseError::MissingEntry; Return(false); } break; } else if (reachEnd()) { lastError = QBencodeParseError::UnterminatedDict; Return(false); } } } currentValue = QBencodeValue(entries); DEBUG << "size =" << entries.size(); } DEBUG << "pos =" << (bencode - head); Return: --nestingLevel; END; return state; }
#ifndef QT_BOOTSTRAPPED #include <QCoreApplication> #endif #include <QDebug> #include "qbencodeparser_p.h" //#define PARSER_DEBUG #ifdef PARSER_DEBUG static int indent = 0; #define BEGIN qDebug() << QByteArray(4*indent++, ' ').constData() << "pos = " << (bencode - head) << " begin: " #define END qDebug() << QByteArray(4*(--indent), ' ').constData() << "end" #define DEBUG qDebug() << QByteArray(4*indent, ' ').constData() #else #define BEGIN if (1) ; else qDebug() #define END do {} while (0) #define DEBUG if (1) ; else qDebug() #endif #define Return(a) do { state = a; goto Return; } while(0) static const int nestingLimit = 1024; // error strings for the Bencode parser #define BENCODEERR_OK QT_TRANSLATE_NOOP("QBencodeParserError", "no error occurred") #define BENCODEERR_UNTERM_INT QT_TRANSLATE_NOOP("QBencodeParserError", "unterminated integer") #define BENCODEERR_UNTERM_LIST QT_TRANSLATE_NOOP("QBencodeParserError", "unterminated list") #define BENCODEERR_UNTERM_DICT QT_TRANSLATE_NOOP("QBencodeParserError", "unterminated dictionary") #define BENCODEERR_MISS_STRSEP QT_TRANSLATE_NOOP("QBencodeParserError", "string separator is missing after digits") #define BENCODEERR_MISS_KEY QT_TRANSLATE_NOOP("QBencodeParserError", "missing string key inside a dict entry") #define BENCODEERR_MISS_ENTRY QT_TRANSLATE_NOOP("QBencodeParserError", "entry is missing after a key inside a dict") #define BENCODEERR_ILLEGAL_NUM QT_TRANSLATE_NOOP("QBencodeParserError", "illegal number") #define BENCODEERR_ILLEGAL_VAL QT_TRANSLATE_NOOP("QBencodeParserError", "illegal value") #define BENCODEERR_DEEP_NEST QT_TRANSLATE_NOOP("QBencodeParserError", "too deeply nested document") #define BENCODEERR_DOC_LARGE QT_TRANSLATE_NOOP("QBencodeParserError", "too large document") #define BENCODEERR_DOC_INCOM QT_TRANSLATE_NOOP("QBencodeParserError", "document incomplete") #define BENCODEERR_LEAD_ZERO QT_TRANSLATE_NOOP("QBencodeParserError", "leading zero in integer entry") /*! \class QBencodeParseError \brief The QBencodeParseError class is used to report errors during Bencode parsing. */ /*! \enum QBencodeParseError::ParseError This enum describes the type of error that occurred during the parsing of a Bencode document. \value NoError No error occurred \value UnterminatedInteger An integer entry is not correctly terminated with a closing mark 'e' \value UnterminatedList A list entry is not correctly terminated with a closing mark 'e' \value UnterminatedDict A dictionary entry is not correctly terminated with a closing mark 'e' \value MissingStringSeparator A colon separating length from data inside strings is missing \value MissingKey A string typed key was expected but couldn't be found inside a dictionary \value MissingEntry An entry was expect after a key but the dictionary ended. \value IllegalNumber The number is not well formed \value IllegalValue The value is illegal \value DeepNesting The Bencode document is too deeply nested for the parser to parse it \value DocumentTooLarge The Bencode document is too large for the parser to parse it \value DocumentIncomplete The Bencode document is possibily incomplete. (e.g. a string entry with a length pass the end of the document) \value LeadingZero The integer entry has leading zero which is not allowed in Bencode format. This is only raised in strict mode. */ /*! \variable QBencodeParseError::error Contains the type of the parse error. Is equal to QBencodeParseError::NoError if the document was parsed correctly. \sa ParseError, errorString() */ /*! \variable QBencodeParseError::offset Contains the offset in the input data where the parse error occurred. \sa error, errorString() */ /*! Returns the human-readable message appropriate to the reported Bencode parsing error. \sa error */ QString QBencodeParseError::errorString() const { const char *sz = ""; switch (error) { case NoError: sz = BENCODEERR_OK; break; case UnterminatedInteger: sz = BENCODEERR_UNTERM_INT; break; case UnterminatedList: sz = BENCODEERR_UNTERM_LIST; break; case UnterminatedDict: sz = BENCODEERR_UNTERM_DICT; break; case MissingStringSeparator: sz = BENCODEERR_MISS_STRSEP; break; case MissingKey: sz = BENCODEERR_MISS_KEY; break; case MissingEntry: sz = BENCODEERR_MISS_ENTRY; break; case IllegalNumber: sz = BENCODEERR_ILLEGAL_NUM; break; case IllegalValue: sz = BENCODEERR_ILLEGAL_VAL; break; case DeepNesting: sz = BENCODEERR_DEEP_NEST; break; case DocumentTooLarge: sz = BENCODEERR_DOC_LARGE; break; case DocumentIncomplete: sz = BENCODEERR_DOC_INCOM; break; case LeadingZero: sz = BENCODEERR_LEAD_ZERO; break; } #ifndef QT_BOOTSTRAPPED return QCoreApplication::translate("QBencodeParseError", sz); #else return QLatin1String(sz); #endif } using namespace QBencodePrivate; Parser::Parser(const char *ben, int length) : strictMode(false), head(ben), bencode(ben), nestingLevel(0), lastError(QBencodeParseError::NoError) { end = bencode + length; } enum { BeginInteger = 'i', BeginDict = 'd', BeginList = 'l', Digit0 = '0', Digit1 = '1', Digit2 = '2', Digit3 = '3', Digit4 = '4', Digit5 = '5', Digit6 = '6', Digit7 = '7', Digit8 = '8', Digit9 = '9', EndMark = 'e', StringSeparator = ':', }; char Parser::nextToken() { if (reachEnd()) { return 0; } char token = *bencode++; return token; } char Parser::peek() const { if (reachEnd()) { return 0; } return *bencode; } bool Parser::eat(char token) { if (end - bencode >= 1 && bencode[0] == token) { bencode++; return true; } return false; } bool Parser::reachEnd() const { return (bencode >= end); } QBencodeDocument Parser::parse(QBencodeParseError *error, bool strictMode) { #ifdef PARSER_DEBUG indent = 0; qDebug() << ">>>>> parser begin"; #endif this->strictMode = strictMode; if (parseValue()) { if (error) { error->offset = 0; error->error = QBencodeParseError::NoError; } return QBencodeDocument(std::move(currentValue)); } else { #ifdef PARSER_DEBUG qDebug() << ">>>>> parser error"; #endif if (error) { error->offset = bencode - head; error->error = lastError; } return QBencodeDocument(); } } bool Parser::parseValue() { char token = nextToken(); bool ret = false; DEBUG << token << '(' << hex << (uint)token << ')'; switch (token) { case BeginInteger: ret = parseInteger(); break; case BeginList: ret = parseList(); break; case BeginDict: ret = parseDict(); break; case Digit0: case Digit1: case Digit2: case Digit3: case Digit4: case Digit5: case Digit6: case Digit7: case Digit8: case Digit9: ret = parseString(); break; default: lastError = QBencodeParseError::IllegalValue; } return ret; } /* * list = begin-list [ value *( value ) ] end-mark */ bool Parser::parseList() { BEGIN << "parseList"; bool state = true; if (++nestingLevel > nestingLimit) { lastError = QBencodeParseError::DeepNesting; Return(false); } if (reachEnd()) { lastError = QBencodeParseError::UnterminatedList; Return(false); } { QBencodeList values; if (peek() == EndMark) { // empty list nextToken(); } else { while (true) { if (!parseValue()) { Return(false); } values.append(std::move(currentValue)); if (peek() == EndMark) { eat(EndMark); break; } else if (reachEnd()) { lastError = QBencodeParseError::UnterminatedList; Return(false); } } } currentValue = QBencodeValue(values); DEBUG << "size =" << values.size(); } DEBUG << "pos =" << (bencode - head); Return: END; --nestingLevel; return state; } /* * integer = begin-integer number end-mark */ bool Parser::parseInteger() { BEGIN << "parseInteger" << bencode; qint64 n; if (!parseNumber(&n)) { return false; } // eat EndMark if (!eat(EndMark)) { lastError = QBencodeParseError::UnterminatedInteger; return false; } currentValue = QBencodeValue(n); END; return true; } bool Parser::parseNumber(qint64 *n) { const char *start = bencode; // minus eat('-'); // leading zero check if (strictMode) { int zeroCnt = 0; while (eat('0')) { ++zeroCnt; } if (zeroCnt > 1) { lastError = QBencodeParseError::LeadingZero; return false; } } while (!reachEnd() && *bencode >= '0' && *bencode <= '9') { ++bencode; } QByteArray number(start, bencode - start); DEBUG << "number" << number; bool ok; *n = number.toLongLong(&ok); if (!ok) { lastError = QBencodeParseError::IllegalNumber; return false; } return true; } /* * string = number string-saperator string-data */ bool Parser::parseString() { BEGIN << "parseString" << bencode; // put back begin token, this should be safe as this method is only // called after at least one call to nextToken() --bencode; qint64 len; if (!parseNumber(&len)) { return false; } if (!eat(StringSeparator)) { lastError = QBencodeParseError::MissingStringSeparator; return false; } if (bencode + len > end) { lastError = QBencodeParseError::DocumentIncomplete; return false; } QByteArray string(bencode, len); DEBUG << "string" << string; bencode += len; currentValue = QBencodeValue(string); END; return true; } bool Parser::parseDict() { BEGIN << "parseDict"; bool state = true; if (++nestingLevel > nestingLimit) { lastError = QBencodeParseError::DeepNesting; Return(false); } if (reachEnd()) { lastError = QBencodeParseError::UnterminatedDict; Return(false); } { QBencodeDict entries; bool shouldBeValue = false; QBencodeValue key; if (peek() == EndMark) { // empty dict nextToken(); } else { while (true) { if (!parseValue()) { Return(false); } // FUTURE: check entry sequence in stric mode if (!shouldBeValue) { if (currentValue.type() != QBencodeValue::String) { lastError = QBencodeParseError::MissingKey; Return(false); } key = currentValue; shouldBeValue = true; } else { entries.insert(key.toString(), currentValue); shouldBeValue = false; } if (peek() == EndMark) { if (shouldBeValue) { lastError = QBencodeParseError::MissingEntry; Return(false); } eat(EndMark); break; } else if (reachEnd()) { lastError = QBencodeParseError::UnterminatedDict; Return(false); } } } currentValue = QBencodeValue(entries); DEBUG << "size =" << entries.size(); } DEBUG << "pos =" << (bencode - head); Return: --nestingLevel; END; return state; }
fix logic error in parsing list and dict
QBencodePrivate::Parser: fix logic error in parsing list and dict
C++
mit
Aetf/QBencode,Aetf/QBencode,Aetf/QBencode
1a8d888d7671151c6f0e30f174bfa4fcf499f4cf
kpilot/conduits/memofileconduit/memofile-conduit.cc
kpilot/conduits/memofileconduit/memofile-conduit.cc
/* memofile-conduit.cc KPilot ** ** Copyright (C) 2004-2004 by Jason 'vanRijn' Kasper ** ** This file does the actual conduit work. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as published by ** the Free Software Foundation; either version 2.1 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, ** MA 02111-1307, USA. */ /* ** Bug reports and questions can be sent to [email protected] */ #include "options.h" // Something to allow us to check what revision // the modules are that make up a binary distribution. // // static const char *memofile_conduit_id= "$Id$"; // Only include what we really need: // First UNIX system stuff, then std C++, // then Qt, then KDE, then local includes. // // #include <time.h> // required by pilot-link includes #include <pi-memo.h> #include "pilotMemo.h" #include <qfile.h> #include <qdir.h> #include <qtextcodec.h> #include <kconfig.h> #include <kdebug.h> #include "pilotAppCategory.h" #include "pilotSerialDatabase.h" #include "memofile-factory.h" #include "memofile-conduit.h" #include "memofileSettings.h" /** * Our workhorse. This is the main driver for the conduit. */ MemofileConduit::MemofileConduit(KPilotDeviceLink *d, const char *n, const QStringList &l) : ConduitAction(d,n,l), _DEFAULT_MEMODIR("~/MyMemos/") { FUNCTIONSETUP; #ifdef DEBUG DEBUGCONDUIT<<memofile_conduit_id<<endl; #endif fConduitName=i18n("Memofile"); fMemoList.setAutoDelete(true); } MemofileConduit::~MemofileConduit() { FUNCTIONSETUP; // we're not guaranteed to have this // if (_memofiles) delete _memofiles; } /* virtual */ bool MemofileConduit::exec() { FUNCTIONSETUP; fFirstSync = false; if(!openDatabases(QString::fromLatin1("MemoDB"))) { emit logError(i18n("Unable to open the memo databases on the handheld.")); return false; } readConfig(); if (! initializeFromPilot()) { emit logError(i18n("Cannot initialize from pilot.")); return false; } _memofiles = new Memofiles(fCategories, fMemoAppInfo, _memo_directory); fFirstSync = _memofiles->isFirstSync(); addSyncLogEntry(" Syncing with " + _memo_directory + "."); if (SyncAction::eCopyHHToPC == getSyncDirection() || fFirstSync) { addSyncLogEntry(" Copying Pilot to PC..."); #ifdef DEBUG DEBUGCONDUIT << fname << ": copying Pilot to PC." << endl; #endif copyHHToPC(); } else if (SyncAction::eCopyPCToHH == getSyncDirection()) { #ifdef DEBUG DEBUGCONDUIT << fname << ": copying PC to Pilot." << endl; #endif addSyncLogEntry(" Copying PC to Pilot..."); copyPCToHH(); } else { #ifdef DEBUG DEBUGCONDUIT << fname << ": doing regular sync." << endl; #endif addSyncLogEntry(" Doing regular sync..."); sync(); } cleanup(); #ifdef DEBUG DEBUGCONDUIT << fname << ": stats: " << getResults() << endl; #endif addSyncLogEntry(" " + getResults()); return delayDone(); } bool MemofileConduit::readConfig() { FUNCTIONSETUP; QString dir(MemofileConduitSettings::directory()); if (dir.isEmpty()) { dir = _DEFAULT_MEMODIR; #ifdef DEBUG DEBUGCONDUIT << fname << ": no directory given to us. defaulting to: [" << _DEFAULT_MEMODIR << "]" << endl; #endif } _memo_directory = dir; _sync_private = MemofileConduitSettings::syncPrivate(); #ifdef DEBUG DEBUGCONDUIT << fname << ": Settings... " << " directory: [" << _memo_directory << "], first sync: [" << isFirstSync() << "], sync private: [" << _sync_private << "]" << endl; #endif return true; } void MemofileConduit::getAppInfo() { FUNCTIONSETUP; unsigned char buffer[PilotDatabase::MAX_APPINFO_SIZE]; int appInfoSize = fDatabase->readAppBlock(buffer,PilotDatabase::MAX_APPINFO_SIZE); if (appInfoSize<0) { fActionStatus=Error; return; } unpack_MemoAppInfo(&fMemoAppInfo,buffer,appInfoSize); PilotDatabase::listAppInfo(&fMemoAppInfo.category); } /** * Methods related to getting set up from the Pilot. */ bool MemofileConduit::initializeFromPilot() { _countDeletedToPilot = 0; _countModifiedToPilot = 0; _countNewToPilot = 0; getAppInfo(); if (!loadPilotCategories()) return false; return true; } bool MemofileConduit::loadPilotCategories() { FUNCTIONSETUP; fCategories.clear(); QString _category_name; int _category_id=0; int _category_num=0; for (int i = 0; i < 15; i++) { if (fMemoAppInfo.category.name[i][0]) { _category_name = PilotAppCategory::codec()->toUnicode(fMemoAppInfo.category.name[i]); _category_id = (int)fMemoAppInfo.category.ID[i]; _category_num = i; fCategories[_category_num] = _category_name; #ifdef DEBUG DEBUGCONDUIT << fname << ": Category #" << _category_num << " has ID " << _category_id << " and name " <<_category_name << endl; #endif } } return true; } /** * Read all memos in from Pilot. */ void MemofileConduit::getAllFromPilot() { FUNCTIONSETUP; #ifdef DEBUG DEBUGCONDUIT << fname << ": Database has " << fDatabase->recordCount() << " records." << endl; #endif fMemoList.clear(); int currentRecord = 0; PilotRecord *pilotRec; PilotMemo *memo = 0; while ((pilotRec = fDatabase->readRecordByIndex(currentRecord)) != NULL) { if ((!pilotRec->isSecret()) || _sync_private) { memo = new PilotMemo(pilotRec); fMemoList.append(memo); #ifdef DEBUG DEBUGCONDUIT << fname << ": Added memo: [" << currentRecord << "], id: [" << memo->getID() << "], category: [" << fCategories[memo->getCat()] << "], title: [" << memo->getTitle() << "]" << endl; #endif } else { #ifdef DEBUG DEBUGCONDUIT << fname << ": Skipped secret record: [" << currentRecord << "], title: [" << memo->getTitle() << "]" << endl; #endif } delete pilotRec; currentRecord++; } #ifdef DEBUG DEBUGCONDUIT << fname << ": read: [" << fMemoList.count() << "] records from palm." << endl; #endif } /** * Read all memos in from Pilot. */ void MemofileConduit::getModifiedFromPilot() { FUNCTIONSETUP; fMemoList.clear(); int currentRecord = 0; PilotRecord *pilotRec; PilotMemo *memo = 0; while ((pilotRec = fDatabase->readNextModifiedRec()) != NULL) { memo = new PilotMemo(pilotRec); // we are syncing to both our filesystem and to the local // databse, so take care of the local database here if (memo->isDeleted()) { fLocalDatabase->deleteRecord(memo->getID()); } else { fLocalDatabase->writeRecord(pilotRec); } if ((!pilotRec->isSecret()) || _sync_private) { fMemoList.append(memo); #ifdef DEBUG DEBUGCONDUIT << fname << ": modified memo id: [" << memo->getID() << "], title: [" << memo->getTitle() << "]" << endl; #endif } else { #ifdef DEBUG DEBUGCONDUIT << fname << ": skipped secret modified record id: [" << memo->getID() << "], title: [" << memo->getTitle() << "]" << endl; #endif } delete pilotRec; currentRecord++; } #ifdef DEBUG DEBUGCONDUIT << fname << ": read: [" << fMemoList.count() << "] modified records from palm." << endl; #endif } /* slot */ void MemofileConduit::process() { FUNCTIONSETUP; #ifdef DEBUG DEBUGCONDUIT << fname << ": Now in state " << fActionStatus << endl; #endif } void MemofileConduit::listPilotMemos() { FUNCTIONSETUP; PilotMemo *memo; for ( memo = fMemoList.first(); memo; memo = fMemoList.next() ) { QString _category_name = fCategories[memo->getCat()]; #ifdef DEBUG DEBUGCONDUIT << fname << ": listing record id: [" << memo->id() << "] category id: [" << memo->getCat() << "] category name: [" << _category_name << "] title: [" << memo->getTitle() << "]" << endl; #endif } } bool MemofileConduit::copyHHToPC() { FUNCTIONSETUP; getAllFromPilot(); _memofiles->eraseLocalMemos(); _memofiles->setPilotMemos(fMemoList); _memofiles->save(); return true; } bool MemofileConduit::copyPCToHH() { FUNCTIONSETUP; _memofiles->load(true); QPtrList<Memofile> memofiles = _memofiles->getAll(); Memofile * memofile; for ( memofile = memofiles.first(); memofile; memofile = memofiles.next() ) { writeToPilot(memofile); } _memofiles->save(); return true; } int MemofileConduit::writeToPilot(Memofile * memofile) { FUNCTIONSETUP; int oldid = memofile->id(); PilotRecord *r = memofile->pack(); int newid = fDatabase->writeRecord(r); fLocalDatabase->writeRecord(r); delete r; memofile->setID(newid); QString status; if (oldid <=0) { _countNewToPilot++; status = "new to pilot"; } else { _countModifiedToPilot++; status = "updated"; } #ifdef DEBUG DEBUGCONDUIT << fname << ": memofile: [" << memofile->toString() << "] written to the pilot, [" << status << "]." << endl; #endif return newid; } void MemofileConduit::deleteFromPilot(Memofile * memofile) { FUNCTIONSETUP; fDatabase->deleteRecord(memofile->getID()); fLocalDatabase->deleteRecord(memofile->getID()); _countDeletedToPilot++; #ifdef DEBUG DEBUGCONDUIT << fname << ": memofile: [" << memofile->toString() << "] deleted from the pilot." << endl; #endif } bool MemofileConduit::sync() { FUNCTIONSETUP; _memofiles->load(false); getModifiedFromPilot(); PilotMemo *memo; for ( memo = fMemoList.first(); memo; memo = fMemoList.next() ) { _memofiles->addModifiedMemo(memo); } QPtrList<Memofile> memofiles = _memofiles->getModified(); Memofile *memofile; for ( memofile = memofiles.first(); memofile; memofile = memofiles.next() ) { if (memofile->isDeleted()) { deleteFromPilot(memofile); } else { writeToPilot(memofile); } } _memofiles->save(); return true; } QString MemofileConduit::getResults() { QString result = ""; if (_countNewToPilot > 0) result += QString::number(_countNewToPilot) + " new to Palm. "; if (_countModifiedToPilot > 0) result += QString::number(_countModifiedToPilot) + " changed to Palm. "; if (_countDeletedToPilot > 0) result += QString::number(_countDeletedToPilot) + " deleted from Palm. "; result += _memofiles->getResults(); if (result.length() <= 0) result = " no changes made."; return result; } void MemofileConduit::cleanup() { FUNCTIONSETUP; fDatabase->cleanup(); fDatabase->resetSyncFlags(); fLocalDatabase->cleanup(); fLocalDatabase->resetSyncFlags(); }
/* memofile-conduit.cc KPilot ** ** Copyright (C) 2004-2004 by Jason 'vanRijn' Kasper ** ** This file does the actual conduit work. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as published by ** the Free Software Foundation; either version 2.1 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, ** MA 02111-1307, USA. */ /* ** Bug reports and questions can be sent to [email protected] */ #include "options.h" // Something to allow us to check what revision // the modules are that make up a binary distribution. // // static const char *memofile_conduit_id= "$Id$"; // Only include what we really need: // First UNIX system stuff, then std C++, // then Qt, then KDE, then local includes. // // #include <time.h> // required by pilot-link includes #include <pi-memo.h> #include "pilotMemo.h" #include <qfile.h> #include <qdir.h> #include <qtextcodec.h> #include <kconfig.h> #include <kdebug.h> #include "pilotAppCategory.h" #include "pilotSerialDatabase.h" #include "memofile-factory.h" #include "memofile-conduit.h" #include "memofileSettings.h" /** * Our workhorse. This is the main driver for the conduit. */ MemofileConduit::MemofileConduit(KPilotDeviceLink *d, const char *n, const QStringList &l) : ConduitAction(d,n,l), _DEFAULT_MEMODIR("~/MyMemos/") { FUNCTIONSETUP; #ifdef DEBUG DEBUGCONDUIT<<memofile_conduit_id<<endl; #endif fConduitName=i18n("Memofile"); fMemoList.setAutoDelete(true); } MemofileConduit::~MemofileConduit() { FUNCTIONSETUP; // we're not guaranteed to have this // if (_memofiles) delete _memofiles; } /* virtual */ bool MemofileConduit::exec() { FUNCTIONSETUP; fFirstSync = false; if(!openDatabases(QString::fromLatin1("MemoDB"))) { emit logError(i18n("Unable to open the memo databases on the handheld.")); return false; } readConfig(); if (! initializeFromPilot()) { emit logError(i18n("Cannot initialize from pilot.")); return false; } _memofiles = new Memofiles(fCategories, fMemoAppInfo, _memo_directory); fFirstSync = _memofiles->isFirstSync(); addSyncLogEntry(" Syncing with " + _memo_directory + "."); if (SyncAction::eCopyHHToPC == getSyncDirection() || fFirstSync) { addSyncLogEntry(" Copying Pilot to PC..."); #ifdef DEBUG DEBUGCONDUIT << fname << ": copying Pilot to PC." << endl; #endif copyHHToPC(); } else if (SyncAction::eCopyPCToHH == getSyncDirection()) { #ifdef DEBUG DEBUGCONDUIT << fname << ": copying PC to Pilot." << endl; #endif addSyncLogEntry(" Copying PC to Pilot..."); copyPCToHH(); } else { #ifdef DEBUG DEBUGCONDUIT << fname << ": doing regular sync." << endl; #endif addSyncLogEntry(" Doing regular sync..."); sync(); } cleanup(); #ifdef DEBUG DEBUGCONDUIT << fname << ": stats: " << getResults() << endl; #endif addSyncLogEntry(" " + getResults()); return delayDone(); } bool MemofileConduit::readConfig() { FUNCTIONSETUP; QString dir(MemofileConduitSettings::directory()); if (dir.isEmpty()) { dir = _DEFAULT_MEMODIR; #ifdef DEBUG DEBUGCONDUIT << fname << ": no directory given to us. defaulting to: [" << _DEFAULT_MEMODIR << "]" << endl; #endif } _memo_directory = dir; _sync_private = MemofileConduitSettings::syncPrivate(); #ifdef DEBUG DEBUGCONDUIT << fname << ": Settings... " << " directory: [" << _memo_directory << "], first sync: [" << isFirstSync() << "], sync private: [" << _sync_private << "]" << endl; #endif return true; } void MemofileConduit::getAppInfo() { FUNCTIONSETUP; unsigned char buffer[PilotDatabase::MAX_APPINFO_SIZE]; int appInfoSize = fDatabase->readAppBlock(buffer,PilotDatabase::MAX_APPINFO_SIZE); if (appInfoSize<0) { fActionStatus=Error; return; } unpack_MemoAppInfo(&fMemoAppInfo,buffer,appInfoSize); PilotDatabase::listAppInfo(&fMemoAppInfo.category); } /** * Methods related to getting set up from the Pilot. */ bool MemofileConduit::initializeFromPilot() { _countDeletedToPilot = 0; _countModifiedToPilot = 0; _countNewToPilot = 0; getAppInfo(); if (!loadPilotCategories()) return false; return true; } bool MemofileConduit::loadPilotCategories() { FUNCTIONSETUP; fCategories.clear(); QString _category_name; int _category_id=0; int _category_num=0; for (int i = 0; i < 15; i++) { if (fMemoAppInfo.category.name[i][0]) { _category_name = PilotAppCategory::codec()->toUnicode(fMemoAppInfo.category.name[i]); _category_id = (int)fMemoAppInfo.category.ID[i]; _category_num = i; fCategories[_category_num] = _category_name; #ifdef DEBUG DEBUGCONDUIT << fname << ": Category #" << _category_num << " has ID " << _category_id << " and name " <<_category_name << endl; #endif } } return true; } /** * Read all memos in from Pilot. */ void MemofileConduit::getAllFromPilot() { FUNCTIONSETUP; #ifdef DEBUG DEBUGCONDUIT << fname << ": Database has " << fDatabase->recordCount() << " records." << endl; #endif fMemoList.clear(); int currentRecord = 0; PilotRecord *pilotRec; PilotMemo *memo = 0; while ((pilotRec = fDatabase->readRecordByIndex(currentRecord)) != NULL) { if ((!pilotRec->isSecret()) || _sync_private) { memo = new PilotMemo(pilotRec); fMemoList.append(memo); #ifdef DEBUG DEBUGCONDUIT << fname << ": Added memo: [" << currentRecord << "], id: [" << memo->getID() << "], category: [" << fCategories[memo->getCat()] << "], title: [" << memo->getTitle() << "]" << endl; #endif } else { #ifdef DEBUG DEBUGCONDUIT << fname << ": Skipped secret record: [" << currentRecord << "], title: [" << memo->getTitle() << "]" << endl; #endif } delete pilotRec; currentRecord++; } #ifdef DEBUG DEBUGCONDUIT << fname << ": read: [" << fMemoList.count() << "] records from palm." << endl; #endif } /** * Read all memos in from Pilot. */ void MemofileConduit::getModifiedFromPilot() { FUNCTIONSETUP; fMemoList.clear(); int currentRecord = 0; PilotRecord *pilotRec; PilotMemo *memo = 0; while ((pilotRec = fDatabase->readNextModifiedRec()) != NULL) { memo = new PilotMemo(pilotRec); // we are syncing to both our filesystem and to the local // databse, so take care of the local database here if (memo->isDeleted()) { fLocalDatabase->deleteRecord(memo->getID()); } else { fLocalDatabase->writeRecord(pilotRec); } if ((!pilotRec->isSecret()) || _sync_private) { fMemoList.append(memo); #ifdef DEBUG DEBUGCONDUIT << fname << ": modified memo id: [" << memo->getID() << "], title: [" << memo->getTitle() << "]" << endl; #endif } else { #ifdef DEBUG DEBUGCONDUIT << fname << ": skipped secret modified record id: [" << memo->getID() << "], title: [" << memo->getTitle() << "]" << endl; #endif } delete pilotRec; currentRecord++; } #ifdef DEBUG DEBUGCONDUIT << fname << ": read: [" << fMemoList.count() << "] modified records from palm." << endl; #endif } /* slot */ void MemofileConduit::process() { FUNCTIONSETUP; #ifdef DEBUG DEBUGCONDUIT << fname << ": Now in state " << fActionStatus << endl; #endif } void MemofileConduit::listPilotMemos() { FUNCTIONSETUP; PilotMemo *memo; for ( memo = fMemoList.first(); memo; memo = fMemoList.next() ) { QString _category_name = fCategories[memo->getCat()]; #ifdef DEBUG DEBUGCONDUIT << fname << ": listing record id: [" << memo->id() << "] category id: [" << memo->getCat() << "] category name: [" << _category_name << "] title: [" << memo->getTitle() << "]" << endl; #endif } } bool MemofileConduit::copyHHToPC() { FUNCTIONSETUP; getAllFromPilot(); _memofiles->eraseLocalMemos(); _memofiles->setPilotMemos(fMemoList); _memofiles->save(); return true; } bool MemofileConduit::copyPCToHH() { FUNCTIONSETUP; _memofiles->load(true); QPtrList<Memofile> memofiles = _memofiles->getAll(); Memofile * memofile; for ( memofile = memofiles.first(); memofile; memofile = memofiles.next() ) { writeToPilot(memofile); } _memofiles->save(); return true; } int MemofileConduit::writeToPilot(Memofile * memofile) { FUNCTIONSETUP; int oldid = memofile->id(); PilotRecord *r = memofile->pack(); int newid = fDatabase->writeRecord(r); fLocalDatabase->writeRecord(r); delete r; memofile->setID(newid); QString status; if (oldid <=0) { _countNewToPilot++; status = "new to pilot"; } else { _countModifiedToPilot++; status = "updated"; } #ifdef DEBUG DEBUGCONDUIT << fname << ": memofile: [" << memofile->toString() << "] written to the pilot, [" << status << "]." << endl; #endif return newid; } void MemofileConduit::deleteFromPilot(Memofile * memofile) { FUNCTIONSETUP; fDatabase->deleteRecord(memofile->getID()); fLocalDatabase->deleteRecord(memofile->getID()); _countDeletedToPilot++; #ifdef DEBUG DEBUGCONDUIT << fname << ": memofile: [" << memofile->toString() << "] deleted from the pilot." << endl; #endif } bool MemofileConduit::sync() { FUNCTIONSETUP; _memofiles->load(false); getModifiedFromPilot(); PilotMemo *memo; for ( memo = fMemoList.first(); memo; memo = fMemoList.next() ) { _memofiles->addModifiedMemo(memo); } QPtrList<Memofile> memofiles = _memofiles->getModified(); Memofile *memofile; for ( memofile = memofiles.first(); memofile; memofile = memofiles.next() ) { if (memofile->isDeleted()) { deleteFromPilot(memofile); } else { writeToPilot(memofile); } } _memofiles->save(); return true; } QString MemofileConduit::getResults() { QString result = ""; if (_countNewToPilot > 0) result += QString::number(_countNewToPilot) + " new to Palm. "; if (_countModifiedToPilot > 0) result += QString::number(_countModifiedToPilot) + " changed to Palm. "; if (_countDeletedToPilot > 0) result += QString::number(_countDeletedToPilot) + " deleted from Palm. "; result += _memofiles->getResults(); if (result.length() <= 0) result = " no changes made."; return result; } void MemofileConduit::cleanup() { FUNCTIONSETUP; fDatabase->cleanup(); fDatabase->resetSyncFlags(); fLocalDatabase->cleanup(); fLocalDatabase->resetSyncFlags(); } #include "memofile-conduit.moc"
Include mocs
Include mocs svn path=/trunk/kdepim/; revision=369545
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
be78ce11499ab7c7b97902baac0832c499ac1cd0
media/audio/android/audio_manager_android.cc
media/audio/android/audio_manager_android.cc
// 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 "media/audio/android/audio_manager_android.h" #include "base/android/build_info.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "jni/AudioManagerAndroid_jni.h" #include "media/audio/android/audio_record_input.h" #include "media/audio/android/opensles_input.h" #include "media/audio/android/opensles_output.h" #include "media/audio/audio_manager.h" #include "media/audio/audio_parameters.h" #include "media/audio/fake_audio_input_stream.h" #include "media/base/channel_layout.h" using base::android::AppendJavaStringArrayToStringVector; using base::android::AttachCurrentThread; using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF8ToJavaString; using base::android::ScopedJavaLocalRef; namespace media { static void AddDefaultDevice(AudioDeviceNames* device_names) { DCHECK(device_names->empty()); device_names->push_front( AudioDeviceName(AudioManagerBase::kDefaultDeviceName, AudioManagerBase::kDefaultDeviceId)); } // Maximum number of output streams that can be open simultaneously. static const int kMaxOutputStreams = 10; static const int kDefaultInputBufferSize = 1024; static const int kDefaultOutputBufferSize = 2048; AudioManager* CreateAudioManager(AudioLogFactory* audio_log_factory) { return new AudioManagerAndroid(audio_log_factory); } AudioManagerAndroid::AudioManagerAndroid(AudioLogFactory* audio_log_factory) : AudioManagerBase(audio_log_factory), communication_mode_is_on_(false) { SetMaxOutputStreamsAllowed(kMaxOutputStreams); // WARNING: This is executed on the UI loop, do not add any code here which // loads libraries or attempts to call out into the OS. Instead add such code // to the InitializeOnAudioThread() method below. // Task must be posted last to avoid races from handing out "this" to the // audio thread. GetTaskRunner()->PostTask(FROM_HERE, base::Bind( &AudioManagerAndroid::InitializeOnAudioThread, base::Unretained(this))); } AudioManagerAndroid::~AudioManagerAndroid() { // It's safe to post a task here since Shutdown() will wait for all tasks to // complete before returning. GetTaskRunner()->PostTask(FROM_HERE, base::Bind( &AudioManagerAndroid::ShutdownOnAudioThread, base::Unretained(this))); Shutdown(); } bool AudioManagerAndroid::HasAudioOutputDevices() { return true; } bool AudioManagerAndroid::HasAudioInputDevices() { return true; } void AudioManagerAndroid::GetAudioInputDeviceNames( AudioDeviceNames* device_names) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); // Always add default device parameters as first element. DCHECK(device_names->empty()); AddDefaultDevice(device_names); // Get list of available audio devices. JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobjectArray> j_device_array = Java_AudioManagerAndroid_getAudioInputDeviceNames( env, j_audio_manager_.obj()); if (j_device_array.is_null()) { // Most probable reason for a NULL result here is that the process lacks // MODIFY_AUDIO_SETTINGS or RECORD_AUDIO permissions. return; } jsize len = env->GetArrayLength(j_device_array.obj()); AudioDeviceName device; for (jsize i = 0; i < len; ++i) { ScopedJavaLocalRef<jobject> j_device( env, env->GetObjectArrayElement(j_device_array.obj(), i)); ScopedJavaLocalRef<jstring> j_device_name = Java_AudioDeviceName_name(env, j_device.obj()); ConvertJavaStringToUTF8(env, j_device_name.obj(), &device.device_name); ScopedJavaLocalRef<jstring> j_device_id = Java_AudioDeviceName_id(env, j_device.obj()); ConvertJavaStringToUTF8(env, j_device_id.obj(), &device.unique_id); device_names->push_back(device); } } void AudioManagerAndroid::GetAudioOutputDeviceNames( AudioDeviceNames* device_names) { // TODO(henrika): enumerate using GetAudioInputDeviceNames(). AddDefaultDevice(device_names); } AudioParameters AudioManagerAndroid::GetInputStreamParameters( const std::string& device_id) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); // Use mono as preferred number of input channels on Android to save // resources. Using mono also avoids a driver issue seen on Samsung // Galaxy S3 and S4 devices. See http://crbug.com/256851 for details. JNIEnv* env = AttachCurrentThread(); ChannelLayout channel_layout = CHANNEL_LAYOUT_MONO; int buffer_size = Java_AudioManagerAndroid_getMinInputFrameSize( env, GetNativeOutputSampleRate(), ChannelLayoutToChannelCount(channel_layout)); buffer_size = buffer_size <= 0 ? kDefaultInputBufferSize : buffer_size; int effects = AudioParameters::NO_EFFECTS; effects |= Java_AudioManagerAndroid_shouldUseAcousticEchoCanceler(env) ? AudioParameters::ECHO_CANCELLER : AudioParameters::NO_EFFECTS; int user_buffer_size = GetUserBufferSize(); if (user_buffer_size) buffer_size = user_buffer_size; AudioParameters params( AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, 0, GetNativeOutputSampleRate(), 16, buffer_size, effects); return params; } AudioOutputStream* AudioManagerAndroid::MakeAudioOutputStream( const AudioParameters& params, const std::string& device_id) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); AudioOutputStream* stream = AudioManagerBase::MakeAudioOutputStream(params, std::string()); streams_.insert(static_cast<OpenSLESOutputStream*>(stream)); return stream; } AudioInputStream* AudioManagerAndroid::MakeAudioInputStream( const AudioParameters& params, const std::string& device_id) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); bool has_no_input_streams = HasNoAudioInputStreams(); AudioInputStream* stream = AudioManagerBase::MakeAudioInputStream(params, device_id); // The audio manager for Android creates streams intended for real-time // VoIP sessions and therefore sets the audio mode to MODE_IN_COMMUNICATION. // If a Bluetooth headset is used, the audio stream will use the SCO // channel and therefore have a limited bandwidth (8kHz). if (stream && has_no_input_streams) { communication_mode_is_on_ = true; SetCommunicationAudioModeOn(true); } return stream; } void AudioManagerAndroid::ReleaseOutputStream(AudioOutputStream* stream) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); AudioManagerBase::ReleaseOutputStream(stream); streams_.erase(static_cast<OpenSLESOutputStream*>(stream)); } void AudioManagerAndroid::ReleaseInputStream(AudioInputStream* stream) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); DCHECK(!j_audio_manager_.is_null()); AudioManagerBase::ReleaseInputStream(stream); // Restore the audio mode which was used before the first communication- // mode stream was created. if (HasNoAudioInputStreams()) { communication_mode_is_on_ = false; SetCommunicationAudioModeOn(false); } } AudioOutputStream* AudioManagerAndroid::MakeLinearOutputStream( const AudioParameters& params) { DCHECK_EQ(AudioParameters::AUDIO_PCM_LINEAR, params.format()); DCHECK(GetTaskRunner()->BelongsToCurrentThread()); return new OpenSLESOutputStream(this, params, SL_ANDROID_STREAM_MEDIA); } AudioOutputStream* AudioManagerAndroid::MakeLowLatencyOutputStream( const AudioParameters& params, const std::string& device_id) { DLOG_IF(ERROR, !device_id.empty()) << "Not implemented!"; DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format()); // Set stream type which matches the current system-wide audio mode used by // the Android audio manager. const SLint32 stream_type = communication_mode_is_on_ ? SL_ANDROID_STREAM_VOICE : SL_ANDROID_STREAM_MEDIA; return new OpenSLESOutputStream(this, params, stream_type); } AudioInputStream* AudioManagerAndroid::MakeLinearInputStream( const AudioParameters& params, const std::string& device_id) { // TODO(henrika): add support for device selection if/when any client // needs it. DLOG_IF(ERROR, !device_id.empty()) << "Not implemented!"; DCHECK_EQ(AudioParameters::AUDIO_PCM_LINEAR, params.format()); return new OpenSLESInputStream(this, params); } AudioInputStream* AudioManagerAndroid::MakeLowLatencyInputStream( const AudioParameters& params, const std::string& device_id) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format()); DLOG_IF(ERROR, device_id.empty()) << "Invalid device ID!"; // Use the device ID to select the correct input device. // Note that the input device is always associated with a certain output // device, i.e., this selection does also switch the output device. // All input and output streams will be affected by the device selection. if (!SetAudioDevice(device_id)) { LOG(ERROR) << "Unable to select audio device!"; return NULL; } if (params.effects() != AudioParameters::NO_EFFECTS) { // Platform effects can only be enabled through the AudioRecord path. // An effect should only have been requested here if recommended by // AudioManagerAndroid.shouldUse<Effect>. // // Creating this class requires Jelly Bean, which is already guaranteed by // shouldUse<Effect>. Only DCHECK on that condition to allow tests to use // the effect settings as a way to select the input path. DCHECK_GE(base::android::BuildInfo::GetInstance()->sdk_int(), 16); DVLOG(1) << "Creating AudioRecordInputStream"; return new AudioRecordInputStream(this, params); } DVLOG(1) << "Creating OpenSLESInputStream"; return new OpenSLESInputStream(this, params); } // static bool AudioManagerAndroid::RegisterAudioManager(JNIEnv* env) { return RegisterNativesImpl(env); } void AudioManagerAndroid::SetMute(JNIEnv* env, jobject obj, jboolean muted) { GetTaskRunner()->PostTask( FROM_HERE, base::Bind( &AudioManagerAndroid::DoSetMuteOnAudioThread, base::Unretained(this), muted)); } AudioParameters AudioManagerAndroid::GetPreferredOutputStreamParameters( const std::string& output_device_id, const AudioParameters& input_params) { // TODO(tommi): Support |output_device_id|. DCHECK(GetTaskRunner()->BelongsToCurrentThread()); DLOG_IF(ERROR, !output_device_id.empty()) << "Not implemented!"; ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO; int sample_rate = GetNativeOutputSampleRate(); int buffer_size = GetOptimalOutputFrameSize(sample_rate, 2); int bits_per_sample = 16; int input_channels = 0; if (input_params.IsValid()) { // Use the client's input parameters if they are valid. sample_rate = input_params.sample_rate(); bits_per_sample = input_params.bits_per_sample(); channel_layout = input_params.channel_layout(); input_channels = input_params.input_channels(); buffer_size = GetOptimalOutputFrameSize( sample_rate, ChannelLayoutToChannelCount(channel_layout)); } int user_buffer_size = GetUserBufferSize(); if (user_buffer_size) buffer_size = user_buffer_size; return AudioParameters( AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, input_channels, sample_rate, bits_per_sample, buffer_size, AudioParameters::NO_EFFECTS); } bool AudioManagerAndroid::HasNoAudioInputStreams() { return input_stream_count() == 0; } void AudioManagerAndroid::InitializeOnAudioThread() { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); // Create the Android audio manager on the audio thread. DVLOG(2) << "Creating Java part of the audio manager"; j_audio_manager_.Reset( Java_AudioManagerAndroid_createAudioManagerAndroid( base::android::AttachCurrentThread(), base::android::GetApplicationContext(), reinterpret_cast<intptr_t>(this))); // Prepare the list of audio devices and register receivers for device // notifications. Java_AudioManagerAndroid_init( base::android::AttachCurrentThread(), j_audio_manager_.obj()); } void AudioManagerAndroid::ShutdownOnAudioThread() { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); DVLOG(2) << "Destroying Java part of the audio manager"; Java_AudioManagerAndroid_close( base::android::AttachCurrentThread(), j_audio_manager_.obj()); j_audio_manager_.Reset(); } void AudioManagerAndroid::SetCommunicationAudioModeOn(bool on) { Java_AudioManagerAndroid_setCommunicationAudioModeOn( base::android::AttachCurrentThread(), j_audio_manager_.obj(), on); } bool AudioManagerAndroid::SetAudioDevice(const std::string& device_id) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); // Send the unique device ID to the Java audio manager and make the // device switch. Provide an empty string to the Java audio manager // if the default device is selected. JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jstring> j_device_id = ConvertUTF8ToJavaString( env, device_id == AudioManagerBase::kDefaultDeviceId ? std::string() : device_id); return Java_AudioManagerAndroid_setDevice( env, j_audio_manager_.obj(), j_device_id.obj()); } int AudioManagerAndroid::GetNativeOutputSampleRate() { return Java_AudioManagerAndroid_getNativeOutputSampleRate( base::android::AttachCurrentThread(), j_audio_manager_.obj()); } bool AudioManagerAndroid::IsAudioLowLatencySupported() { return Java_AudioManagerAndroid_isAudioLowLatencySupported( base::android::AttachCurrentThread(), j_audio_manager_.obj()); } int AudioManagerAndroid::GetAudioLowLatencyOutputFrameSize() { return Java_AudioManagerAndroid_getAudioLowLatencyOutputFrameSize( base::android::AttachCurrentThread(), j_audio_manager_.obj()); } int AudioManagerAndroid::GetOptimalOutputFrameSize(int sample_rate, int channels) { if (IsAudioLowLatencySupported()) return GetAudioLowLatencyOutputFrameSize(); return std::max(kDefaultOutputBufferSize, Java_AudioManagerAndroid_getMinOutputFrameSize( base::android::AttachCurrentThread(), sample_rate, channels)); } void AudioManagerAndroid::DoSetMuteOnAudioThread(bool muted) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); for (OutputStreams::iterator it = streams_.begin(); it != streams_.end(); ++it) { (*it)->SetMute(muted); } } } // namespace media
// 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 "media/audio/android/audio_manager_android.h" #include <algorithm> #include <string> #include "base/android/build_info.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "jni/AudioManagerAndroid_jni.h" #include "media/audio/android/audio_record_input.h" #include "media/audio/android/opensles_input.h" #include "media/audio/android/opensles_output.h" #include "media/audio/audio_manager.h" #include "media/audio/audio_parameters.h" #include "media/audio/fake_audio_input_stream.h" #include "media/base/channel_layout.h" using base::android::AppendJavaStringArrayToStringVector; using base::android::AttachCurrentThread; using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF8ToJavaString; using base::android::ScopedJavaLocalRef; namespace media { static void AddDefaultDevice(AudioDeviceNames* device_names) { DCHECK(device_names->empty()); device_names->push_front( AudioDeviceName(AudioManagerBase::kDefaultDeviceName, AudioManagerBase::kDefaultDeviceId)); } // Maximum number of output streams that can be open simultaneously. static const int kMaxOutputStreams = 10; static const int kDefaultInputBufferSize = 1024; static const int kDefaultOutputBufferSize = 2048; AudioManager* CreateAudioManager(AudioLogFactory* audio_log_factory) { return new AudioManagerAndroid(audio_log_factory); } AudioManagerAndroid::AudioManagerAndroid(AudioLogFactory* audio_log_factory) : AudioManagerBase(audio_log_factory), communication_mode_is_on_(false) { SetMaxOutputStreamsAllowed(kMaxOutputStreams); // WARNING: This is executed on the UI loop, do not add any code here which // loads libraries or attempts to call out into the OS. Instead add such code // to the InitializeOnAudioThread() method below. // Task must be posted last to avoid races from handing out "this" to the // audio thread. GetTaskRunner()->PostTask(FROM_HERE, base::Bind( &AudioManagerAndroid::InitializeOnAudioThread, base::Unretained(this))); } AudioManagerAndroid::~AudioManagerAndroid() { // It's safe to post a task here since Shutdown() will wait for all tasks to // complete before returning. GetTaskRunner()->PostTask(FROM_HERE, base::Bind( &AudioManagerAndroid::ShutdownOnAudioThread, base::Unretained(this))); Shutdown(); } bool AudioManagerAndroid::HasAudioOutputDevices() { return true; } bool AudioManagerAndroid::HasAudioInputDevices() { return true; } void AudioManagerAndroid::GetAudioInputDeviceNames( AudioDeviceNames* device_names) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); // Always add default device parameters as first element. DCHECK(device_names->empty()); AddDefaultDevice(device_names); // Get list of available audio devices. JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobjectArray> j_device_array = Java_AudioManagerAndroid_getAudioInputDeviceNames( env, j_audio_manager_.obj()); if (j_device_array.is_null()) { // Most probable reason for a NULL result here is that the process lacks // MODIFY_AUDIO_SETTINGS or RECORD_AUDIO permissions. return; } jsize len = env->GetArrayLength(j_device_array.obj()); AudioDeviceName device; for (jsize i = 0; i < len; ++i) { ScopedJavaLocalRef<jobject> j_device( env, env->GetObjectArrayElement(j_device_array.obj(), i)); ScopedJavaLocalRef<jstring> j_device_name = Java_AudioDeviceName_name(env, j_device.obj()); ConvertJavaStringToUTF8(env, j_device_name.obj(), &device.device_name); ScopedJavaLocalRef<jstring> j_device_id = Java_AudioDeviceName_id(env, j_device.obj()); ConvertJavaStringToUTF8(env, j_device_id.obj(), &device.unique_id); device_names->push_back(device); } } void AudioManagerAndroid::GetAudioOutputDeviceNames( AudioDeviceNames* device_names) { // TODO(henrika): enumerate using GetAudioInputDeviceNames(). AddDefaultDevice(device_names); } AudioParameters AudioManagerAndroid::GetInputStreamParameters( const std::string& device_id) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); // Use mono as preferred number of input channels on Android to save // resources. Using mono also avoids a driver issue seen on Samsung // Galaxy S3 and S4 devices. See http://crbug.com/256851 for details. JNIEnv* env = AttachCurrentThread(); ChannelLayout channel_layout = CHANNEL_LAYOUT_MONO; int buffer_size = Java_AudioManagerAndroid_getMinInputFrameSize( env, GetNativeOutputSampleRate(), ChannelLayoutToChannelCount(channel_layout)); buffer_size = buffer_size <= 0 ? kDefaultInputBufferSize : buffer_size; int effects = AudioParameters::NO_EFFECTS; effects |= Java_AudioManagerAndroid_shouldUseAcousticEchoCanceler(env) ? AudioParameters::ECHO_CANCELLER : AudioParameters::NO_EFFECTS; int user_buffer_size = GetUserBufferSize(); if (user_buffer_size) buffer_size = user_buffer_size; AudioParameters params( AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, 0, GetNativeOutputSampleRate(), 16, buffer_size, effects); return params; } AudioOutputStream* AudioManagerAndroid::MakeAudioOutputStream( const AudioParameters& params, const std::string& device_id) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); AudioOutputStream* stream = AudioManagerBase::MakeAudioOutputStream(params, std::string()); streams_.insert(static_cast<OpenSLESOutputStream*>(stream)); return stream; } AudioInputStream* AudioManagerAndroid::MakeAudioInputStream( const AudioParameters& params, const std::string& device_id) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); bool has_no_input_streams = HasNoAudioInputStreams(); AudioInputStream* stream = AudioManagerBase::MakeAudioInputStream(params, device_id); // The audio manager for Android creates streams intended for real-time // VoIP sessions and therefore sets the audio mode to MODE_IN_COMMUNICATION. // If a Bluetooth headset is used, the audio stream will use the SCO // channel and therefore have a limited bandwidth (8kHz). if (stream && has_no_input_streams) { communication_mode_is_on_ = true; SetCommunicationAudioModeOn(true); } return stream; } void AudioManagerAndroid::ReleaseOutputStream(AudioOutputStream* stream) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); AudioManagerBase::ReleaseOutputStream(stream); streams_.erase(static_cast<OpenSLESOutputStream*>(stream)); } void AudioManagerAndroid::ReleaseInputStream(AudioInputStream* stream) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); DCHECK(!j_audio_manager_.is_null()); AudioManagerBase::ReleaseInputStream(stream); // Restore the audio mode which was used before the first communication- // mode stream was created. if (HasNoAudioInputStreams()) { communication_mode_is_on_ = false; SetCommunicationAudioModeOn(false); } } AudioOutputStream* AudioManagerAndroid::MakeLinearOutputStream( const AudioParameters& params) { DCHECK_EQ(AudioParameters::AUDIO_PCM_LINEAR, params.format()); DCHECK(GetTaskRunner()->BelongsToCurrentThread()); return new OpenSLESOutputStream(this, params, SL_ANDROID_STREAM_MEDIA); } AudioOutputStream* AudioManagerAndroid::MakeLowLatencyOutputStream( const AudioParameters& params, const std::string& device_id) { DLOG_IF(ERROR, !device_id.empty()) << "Not implemented!"; DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format()); // Set stream type which matches the current system-wide audio mode used by // the Android audio manager. const SLint32 stream_type = communication_mode_is_on_ ? SL_ANDROID_STREAM_VOICE : SL_ANDROID_STREAM_MEDIA; return new OpenSLESOutputStream(this, params, stream_type); } AudioInputStream* AudioManagerAndroid::MakeLinearInputStream( const AudioParameters& params, const std::string& device_id) { // TODO(henrika): add support for device selection if/when any client // needs it. DLOG_IF(ERROR, !device_id.empty()) << "Not implemented!"; DCHECK_EQ(AudioParameters::AUDIO_PCM_LINEAR, params.format()); return new OpenSLESInputStream(this, params); } AudioInputStream* AudioManagerAndroid::MakeLowLatencyInputStream( const AudioParameters& params, const std::string& device_id) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); DCHECK_EQ(AudioParameters::AUDIO_PCM_LOW_LATENCY, params.format()); DLOG_IF(ERROR, device_id.empty()) << "Invalid device ID!"; // Use the device ID to select the correct input device. // Note that the input device is always associated with a certain output // device, i.e., this selection does also switch the output device. // All input and output streams will be affected by the device selection. if (!SetAudioDevice(device_id)) { LOG(ERROR) << "Unable to select audio device!"; return NULL; } if (params.effects() != AudioParameters::NO_EFFECTS) { // Platform effects can only be enabled through the AudioRecord path. // An effect should only have been requested here if recommended by // AudioManagerAndroid.shouldUse<Effect>. // // Creating this class requires Jelly Bean, which is already guaranteed by // shouldUse<Effect>. Only DCHECK on that condition to allow tests to use // the effect settings as a way to select the input path. DCHECK_GE(base::android::BuildInfo::GetInstance()->sdk_int(), 16); DVLOG(1) << "Creating AudioRecordInputStream"; return new AudioRecordInputStream(this, params); } // TODO(xingnan): Crash will happen in the openSL ES library on some IA // devices like ZTE Geek V975, Use AudioRecordInputStream path instead as // a workaround. Will fall back after the fix of the bug. #if defined(ARCH_CPU_X86) if (base::android::BuildInfo::GetInstance()->sdk_int() < 16) return NULL; DVLOG(1) << "Creating AudioRecordInputStream"; return new AudioRecordInputStream(this, params); #else DVLOG(1) << "Creating OpenSLESInputStream"; return new OpenSLESInputStream(this, params); #endif } // static bool AudioManagerAndroid::RegisterAudioManager(JNIEnv* env) { return RegisterNativesImpl(env); } void AudioManagerAndroid::SetMute(JNIEnv* env, jobject obj, jboolean muted) { GetTaskRunner()->PostTask( FROM_HERE, base::Bind( &AudioManagerAndroid::DoSetMuteOnAudioThread, base::Unretained(this), muted)); } AudioParameters AudioManagerAndroid::GetPreferredOutputStreamParameters( const std::string& output_device_id, const AudioParameters& input_params) { // TODO(tommi): Support |output_device_id|. DCHECK(GetTaskRunner()->BelongsToCurrentThread()); DLOG_IF(ERROR, !output_device_id.empty()) << "Not implemented!"; ChannelLayout channel_layout = CHANNEL_LAYOUT_STEREO; int sample_rate = GetNativeOutputSampleRate(); int buffer_size = GetOptimalOutputFrameSize(sample_rate, 2); int bits_per_sample = 16; int input_channels = 0; if (input_params.IsValid()) { // Use the client's input parameters if they are valid. sample_rate = input_params.sample_rate(); bits_per_sample = input_params.bits_per_sample(); channel_layout = input_params.channel_layout(); input_channels = input_params.input_channels(); buffer_size = GetOptimalOutputFrameSize( sample_rate, ChannelLayoutToChannelCount(channel_layout)); } int user_buffer_size = GetUserBufferSize(); if (user_buffer_size) buffer_size = user_buffer_size; return AudioParameters( AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, input_channels, sample_rate, bits_per_sample, buffer_size, AudioParameters::NO_EFFECTS); } bool AudioManagerAndroid::HasNoAudioInputStreams() { return input_stream_count() == 0; } void AudioManagerAndroid::InitializeOnAudioThread() { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); // Create the Android audio manager on the audio thread. DVLOG(2) << "Creating Java part of the audio manager"; j_audio_manager_.Reset( Java_AudioManagerAndroid_createAudioManagerAndroid( base::android::AttachCurrentThread(), base::android::GetApplicationContext(), reinterpret_cast<intptr_t>(this))); // Prepare the list of audio devices and register receivers for device // notifications. Java_AudioManagerAndroid_init( base::android::AttachCurrentThread(), j_audio_manager_.obj()); } void AudioManagerAndroid::ShutdownOnAudioThread() { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); DVLOG(2) << "Destroying Java part of the audio manager"; Java_AudioManagerAndroid_close( base::android::AttachCurrentThread(), j_audio_manager_.obj()); j_audio_manager_.Reset(); } void AudioManagerAndroid::SetCommunicationAudioModeOn(bool on) { Java_AudioManagerAndroid_setCommunicationAudioModeOn( base::android::AttachCurrentThread(), j_audio_manager_.obj(), on); } bool AudioManagerAndroid::SetAudioDevice(const std::string& device_id) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); // Send the unique device ID to the Java audio manager and make the // device switch. Provide an empty string to the Java audio manager // if the default device is selected. JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jstring> j_device_id = ConvertUTF8ToJavaString( env, device_id == AudioManagerBase::kDefaultDeviceId ? std::string() : device_id); return Java_AudioManagerAndroid_setDevice( env, j_audio_manager_.obj(), j_device_id.obj()); } int AudioManagerAndroid::GetNativeOutputSampleRate() { return Java_AudioManagerAndroid_getNativeOutputSampleRate( base::android::AttachCurrentThread(), j_audio_manager_.obj()); } bool AudioManagerAndroid::IsAudioLowLatencySupported() { return Java_AudioManagerAndroid_isAudioLowLatencySupported( base::android::AttachCurrentThread(), j_audio_manager_.obj()); } int AudioManagerAndroid::GetAudioLowLatencyOutputFrameSize() { return Java_AudioManagerAndroid_getAudioLowLatencyOutputFrameSize( base::android::AttachCurrentThread(), j_audio_manager_.obj()); } int AudioManagerAndroid::GetOptimalOutputFrameSize(int sample_rate, int channels) { if (IsAudioLowLatencySupported()) return GetAudioLowLatencyOutputFrameSize(); return std::max(kDefaultOutputBufferSize, Java_AudioManagerAndroid_getMinOutputFrameSize( base::android::AttachCurrentThread(), sample_rate, channels)); } void AudioManagerAndroid::DoSetMuteOnAudioThread(bool muted) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); for (OutputStreams::iterator it = streams_.begin(); it != streams_.end(); ++it) { (*it)->SetMute(muted); } } } // namespace media
Fix the crash of GetUserMedia
[Android] Fix the crash of GetUserMedia Crash happens when releasing the audio resource of localusermedia in openSL ES. On Android there are two ways to get the audio input: openSL ES and java Recording API. We swtich to the Recording API as a workaround of the bug. The limitation is Recording API only be avaiable after version 15 of SDK. BUG=XWALK-1833
C++
bsd-3-clause
bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk
4a57ac1516a6b09c426b926f0ab29fa74d3fd27e
app/src/main.cpp
app/src/main.cpp
/* Copyright (C) 2016 INRA * * 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 <fstream> #include <iomanip> #include <iostream> #include <limits> #include <lpcore-out> #include <lpcore> #include <sstream> #include <cerrno> #include <climits> #include <cmath> #include <cstdio> #include <cstring> #include <getopt.h> #include <sys/types.h> #include <unistd.h> void help() noexcept; double to_double(const char* s, double bad_value) noexcept; long to_long(const char* s, long bad_value) noexcept; std::tuple<std::string, lp::parameter> split_param(const char* param) noexcept; const char* file_format_error_format(lp::file_format_error::tag) noexcept; const char* problem_definition_error_format( lp::problem_definition_error::tag) noexcept; const char* solver_error_format(lp::solver_error::tag) noexcept; lp::result solve(std::shared_ptr<lp::context> ctx, lp::problem& pb, const std::map<std::string, lp::parameter>& params, bool optimize); int main(int argc, char* argv[]) { const char* const short_opts = "Ohp:l:qv:"; const struct option long_opts[] = { { "optimize", 0, nullptr, 'O' }, { "help", 0, nullptr, 'h' }, { "param", 1, nullptr, 'p' }, { "limit", 1, nullptr, 'l' }, { "quiet", 0, nullptr, 0 }, { "verbose", 1, nullptr, 'v' }, { 0, 0, nullptr, 0 } }; int opt_index; int verbose = 1; bool fail = false; bool optimize = false; bool quiet = false; std::map<std::string, lp::parameter> parameters; while (not fail) { const auto opt = getopt_long(argc, argv, short_opts, long_opts, &opt_index); if (opt == -1) break; switch (opt) { case 0: break; case 'O': optimize = true; break; case 'l': parameters["limit"] = to_long(::optarg, 1000l); break; case 'h': help(); return EXIT_SUCCESS; case 'p': { std::string name; lp::parameter value; std::tie(name, value) = split_param(::optarg); parameters[name] = value; } break; case '?': default: fail = true; std::fprintf(stderr, "Unknown command line option\n"); break; }; } if (fail) return EXIT_FAILURE; (void)verbose; (void)quiet; auto ctx = std::make_shared<lp::context>(); ctx->set_standard_stream_logger(); for (int i = ::optind; i < argc; ++i) { try { auto pb = lp::make_problem(ctx, argv[i]); std::string filename(argv[i]); filename += '-'; filename += std::to_string(::getpid()); filename += '_'; filename += std::to_string(i); filename += ".sol"; ctx->log(lp::context::message_type::info, "solution: %s\n", filename.c_str()); std::ofstream ofs(filename); ofs << std::boolalpha << std::setprecision(std::floor( std::numeric_limits<double>::digits * std::log10(2) + 2)); auto now = std::chrono::system_clock::now(); auto in_time_t = std::chrono::system_clock::to_time_t(now); ofs << "start: " << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %X") << '\n'; auto ret = solve(ctx, pb, parameters, optimize); if (ret.status == lp::result_status::success) { ofs << "Solution found: " << ret.value << '\n' << ret; } else { ofs << "Solution not found. Missing constraints: " << ret.remaining_constraints << '\n'; } } catch (const lp::precondition_error& e) { std::fprintf(stderr, "internal failure\n"); } catch (const lp::postcondition_error& e) { std::fprintf(stderr, "internal failure\n"); } catch (const lp::numeric_cast_error& e) { std::fprintf(stderr, "numeric cast interal failure\n"); } catch (const lp::file_access_error& e) { std::fprintf(stderr, "file `%s' fail %d: %s\n", e.file().c_str(), e.error(), std::strerror(e.error())); } catch (const lp::file_format_error& e) { std::fprintf(stderr, "file format error at line %d column %d " "%s\n", e.line(), e.column(), file_format_error_format(e.failure())); } catch (const lp::problem_definition_error& e) { std::fprintf(stderr, "definition problem error at %s: %s\n", e.element().c_str(), problem_definition_error_format(e.failure())); } catch (const lp::solver_error& e) { std::fprintf( stderr, "solver error: %s\n", solver_error_format(e.failure())); } catch (const std::exception& e) { std::fprintf(stderr, "failure: %s.\n", e.what()); } } return EXIT_SUCCESS; } void help() noexcept { std::fprintf(stdout, "--help|-h This help message\n" "--param|-p [name]:[value] Add a new parameter (name is" " [a-z][A-Z]_ value can be a double, an integer otherwise a" " string.\n" "--optimize|-O Optimize model (default " "feasibility search only)\n" "--limit int Set limit\n" "--quiet Remove any verbose message\n" "--verbose|-v int Set verbose level\n"); } const char* file_format_error_format(lp::file_format_error::tag failure) noexcept { static const char* const tag[] = { "end of file", "unknown", "already defined", "incomplete", "bad name", "bad operator", "bad integer", "bad objective function type", "bad bound", "bad function element", "bad constraint" }; switch (failure) { case lp::file_format_error::tag::end_of_file: return tag[0]; case lp::file_format_error::tag::unknown: return tag[1]; case lp::file_format_error::tag::already_defined: return tag[2]; case lp::file_format_error::tag::incomplete: return tag[3]; case lp::file_format_error::tag::bad_name: return tag[4]; case lp::file_format_error::tag::bad_operator: return tag[5]; case lp::file_format_error::tag::bad_integer: return tag[6]; case lp::file_format_error::tag::bad_objective_function_type: return tag[7]; case lp::file_format_error::tag::bad_bound: return tag[8]; case lp::file_format_error::tag::bad_function_element: return tag[9]; case lp::file_format_error::tag::bad_constraint: return tag[10]; } return nullptr; } const char* problem_definition_error_format( lp::problem_definition_error::tag failure) noexcept { static const char* const tag[] = { "empty variables", "empty objective function", "variable not used", "bad bound", "multiple constraints with different value" }; switch (failure) { case lp::problem_definition_error::tag::empty_variables: return tag[0]; case lp::problem_definition_error::tag::empty_objective_function: return tag[1]; case lp::problem_definition_error::tag::variable_not_used: return tag[2]; case lp::problem_definition_error::tag::bad_bound: return tag[3]; case lp::problem_definition_error::tag::multiple_constraint: return tag[4]; } return nullptr; } const char* solver_error_format(lp::solver_error::tag failure) noexcept { static const char* const tag[] = { "no solver available", "unrealisable constraint", "not enough memory" }; switch (failure) { case lp::solver_error::tag::no_solver_available: return tag[0]; case lp::solver_error::tag::unrealisable_constraint: return tag[1]; case lp::solver_error::tag::not_enough_memory: return tag[2]; } return nullptr; } double to_double(const char* s, double bad_value) noexcept { char* c; errno = 0; double value = std::strtod(s, &c); if ((errno == ERANGE and (value == HUGE_VAL or value == -HUGE_VAL)) or (value == 0.0 and c == s)) return bad_value; return value; } long to_long(const char* s, long bad_value) noexcept { char* c; errno = 0; long value = std::strtol(s, &c, 10); if ((errno == ERANGE and (value == LONG_MIN or value == LONG_MAX)) or (value == 0 and c == s)) return bad_value; return value; } std::tuple<std::string, lp::parameter> split_param(const char* param) noexcept { std::string name, value; while (*param) { if (isalpha(*param) or *param == '_' or *param == '-') name += *param; else break; param++; } if (*param and (*param == ':' or *param == '=')) { param++; while (*param) value += *param++; } auto valuel = to_long(value.c_str(), LONG_MIN); auto valued = to_double(value.c_str(), -HUGE_VAL); double tmp; if (valued != -HUGE_VAL and std::modf(valued, &tmp)) return std::make_tuple(name, lp::parameter(valued)); if (valuel != LONG_MIN) return std::make_tuple(name, lp::parameter(valuel)); return std::make_tuple(name, lp::parameter(value)); } lp::result solve(std::shared_ptr<lp::context> ctx, lp::problem& pb, const std::map<std::string, lp::parameter>& params, bool optimize) { if (optimize) return lp::optimize(ctx, pb, params); return lp::solve(ctx, pb, params); }
/* Copyright (C) 2016 INRA * * 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 <lpcore-out> #include <lpcore> #include <fstream> #include <iomanip> #include <limits> #include <sstream> #include <cerrno> #include <climits> #include <cmath> #include <cstdio> #include <cstring> #include <getopt.h> #include <sys/types.h> #include <unistd.h> void help(std::shared_ptr<lp::context> ctx) noexcept; double to_double(const char* s, double bad_value) noexcept; long to_long(const char* s, long bad_value) noexcept; std::tuple<std::string, lp::parameter> split_param(const char* param) noexcept; const char* file_format_error_format(lp::file_format_error::tag) noexcept; const char* problem_definition_error_format( lp::problem_definition_error::tag) noexcept; const char* solver_error_format(lp::solver_error::tag) noexcept; lp::result solve(std::shared_ptr<lp::context> ctx, lp::problem& pb, const std::map<std::string, lp::parameter>& params, bool optimize); int main(int argc, char* argv[]) { const char* const short_opts = "Ohp:l:qv:"; const struct option long_opts[] = { { "optimize", 0, nullptr, 'O' }, { "help", 0, nullptr, 'h' }, { "param", 1, nullptr, 'p' }, { "limit", 1, nullptr, 'l' }, { "quiet", 0, nullptr, 0 }, { "verbose", 1, nullptr, 'v' }, { 0, 0, nullptr, 0 } }; int opt_index; int verbose = 1; bool fail = false; bool optimize = false; bool quiet = false; std::map<std::string, lp::parameter> parameters; auto ctx = std::make_shared<lp::context>(); ctx->set_standard_stream_logger(); while (not fail) { const auto opt = getopt_long(argc, argv, short_opts, long_opts, &opt_index); if (opt == -1) break; switch (opt) { case 0: break; case 'O': optimize = true; break; case 'l': parameters["limit"] = to_long(::optarg, 1000l); break; case 'h': help(ctx); return EXIT_SUCCESS; case 'p': { std::string name; lp::parameter value; std::tie(name, value) = split_param(::optarg); parameters[name] = value; } break; case '?': default: fail = true; ctx->error("Unknown command line option\n"); break; }; } if (fail) return EXIT_FAILURE; (void)verbose; (void)quiet; for (int i = ::optind; i < argc; ++i) { try { auto pb = lp::make_problem(ctx, argv[i]); std::string filename(argv[i]); filename += '-'; filename += std::to_string(::getpid()); filename += '_'; filename += std::to_string(i); filename += ".sol"; ctx->info("Output file: %s\n", filename.c_str()); std::ofstream ofs(filename); ofs << std::boolalpha << std::setprecision(std::floor( std::numeric_limits<double>::digits * std::log10(2) + 2)); auto now = std::chrono::system_clock::now(); auto in_time_t = std::chrono::system_clock::to_time_t(now); ofs << lp::resume(pb) << "start: " << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %X") << std::endl; auto ret = solve(ctx, pb, parameters, optimize); if (ret.status == lp::result_status::success) { ofs << "Solution found: " << ret.value << '\n' << ret; } else { ofs << "Solution not found. Missing constraints: " << ret.remaining_constraints << '\n'; } } catch (const lp::precondition_error& e) { ctx->error("internal failure\n"); } catch (const lp::postcondition_error& e) { ctx->error("internal failure\n"); } catch (const lp::numeric_cast_error& e) { ctx->error("numeric cast interal failure\n"); } catch (const lp::file_access_error& e) { ctx->error("file `%s' fail %d: %s\n", e.file().c_str(), e.error(), std::strerror(e.error())); } catch (const lp::file_format_error& e) { ctx->error("file format error at line %d column %d " "%s\n", e.line(), e.column(), file_format_error_format(e.failure())); } catch (const lp::problem_definition_error& e) { ctx->error("definition problem error at %s: %s\n", e.element().c_str(), problem_definition_error_format(e.failure())); } catch (const lp::solver_error& e) { ctx->error("solver error: %s\n", solver_error_format(e.failure())); } catch (const std::exception& e) { ctx->error("failure: %s.\n", e.what()); } } return EXIT_SUCCESS; } void help(std::shared_ptr<lp::context> ctx) noexcept { ctx->info("--help|-h This help message\n" "--param|-p [name]:[value] Add a new parameter (name is" " [a-z][A-Z]_ value can be a double, an integer otherwise a" " string.\n" "--optimize|-O Optimize model (default " "feasibility search only)\n" "--limit int Set limit\n" "--quiet Remove any verbose message\n" "--verbose|-v int Set verbose level\n"); } const char* file_format_error_format(lp::file_format_error::tag failure) noexcept { static const char* const tag[] = { "end of file", "unknown", "already defined", "incomplete", "bad name", "bad operator", "bad integer", "bad objective function type", "bad bound", "bad function element", "bad constraint" }; switch (failure) { case lp::file_format_error::tag::end_of_file: return tag[0]; case lp::file_format_error::tag::unknown: return tag[1]; case lp::file_format_error::tag::already_defined: return tag[2]; case lp::file_format_error::tag::incomplete: return tag[3]; case lp::file_format_error::tag::bad_name: return tag[4]; case lp::file_format_error::tag::bad_operator: return tag[5]; case lp::file_format_error::tag::bad_integer: return tag[6]; case lp::file_format_error::tag::bad_objective_function_type: return tag[7]; case lp::file_format_error::tag::bad_bound: return tag[8]; case lp::file_format_error::tag::bad_function_element: return tag[9]; case lp::file_format_error::tag::bad_constraint: return tag[10]; } return nullptr; } const char* problem_definition_error_format( lp::problem_definition_error::tag failure) noexcept { static const char* const tag[] = { "empty variables", "empty objective function", "variable not used", "bad bound", "multiple constraints with different value" }; switch (failure) { case lp::problem_definition_error::tag::empty_variables: return tag[0]; case lp::problem_definition_error::tag::empty_objective_function: return tag[1]; case lp::problem_definition_error::tag::variable_not_used: return tag[2]; case lp::problem_definition_error::tag::bad_bound: return tag[3]; case lp::problem_definition_error::tag::multiple_constraint: return tag[4]; } return nullptr; } const char* solver_error_format(lp::solver_error::tag failure) noexcept { static const char* const tag[] = { "no solver available", "unrealisable constraint", "not enough memory" }; switch (failure) { case lp::solver_error::tag::no_solver_available: return tag[0]; case lp::solver_error::tag::unrealisable_constraint: return tag[1]; case lp::solver_error::tag::not_enough_memory: return tag[2]; } return nullptr; } double to_double(const char* s, double bad_value) noexcept { char* c; errno = 0; double value = std::strtod(s, &c); if ((errno == ERANGE and (value == HUGE_VAL or value == -HUGE_VAL)) or (value == 0.0 and c == s)) return bad_value; return value; } long to_long(const char* s, long bad_value) noexcept { char* c; errno = 0; long value = std::strtol(s, &c, 10); if ((errno == ERANGE and (value == LONG_MIN or value == LONG_MAX)) or (value == 0 and c == s)) return bad_value; return value; } std::tuple<std::string, lp::parameter> split_param(const char* param) noexcept { std::string name, value; while (*param) { if (isalpha(*param) or *param == '_' or *param == '-') name += *param; else break; param++; } if (*param and (*param == ':' or *param == '=')) { param++; while (*param) value += *param++; } auto valuel = to_long(value.c_str(), LONG_MIN); auto valued = to_double(value.c_str(), -HUGE_VAL); double tmp; if (valued != -HUGE_VAL and std::modf(valued, &tmp)) return std::make_tuple(name, lp::parameter(valued)); if (valuel != LONG_MIN) return std::make_tuple(name, lp::parameter(valuel)); return std::make_tuple(name, lp::parameter(value)); } lp::result solve(std::shared_ptr<lp::context> ctx, lp::problem& pb, const std::map<std::string, lp::parameter>& params, bool optimize) { if (optimize) return lp::optimize(ctx, pb, params); return lp::solve(ctx, pb, params); }
use context to write console message
main: use context to write console message
C++
mit
quesnel/baryonyx,quesnel/baryonyx,quesnel/baryonyx
2cf576b4e73d20f6687527bfc275243316a8a9e3
app/src/main.cpp
app/src/main.cpp
/* Copyright (C) 2016 INRA * * 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 <fstream> #include <iostream> #include <limits> #include <lpcore> #include <sstream> #include <cerrno> #include <cstdio> #include <cstring> #include <getopt.h> double to_double(const char* s, double bad_value); long to_long(const char* s, long bad_value); std::tuple<std::string, lp::parameter> split_param(const char* param) { std::string name, value; while (*param) { if (isalpha(*param) or *param == '_') name += *param; else break; param++; } if (*param and *param == ':') { param++; while (*param) { if (isalnum(*param) or *param == '_' or *param == ':') value += *param; else break; param++; } } auto valuel = to_long(::optarg, std::numeric_limits<long>::min()); if (valuel != std::numeric_limits<long>::min()) return std::make_tuple(name, lp::parameter(valuel)); auto valued = to_double(::optarg, std::numeric_limits<double>::min()); if (valued != std::numeric_limits<double>::min()) return std::make_tuple(name, lp::parameter(valued)); return std::make_tuple(name, lp::parameter(value)); } const char* file_format_error_format(lp::file_format_error::tag); const char* problem_definition_error_format(lp::problem_definition_error::tag); const char* solver_error_format(lp::solver_error::tag); void help() { std::fprintf(stdout, "--help|-h This help message\n" "--param|-p [name]:[value] Add a new parameter (name is" " [a-z][A-Z]_ value can be a double, an integer otherwise a" " string.\n" "--limit int Set limit\n" "--quiet Remove any verbose message\n" "--verbose|-v int Set verbose level\n"); } int main(int argc, char* argv[]) { const char* const short_opts = "hp:l:qv:"; const struct option long_opts[] = { { "help", 0, nullptr, 'h' }, { "param", 1, nullptr, 'p' }, { "limit", 1, nullptr, 'l' }, { "quiet", 0, nullptr, 0 }, { "verbose", 1, nullptr, 'v' }, { 0, 0, nullptr, 0 } }; int opt_index; int verbose = 1; bool fail = false; bool quiet = false; std::map<std::string, lp::parameter> parameters; while (not fail) { const auto opt = getopt_long(argc, argv, short_opts, long_opts, &opt_index); if (opt == -1) break; switch (opt) { case 0: break; case 'h': help(); return EXIT_SUCCESS; case 'p': { std::string name; lp::parameter value; std::tie(name, value) = split_param(::optarg); parameters[name] = value; } break; case '?': default: fail = true; std::fprintf(stderr, "Unknown command line option\n"); break; }; } if (fail) return EXIT_FAILURE; (void)verbose; (void)quiet; for (int i = ::optind; i < argc; ++i) { try { auto pb = lp::make_problem(argv[i]); auto ret = lp::solve(pb, parameters); for (std::size_t i{ 0 }, e{ ret.variable_name.size() }; i != e; ++i) std::fprintf(stdout, "%s = %d\n", ret.variable_name[i].c_str(), ret.variable_value[i]); } catch (const lp::precondition_error& e) { std::fprintf(stderr, "internal failure\n"); } catch (const lp::postcondition_error& e) { std::fprintf(stderr, "internal failure\n"); } catch (const lp::numeric_cast_error& e) { std::fprintf(stderr, "numeric cast interal failure\n"); } catch (const lp::file_access_error& e) { std::fprintf(stderr, "file `%s' fail %d: %s\n", e.file().c_str(), e.error(), std::strerror(e.error())); } catch (const lp::file_format_error& e) { std::fprintf(stderr, "file format error at line %d column %d " "%s\n", e.line(), e.column(), file_format_error_format(e.failure())); } catch (const lp::problem_definition_error& e) { std::fprintf(stderr, "definition problem error at %s: %s\n", e.element().c_str(), problem_definition_error_format(e.failure())); } catch (const lp::solver_error& e) { std::fprintf( stderr, "solver error: %s\n", solver_error_format(e.failure())); } catch (const std::exception& e) { std::fprintf(stderr, "failure: %s.\n", e.what()); } } return EXIT_SUCCESS; } const char* file_format_error_format(lp::file_format_error::tag failure) { static const char* const tag[] = { "end of file", "unknown", "already defined", "incomplete", "bad name", "bad operator", "bad integer", "bad objective function type", "bad bound", "bad function element", "bad constraint" }; switch (failure) { case lp::file_format_error::tag::end_of_file: return tag[0]; case lp::file_format_error::tag::unknown: return tag[1]; case lp::file_format_error::tag::already_defined: return tag[2]; case lp::file_format_error::tag::incomplete: return tag[3]; case lp::file_format_error::tag::bad_name: return tag[4]; case lp::file_format_error::tag::bad_operator: return tag[5]; case lp::file_format_error::tag::bad_integer: return tag[6]; case lp::file_format_error::tag::bad_objective_function_type: return tag[7]; case lp::file_format_error::tag::bad_bound: return tag[8]; case lp::file_format_error::tag::bad_function_element: return tag[9]; case lp::file_format_error::tag::bad_constraint: return tag[10]; } return nullptr; } const char* problem_definition_error_format(lp::problem_definition_error::tag failure) { static const char* const tag[] = { "empty variables", "empty objective function", "variable not used", "bad bound", "multiple constraints with different value" }; switch (failure) { case lp::problem_definition_error::tag::empty_variables: return tag[0]; case lp::problem_definition_error::tag::empty_objective_function: return tag[1]; case lp::problem_definition_error::tag::variable_not_used: return tag[2]; case lp::problem_definition_error::tag::bad_bound: return tag[3]; case lp::problem_definition_error::tag::multiple_constraint: return tag[4]; } return nullptr; } const char* solver_error_format(lp::solver_error::tag failure) { static const char* const tag[] = { "no solver available", "unrealisable constraint", "not enough memory" }; switch (failure) { case lp::solver_error::tag::no_solver_available: return tag[0]; case lp::solver_error::tag::unrealisable_constraint: return tag[1]; case lp::solver_error::tag::not_enough_memory: return tag[2]; } return nullptr; } double to_double(const char* s, double bad_value) { char* c; errno = 0; double value = std::strtof(s, &c); if ((errno == ERANGE and (value == std::numeric_limits<double>::lowest() or value == -std::numeric_limits<double>::max())) or (errno != 0 and value == 0) or (c == ::optarg)) return value; return bad_value; } long to_long(const char* s, long bad_value) { char* c; errno = 0; long value = std::strtol(s, &c, 10); if ((errno == ERANGE and (value == std::numeric_limits<long>::lowest() or value == std::numeric_limits<long>::max())) or (errno != 0 and value == 0) or (c == ::optarg)) return value; return bad_value; }
/* Copyright (C) 2016 INRA * * 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 <fstream> #include <iostream> #include <limits> #include <lpcore> #include <sstream> #include <cerrno> #include <cmath> #include <cstdio> #include <cstring> #include <getopt.h> void help() noexcept; double to_double(const char* s, double bad_value) noexcept; long to_long(const char* s, long bad_value) noexcept; std::tuple<std::string, lp::parameter> split_param(const char* param) noexcept; const char* file_format_error_format(lp::file_format_error::tag) noexcept; const char* problem_definition_error_format( lp::problem_definition_error::tag) noexcept; const char* solver_error_format(lp::solver_error::tag) noexcept; int main(int argc, char* argv[]) { const char* const short_opts = "hp:l:qv:"; const struct option long_opts[] = { { "help", 0, nullptr, 'h' }, { "param", 1, nullptr, 'p' }, { "limit", 1, nullptr, 'l' }, { "quiet", 0, nullptr, 0 }, { "verbose", 1, nullptr, 'v' }, { 0, 0, nullptr, 0 } }; int opt_index; int verbose = 1; bool fail = false; bool quiet = false; std::map<std::string, lp::parameter> parameters; while (not fail) { const auto opt = getopt_long(argc, argv, short_opts, long_opts, &opt_index); if (opt == -1) break; switch (opt) { case 0: break; case 'l': parameters["limit"] = to_long(::optarg, 1000l); break; case 'h': help(); return EXIT_SUCCESS; case 'p': { std::string name; lp::parameter value; std::tie(name, value) = split_param(::optarg); parameters[name] = value; } break; case '?': default: fail = true; std::fprintf(stderr, "Unknown command line option\n"); break; }; } if (fail) return EXIT_FAILURE; (void)verbose; (void)quiet; for (int i = ::optind; i < argc; ++i) { try { auto pb = lp::make_problem(argv[i]); auto ret = lp::solve(pb, parameters); if (ret.solution_found and lp::is_valid_solution(pb, ret.variable_value)) { std::fprintf(stdout, "Solution found: %f\n", ret.value); for (std::size_t i{ 0 }, e{ ret.variable_name.size() }; i != e; ++i) std::fprintf(stdout, "%s = %d", ret.variable_name[i].c_str(), ret.variable_value[i]); } else { std::fprintf(stdout, "No solution found\n"); } } catch (const lp::precondition_error& e) { std::fprintf(stderr, "internal failure\n"); } catch (const lp::postcondition_error& e) { std::fprintf(stderr, "internal failure\n"); } catch (const lp::numeric_cast_error& e) { std::fprintf(stderr, "numeric cast interal failure\n"); } catch (const lp::file_access_error& e) { std::fprintf(stderr, "file `%s' fail %d: %s\n", e.file().c_str(), e.error(), std::strerror(e.error())); } catch (const lp::file_format_error& e) { std::fprintf(stderr, "file format error at line %d column %d " "%s\n", e.line(), e.column(), file_format_error_format(e.failure())); } catch (const lp::problem_definition_error& e) { std::fprintf(stderr, "definition problem error at %s: %s\n", e.element().c_str(), problem_definition_error_format(e.failure())); } catch (const lp::solver_error& e) { std::fprintf( stderr, "solver error: %s\n", solver_error_format(e.failure())); } catch (const std::exception& e) { std::fprintf(stderr, "failure: %s.\n", e.what()); } } return EXIT_SUCCESS; } void help() noexcept { std::fprintf(stdout, "--help|-h This help message\n" "--param|-p [name]:[value] Add a new parameter (name is" " [a-z][A-Z]_ value can be a double, an integer otherwise a" " string.\n" "--limit int Set limit\n" "--quiet Remove any verbose message\n" "--verbose|-v int Set verbose level\n"); } const char* file_format_error_format(lp::file_format_error::tag failure) noexcept { static const char* const tag[] = { "end of file", "unknown", "already defined", "incomplete", "bad name", "bad operator", "bad integer", "bad objective function type", "bad bound", "bad function element", "bad constraint" }; switch (failure) { case lp::file_format_error::tag::end_of_file: return tag[0]; case lp::file_format_error::tag::unknown: return tag[1]; case lp::file_format_error::tag::already_defined: return tag[2]; case lp::file_format_error::tag::incomplete: return tag[3]; case lp::file_format_error::tag::bad_name: return tag[4]; case lp::file_format_error::tag::bad_operator: return tag[5]; case lp::file_format_error::tag::bad_integer: return tag[6]; case lp::file_format_error::tag::bad_objective_function_type: return tag[7]; case lp::file_format_error::tag::bad_bound: return tag[8]; case lp::file_format_error::tag::bad_function_element: return tag[9]; case lp::file_format_error::tag::bad_constraint: return tag[10]; } return nullptr; } const char* problem_definition_error_format( lp::problem_definition_error::tag failure) noexcept { static const char* const tag[] = { "empty variables", "empty objective function", "variable not used", "bad bound", "multiple constraints with different value" }; switch (failure) { case lp::problem_definition_error::tag::empty_variables: return tag[0]; case lp::problem_definition_error::tag::empty_objective_function: return tag[1]; case lp::problem_definition_error::tag::variable_not_used: return tag[2]; case lp::problem_definition_error::tag::bad_bound: return tag[3]; case lp::problem_definition_error::tag::multiple_constraint: return tag[4]; } return nullptr; } const char* solver_error_format(lp::solver_error::tag failure) noexcept { static const char* const tag[] = { "no solver available", "unrealisable constraint", "not enough memory" }; switch (failure) { case lp::solver_error::tag::no_solver_available: return tag[0]; case lp::solver_error::tag::unrealisable_constraint: return tag[1]; case lp::solver_error::tag::not_enough_memory: return tag[2]; } return nullptr; } double to_double(const char* s, double bad_value) noexcept { char* c; errno = 0; double value = std::strtof(s, &c); if ((errno == ERANGE and (value == std::numeric_limits<double>::lowest() or value == -std::numeric_limits<double>::max())) or (errno != 0 and value == 0) or (c == ::optarg)) return bad_value; return value; } long to_long(const char* s, long bad_value) noexcept { char* c; errno = 0; long value = std::strtol(s, &c, 10); if ((errno == ERANGE and (value == std::numeric_limits<long>::lowest() or value == std::numeric_limits<long>::max())) or (errno != 0 and value == 0) or (c == ::optarg)) return bad_value; return value; } std::tuple<std::string, lp::parameter> split_param(const char* param) noexcept { std::string name, value; while (*param) { if (isalpha(*param) or *param == '_' or *param == '-') name += *param; else break; param++; } if (*param and (*param == ':' or *param == '=')) { param++; while (*param) { if (isalnum(*param) or *param == '.') value += *param; else break; param++; } } auto valuel = to_long(value.c_str(), std::numeric_limits<long>::min()); auto valued = to_double(value.c_str(), std::numeric_limits<double>::min()); double tmp; if (valued != std::numeric_limits<double>::min() and std::modf(valued, &tmp)) return std::make_tuple(name, lp::parameter(valued)); if (valuel != std::numeric_limits<long>::min()) return std::make_tuple(name, lp::parameter(valuel)); return std::make_tuple(name, lp::parameter(value)); }
update main to pass correctly parameters
app: update main to pass correctly parameters
C++
mit
quesnel/baryonyx,quesnel/baryonyx,quesnel/baryonyx
2a035c00cde4d33a4f562915c0a1370892b98fb1
src/qt/aboutdialog.cpp
src/qt/aboutdialog.cpp
#include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" // Copyright year (2009-this) // Todo: update this when changing our copyright comments in the source const int ABOUTDIALOG_COPYRIGHT_YEAR = 2013; AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers") + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("2011-%1 The Litecoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR)); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); }
#include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" // Copyright year (2009-this) // Todo: update this when changing our copyright comments in the source const int ABOUTDIALOG_COPYRIGHT_YEAR = 2014; AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers") + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("2011-%1 The Litecoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR)); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); }
Update aboutdialog.cpp
Update aboutdialog.cpp
C++
mit
uberadminer/Bobe-Coin,uberadminer/Bobe-Coin,uberadminer/Bobe-Coin,uberadminer/Bobe-Coin,uberadminer/Bobe-Coin
37c209bc6eef9fa8888a9f28081bb048f8b6eedf
src/qt/messagepage.cpp
src/qt/messagepage.cpp
#include <string> #include <vector> #include "main.h" #include "wallet.h" #include "init.h" #include "util.h" #include "messagepage.h" #include "ui_messagepage.h" #include "addressbookpage.h" #include "guiutil.h" #include "walletmodel.h" #include <QClipboard> #include <QInputDialog> #include <QList> #include <QListWidgetItem> #include <QMessageBox> MessagePage::MessagePage(QWidget *parent) : QDialog(parent), ui(new Ui::MessagePage) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->signFrom, this); } MessagePage::~MessagePage() { delete ui; } void MessagePage::setModel(WalletModel *model) { this->model = model; } void MessagePage::setAddress(QString addr) { ui->signFrom->setText(addr); ui->message->setFocus(); } void MessagePage::on_pasteButton_clicked() { setAddress(QApplication::clipboard()->text()); } void MessagePage::on_addressBookButton_clicked() { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { setAddress(dlg.getReturnValue()); } } void MessagePage::on_copyToClipboard_clicked() { QApplication::clipboard()->setText(ui->signature->text()); } void MessagePage::on_signMessage_clicked() { QString address = ui->signFrom->text(); CBitcoinAddress addr(address.toStdString()); if (!addr.IsValid()) { QMessageBox::critical(this, tr("Error signing"), tr("%1 is not a valid address.").arg(address), QMessageBox::Abort, QMessageBox::Abort); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled return; } CKey key; if (!pwalletMain->GetKey(addr, key)) { QMessageBox::critical(this, tr("Error signing"), tr("Private key for %1 is not available.").arg(address), QMessageBox::Abort, QMessageBox::Abort); return; } CDataStream ss(SER_GETHASH); ss << strMessageMagic; ss << ui->message->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) { QMessageBox::critical(this, tr("Error signing"), tr("Sign failed"), QMessageBox::Abort, QMessageBox::Abort); } ui->signature->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); ui->signature->setFont(GUIUtil::bitcoinAddressFont()); }
#include <string> #include <vector> #include <QClipboard> #include <QInputDialog> #include <QList> #include <QListWidgetItem> #include <QMessageBox> #include "main.h" #include "wallet.h" #include "init.h" #include "util.h" #include "messagepage.h" #include "ui_messagepage.h" #include "addressbookpage.h" #include "guiutil.h" #include "walletmodel.h" MessagePage::MessagePage(QWidget *parent) : QDialog(parent), ui(new Ui::MessagePage) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->signFrom, this); } MessagePage::~MessagePage() { delete ui; } void MessagePage::setModel(WalletModel *model) { this->model = model; } void MessagePage::setAddress(QString addr) { ui->signFrom->setText(addr); ui->message->setFocus(); } void MessagePage::on_pasteButton_clicked() { setAddress(QApplication::clipboard()->text()); } void MessagePage::on_addressBookButton_clicked() { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { setAddress(dlg.getReturnValue()); } } void MessagePage::on_copyToClipboard_clicked() { QApplication::clipboard()->setText(ui->signature->text()); } void MessagePage::on_signMessage_clicked() { QString address = ui->signFrom->text(); CBitcoinAddress addr(address.toStdString()); if (!addr.IsValid()) { QMessageBox::critical(this, tr("Error signing"), tr("%1 is not a valid address.").arg(address), QMessageBox::Abort, QMessageBox::Abort); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled return; } CKey key; if (!pwalletMain->GetKey(addr, key)) { QMessageBox::critical(this, tr("Error signing"), tr("Private key for %1 is not available.").arg(address), QMessageBox::Abort, QMessageBox::Abort); return; } CDataStream ss(SER_GETHASH); ss << strMessageMagic; ss << ui->message->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) { QMessageBox::critical(this, tr("Error signing"), tr("Sign failed"), QMessageBox::Abort, QMessageBox::Abort); } ui->signature->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); ui->signature->setFont(GUIUtil::bitcoinAddressFont()); }
Fix compilation warning.
Fix compilation warning.
C++
mit
coinkeeper/2015-06-22_19-10_cannacoin,reddcoin-project/reddcoin,ahmedbodi/poscoin,bmp02050/ReddcoinUpdates,coinkeeper/2015-06-22_18-46_reddcoin,reddcoin-project/reddcoin,coinkeeper/2015-06-22_18-46_reddcoin,coinkeeper/2015-06-22_18-46_reddcoin,coinkeeper/2015-06-22_19-10_cannacoin,reddcoin-project/reddcoin,bmp02050/ReddcoinUpdates,ahmedbodi/poscoin,reddink/reddcoin,bmp02050/ReddcoinUpdates,reddcoin-project/reddcoin,joroob/reddcoin,coinkeeper/2015-06-22_18-46_reddcoin,joroob/reddcoin,ahmedbodi/poscoin,reddink/reddcoin,ahmedbodi/poscoin,reddink/reddcoin,coinkeeper/2015-06-22_19-10_cannacoin,bmp02050/ReddcoinUpdates,ahmedbodi/poscoin,joroob/reddcoin,joroob/reddcoin,reddink/reddcoin,Cannacoin-Project/Cannacoin,Cannacoin-Project/Cannacoin,bmp02050/ReddcoinUpdates,Cannacoin-Project/Cannacoin,coinkeeper/2015-06-22_19-10_cannacoin,reddcoin-project/reddcoin,Cannacoin-Project/Cannacoin,Cannacoin-Project/Cannacoin,joroob/reddcoin,reddink/reddcoin,coinkeeper/2015-06-22_18-46_reddcoin,reddcoin-project/reddcoin,coinkeeper/2015-06-22_19-10_cannacoin
14cca407837d638ee789ed4f38697e089011d9c7
lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp
lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp
//===- lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp ----------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MipsTargetHandler.h" #include "MipsLinkingContext.h" #include "MipsRelocationHandler.h" #include "lld/ReaderWriter/RelocationHelperFunctions.h" using namespace lld; using namespace elf; using namespace llvm::ELF; namespace { inline void applyReloc(uint8_t *location, uint32_t result) { auto target = reinterpret_cast<llvm::support::ulittle32_t *>(location); *target = result | uint32_t(*target); } /// \brief Calculate AHL value combines addends from 'hi' and 'lo' relocations. inline int64_t calcAHL(int64_t AHI, int64_t ALO) { AHI &= 0xffff; ALO &= 0xffff; return (AHI << 16) + (int16_t)ALO; } template <size_t BITS, class T> inline T signExtend(T val) { if (val & (T(1) << (BITS - 1))) val |= T(-1) << BITS; return val; } /// \brief R_MIPS_32 /// local/external: word32 S + A (truncate) void reloc32(uint8_t *location, uint64_t P, uint64_t S, int64_t A) { applyReloc(location, (S + A) & 0xffffffff); } /// \brief R_MIPS_26 /// local : ((A | ((P + 4) & 0x3F000000)) + S) >> 2 /// external: (sign–extend(A) + S) >> 2 void reloc26(uint8_t *location, uint64_t P, uint64_t S, bool isLocal) { int32_t A = (*(uint32_t*)location & 0x03FFFFFFU) << 2; uint32_t result = isLocal ? (A | ((P + 4) & 0x3F000000)) : signExtend<28>(A); result = (result + S) >> 2; applyReloc(location, result); } /// \brief R_MIPS_HI16 /// local/external: hi16 (AHL + S) - (short)(AHL + S) (truncate) /// _gp_disp : hi16 (AHL + GP - P) - (short)(AHL + GP - P) (verify) void relocHi16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL, uint64_t GP, bool isGPDisp) { int32_t result = 0; if (isGPDisp) result = (AHL + GP - P) - (int16_t)(AHL + GP - P); else result = (AHL + S) - (int16_t)(AHL + S); applyReloc(location, (result >> 16) & 0xffff); } /// \brief R_MIPS_LO16 /// local/external: lo16 AHL + S (truncate) /// _gp_disp : lo16 AHL + GP - P + 4 (verify) void relocLo16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL, uint64_t GP, bool isGPDisp) { int32_t result = 0; if (isGPDisp) result = AHL + GP - P + 4; else result = AHL + S; applyReloc(location, result & 0xffff); } /// \brief R_MIPS_GOT16 /// local/external: rel16 G (verify) void relocGOT16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL, uint64_t GP) { // FIXME (simon): for local sym put high 16 bit of AHL to the GOT int32_t G = (int32_t)(S - GP); applyReloc(location, G & 0xffff); } /// \brief R_MIPS_CALL16 /// external: rel16 G (verify) void relocCall16(uint8_t *location, uint64_t P, uint64_t S, int64_t A, uint64_t GP) { int32_t G = (int32_t)(S - GP); applyReloc(location, G & 0xffff); } /// \brief LLD_R_MIPS_HI16 void relocLldHi16(uint8_t *location, uint64_t S) { applyReloc(location, ((S + 0x8000) >> 16) & 0xffff); } /// \brief LLD_R_MIPS_LO16 void relocLldLo16(uint8_t *location, uint64_t S) { applyReloc(location, S & 0xffff); } } // end anon namespace MipsTargetRelocationHandler::~MipsTargetRelocationHandler() { assert(_pairedRelocations.empty()); } void MipsTargetRelocationHandler::savePairedRelocation(const lld::AtomLayout &atom, const Reference &ref) const { auto pi = _pairedRelocations.find(&atom); if (pi == _pairedRelocations.end()) pi = _pairedRelocations.emplace(&atom, PairedRelocationsT()).first; pi->second.push_back(&ref); } void MipsTargetRelocationHandler::applyPairedRelocations( ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom, int64_t gpAddr, int64_t loAddend) const { auto pi = _pairedRelocations.find(&atom); if (pi == _pairedRelocations.end()) return; for (auto ri : pi->second) { uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset; uint8_t *location = atomContent + ri->offsetInAtom(); uint64_t targetVAddress = writer.addressOfAtom(ri->target()); uint64_t relocVAddress = atom._virtualAddr + ri->offsetInAtom(); int64_t ahl = calcAHL(ri->addend(), loAddend); if (ri->kindNamespace() != lld::Reference::KindNamespace::ELF) continue; assert(ri->kindArch() == Reference::KindArch::Mips); switch (ri->kindValue()) { case R_MIPS_HI16: relocHi16(location, relocVAddress, targetVAddress, ahl, gpAddr, ri->target()->name() == "_gp_disp"); break; case R_MIPS_GOT16: relocGOT16(location, relocVAddress, targetVAddress, ahl, gpAddr); break; default: llvm_unreachable("Unknown type of paired relocation."); } } _pairedRelocations.erase(pi); } error_code MipsTargetRelocationHandler::applyRelocation( ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom, const Reference &ref) const { AtomLayout *gpAtom = _mipsTargetLayout.getGP(); uint64_t gpAddr = gpAtom ? gpAtom->_virtualAddr : 0; uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset; uint8_t *location = atomContent + ref.offsetInAtom(); uint64_t targetVAddress = writer.addressOfAtom(ref.target()); uint64_t relocVAddress = atom._virtualAddr + ref.offsetInAtom(); if (ref.kindNamespace() != lld::Reference::KindNamespace::ELF) return error_code::success(); assert(ref.kindArch() == Reference::KindArch::Mips); switch (ref.kindValue()) { case R_MIPS_NONE: break; case R_MIPS_32: reloc32(location, relocVAddress, targetVAddress, ref.addend()); break; case R_MIPS_26: reloc26(location, relocVAddress, targetVAddress, true); break; case R_MIPS_HI16: savePairedRelocation(atom, ref); break; case R_MIPS_LO16: relocLo16(location, relocVAddress, targetVAddress, calcAHL(0, ref.addend()), gpAddr, ref.target()->name() == "_gp_disp"); applyPairedRelocations(writer, buf, atom, gpAddr, ref.addend()); break; case R_MIPS_GOT16: savePairedRelocation(atom, ref); break; case R_MIPS_CALL16: relocCall16(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_JALR: // We do not do JALR optimization now. break; case R_MIPS_JUMP_SLOT: // Ignore runtime relocations. break; case LLD_R_MIPS_GLOBAL_GOT: // Do nothing. break; case LLD_R_MIPS_GLOBAL_GOT16: relocGOT16(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case LLD_R_MIPS_GLOBAL_26: reloc26(location, relocVAddress, targetVAddress, false); break; case LLD_R_MIPS_HI16: relocLldHi16(location, targetVAddress); break; case LLD_R_MIPS_LO16: relocLldLo16(location, targetVAddress); break; default: { std::string str; llvm::raw_string_ostream s(str); s << "Unhandled Mips relocation: " << ref.kindValue(); llvm_unreachable(s.str().c_str()); } } return error_code::success(); }
//===- lib/ReaderWriter/ELF/Mips/MipsRelocationHandler.cpp ----------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MipsTargetHandler.h" #include "MipsLinkingContext.h" #include "MipsRelocationHandler.h" #include "lld/ReaderWriter/RelocationHelperFunctions.h" using namespace lld; using namespace elf; using namespace llvm::ELF; namespace { inline void applyReloc(uint8_t *location, uint32_t result) { auto target = reinterpret_cast<llvm::support::ulittle32_t *>(location); *target = result | uint32_t(*target); } /// \brief Calculate AHL value combines addends from 'hi' and 'lo' relocations. inline int64_t calcAHL(int64_t AHI, int64_t ALO) { AHI &= 0xffff; ALO &= 0xffff; return (AHI << 16) + (int16_t)ALO; } template <size_t BITS, class T> inline T signExtend(T val) { if (val & (T(1) << (BITS - 1))) val |= T(-1) << BITS; return val; } /// \brief R_MIPS_32 /// local/external: word32 S + A (truncate) void reloc32(uint8_t *location, uint64_t P, uint64_t S, int64_t A) { applyReloc(location, (S + A) & 0xffffffff); } /// \brief R_MIPS_26 /// local : ((A | ((P + 4) & 0x3F000000)) + S) >> 2 /// external: (sign–extend(A) + S) >> 2 void reloc26(uint8_t *location, uint64_t P, uint64_t S, bool isLocal) { int32_t A = (*(uint32_t*)location & 0x03FFFFFFU) << 2; uint32_t result = isLocal ? (A | ((P + 4) & 0x3F000000)) : signExtend<28>(A); result = (result + S) >> 2; applyReloc(location, result); } /// \brief R_MIPS_HI16 /// local/external: hi16 (AHL + S) - (short)(AHL + S) (truncate) /// _gp_disp : hi16 (AHL + GP - P) - (short)(AHL + GP - P) (verify) void relocHi16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL, uint64_t GP, bool isGPDisp) { int32_t result = 0; if (isGPDisp) result = (AHL + GP - P) - (int16_t)(AHL + GP - P); else result = (AHL + S) - (int16_t)(AHL + S); applyReloc(location, (result >> 16) & 0xffff); } /// \brief R_MIPS_LO16 /// local/external: lo16 AHL + S (truncate) /// _gp_disp : lo16 AHL + GP - P + 4 (verify) void relocLo16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL, uint64_t GP, bool isGPDisp) { int32_t result = 0; if (isGPDisp) result = AHL + GP - P + 4; else result = AHL + S; applyReloc(location, result & 0xffff); } /// \brief R_MIPS_GOT16 /// local/external: rel16 G (verify) void relocGOT16(uint8_t *location, uint64_t P, uint64_t S, int64_t AHL, uint64_t GP) { // FIXME (simon): for local sym put high 16 bit of AHL to the GOT int32_t G = (int32_t)(S - GP); applyReloc(location, G & 0xffff); } /// \brief R_MIPS_CALL16 /// external: rel16 G (verify) void relocCall16(uint8_t *location, uint64_t P, uint64_t S, int64_t A, uint64_t GP) { int32_t G = (int32_t)(S - GP); applyReloc(location, G & 0xffff); } /// \brief LLD_R_MIPS_HI16 void relocLldHi16(uint8_t *location, uint64_t S) { applyReloc(location, ((S + 0x8000) >> 16) & 0xffff); } /// \brief LLD_R_MIPS_LO16 void relocLldLo16(uint8_t *location, uint64_t S) { applyReloc(location, S & 0xffff); } } // end anon namespace MipsTargetRelocationHandler::~MipsTargetRelocationHandler() { assert(_pairedRelocations.empty()); } void MipsTargetRelocationHandler::savePairedRelocation(const lld::AtomLayout &atom, const Reference &ref) const { auto pi = _pairedRelocations.find(&atom); if (pi == _pairedRelocations.end()) pi = _pairedRelocations.emplace(&atom, PairedRelocationsT()).first; pi->second.push_back(&ref); } void MipsTargetRelocationHandler::applyPairedRelocations( ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom, int64_t gpAddr, int64_t loAddend) const { auto pi = _pairedRelocations.find(&atom); if (pi == _pairedRelocations.end()) return; for (auto ri : pi->second) { uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset; uint8_t *location = atomContent + ri->offsetInAtom(); uint64_t targetVAddress = writer.addressOfAtom(ri->target()); uint64_t relocVAddress = atom._virtualAddr + ri->offsetInAtom(); int64_t ahl = calcAHL(ri->addend(), loAddend); if (ri->kindNamespace() != lld::Reference::KindNamespace::ELF) continue; assert(ri->kindArch() == Reference::KindArch::Mips); switch (ri->kindValue()) { case R_MIPS_HI16: relocHi16(location, relocVAddress, targetVAddress, ahl, gpAddr, ri->target()->name() == "_gp_disp"); break; case R_MIPS_GOT16: relocGOT16(location, relocVAddress, targetVAddress, ahl, gpAddr); break; default: llvm_unreachable("Unknown type of paired relocation."); } } _pairedRelocations.erase(pi); } error_code MipsTargetRelocationHandler::applyRelocation( ELFWriter &writer, llvm::FileOutputBuffer &buf, const lld::AtomLayout &atom, const Reference &ref) const { if (ref.kindNamespace() != lld::Reference::KindNamespace::ELF) return error_code::success(); assert(ref.kindArch() == Reference::KindArch::Mips); AtomLayout *gpAtom = _mipsTargetLayout.getGP(); uint64_t gpAddr = gpAtom ? gpAtom->_virtualAddr : 0; uint8_t *atomContent = buf.getBufferStart() + atom._fileOffset; uint8_t *location = atomContent + ref.offsetInAtom(); uint64_t targetVAddress = writer.addressOfAtom(ref.target()); uint64_t relocVAddress = atom._virtualAddr + ref.offsetInAtom(); switch (ref.kindValue()) { case R_MIPS_NONE: break; case R_MIPS_32: reloc32(location, relocVAddress, targetVAddress, ref.addend()); break; case R_MIPS_26: reloc26(location, relocVAddress, targetVAddress, true); break; case R_MIPS_HI16: savePairedRelocation(atom, ref); break; case R_MIPS_LO16: relocLo16(location, relocVAddress, targetVAddress, calcAHL(0, ref.addend()), gpAddr, ref.target()->name() == "_gp_disp"); applyPairedRelocations(writer, buf, atom, gpAddr, ref.addend()); break; case R_MIPS_GOT16: savePairedRelocation(atom, ref); break; case R_MIPS_CALL16: relocCall16(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case R_MIPS_JALR: // We do not do JALR optimization now. break; case R_MIPS_JUMP_SLOT: // Ignore runtime relocations. break; case LLD_R_MIPS_GLOBAL_GOT: // Do nothing. break; case LLD_R_MIPS_GLOBAL_GOT16: relocGOT16(location, relocVAddress, targetVAddress, ref.addend(), gpAddr); break; case LLD_R_MIPS_GLOBAL_26: reloc26(location, relocVAddress, targetVAddress, false); break; case LLD_R_MIPS_HI16: relocLldHi16(location, targetVAddress); break; case LLD_R_MIPS_LO16: relocLldLo16(location, targetVAddress); break; default: { std::string str; llvm::raw_string_ostream s(str); s << "Unhandled Mips relocation: " << ref.kindValue(); llvm_unreachable(s.str().c_str()); } } return error_code::success(); }
Exit from the class method as soon as possible.
[Mips] Exit from the class method as soon as possible. git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@202287 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/lld,llvm-mirror/lld
3f2774cabebf505f6f5853b9295985ab932d7a99
modules/fluid_properties/src/base/FluidPropertiesApp.C
modules/fluid_properties/src/base/FluidPropertiesApp.C
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "FluidPropertiesApp.h" #include "Moose.h" #include "AppFactory.h" #include "MooseSyntax.h" InputParameters FluidPropertiesApp::validParams() { InputParameters params = MooseApp::validParams(); params.set<bool>("use_legacy_material_output") = false; return params; } registerKnownLabel("FluidPropertiesApp"); FluidPropertiesApp::FluidPropertiesApp(InputParameters parameters) : MooseApp(parameters) { FluidPropertiesApp::registerAll(_factory, _action_factory, _syntax); } FluidPropertiesApp::~FluidPropertiesApp() {} void FluidPropertiesApp::registerApps() { registerApp(FluidPropertiesApp); } static void associateSyntaxInner(Syntax & syntax, ActionFactory & /*action_factory*/) { registerSyntaxTask( "AddFluidPropertiesAction", "Modules/FluidProperties/*", "add_fluid_properties"); registerMooseObjectTask("add_fluid_properties", FluidProperties, false); registerMooseObjectTask("add_fp_output", Output, false); syntax.addDependency("add_fluid_properties", "init_displaced_problem"); syntax.addDependency("add_user_object", "add_fluid_properties"); syntax.addDependency("add_fp_output", "add_output"); syntax.addDependency("add_postprocessor", "add_fp_output"); syntax.registerActionSyntax("AddFluidPropertiesInterrogatorAction", "FluidPropertiesInterrogator"); } void FluidPropertiesApp::registerAll(Factory & f, ActionFactory & af, Syntax & s) { Registry::registerObjectsTo(f, {"FluidPropertiesApp"}); Registry::registerActionsTo(af, {"FluidPropertiesApp"}); associateSyntaxInner(s, af); } void FluidPropertiesApp::registerObjects(Factory & factory) { mooseDeprecated("use registerAll instead of registerObjects"); Registry::registerObjectsTo(factory, {"FluidPropertiesApp"}); } void FluidPropertiesApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory) { mooseDeprecated("use registerAll instead of associateSyntax"); Registry::registerActionsTo(action_factory, {"FluidPropertiesApp"}); associateSyntaxInner(syntax, action_factory); } void FluidPropertiesApp::registerExecFlags(Factory & /*factory*/) { mooseDeprecated("use registerAll instead of registerExecFlags"); } extern "C" void FluidPropertiesApp__registerAll(Factory & f, ActionFactory & af, Syntax & s) { FluidPropertiesApp::registerAll(f, af, s); } extern "C" void FluidPropertiesApp__registerApps() { FluidPropertiesApp::registerApps(); }
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "FluidPropertiesApp.h" #include "Moose.h" #include "AppFactory.h" #include "MooseSyntax.h" InputParameters FluidPropertiesApp::validParams() { InputParameters params = MooseApp::validParams(); params.set<bool>("use_legacy_material_output") = false; return params; } registerKnownLabel("FluidPropertiesApp"); FluidPropertiesApp::FluidPropertiesApp(InputParameters parameters) : MooseApp(parameters) { FluidPropertiesApp::registerAll(_factory, _action_factory, _syntax); } FluidPropertiesApp::~FluidPropertiesApp() {} void FluidPropertiesApp::registerApps() { registerApp(FluidPropertiesApp); } static void associateSyntaxInner(Syntax & syntax, ActionFactory & /*action_factory*/) { registerSyntaxTask( "AddFluidPropertiesAction", "Modules/FluidProperties/*", "add_fluid_properties"); registerMooseObjectTask("add_fluid_properties", FluidProperties, false); registerMooseObjectTask("add_fp_output", Output, false); syntax.addDependency("add_fluid_properties", "init_displaced_problem"); syntax.addDependency("add_aux_variable", "add_fluid_properties"); syntax.addDependency("add_variable", "add_fluid_properties"); syntax.addDependency("add_elemental_field_variable", "add_fluid_properties"); syntax.addDependency("add_external_aux_variables", "add_fluid_properties"); syntax.addDependency("add_fp_output", "add_output"); syntax.addDependency("add_postprocessor", "add_fp_output"); syntax.registerActionSyntax("AddFluidPropertiesInterrogatorAction", "FluidPropertiesInterrogator"); } void FluidPropertiesApp::registerAll(Factory & f, ActionFactory & af, Syntax & s) { Registry::registerObjectsTo(f, {"FluidPropertiesApp"}); Registry::registerActionsTo(af, {"FluidPropertiesApp"}); associateSyntaxInner(s, af); } void FluidPropertiesApp::registerObjects(Factory & factory) { mooseDeprecated("use registerAll instead of registerObjects"); Registry::registerObjectsTo(factory, {"FluidPropertiesApp"}); } void FluidPropertiesApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory) { mooseDeprecated("use registerAll instead of associateSyntax"); Registry::registerActionsTo(action_factory, {"FluidPropertiesApp"}); associateSyntaxInner(syntax, action_factory); } void FluidPropertiesApp::registerExecFlags(Factory & /*factory*/) { mooseDeprecated("use registerAll instead of registerExecFlags"); } extern "C" void FluidPropertiesApp__registerAll(Factory & f, ActionFactory & af, Syntax & s) { FluidPropertiesApp::registerAll(f, af, s); } extern "C" void FluidPropertiesApp__registerApps() { FluidPropertiesApp::registerApps(); }
Make sure that we have same task ordering as prior in FP
Make sure that we have same task ordering as prior in FP
C++
lgpl-2.1
milljm/moose,dschwen/moose,sapitts/moose,sapitts/moose,dschwen/moose,harterj/moose,andrsd/moose,laagesen/moose,harterj/moose,laagesen/moose,idaholab/moose,laagesen/moose,andrsd/moose,lindsayad/moose,dschwen/moose,idaholab/moose,laagesen/moose,laagesen/moose,lindsayad/moose,milljm/moose,lindsayad/moose,dschwen/moose,idaholab/moose,milljm/moose,dschwen/moose,idaholab/moose,harterj/moose,andrsd/moose,milljm/moose,harterj/moose,idaholab/moose,andrsd/moose,andrsd/moose,lindsayad/moose,milljm/moose,sapitts/moose,sapitts/moose,sapitts/moose,harterj/moose,lindsayad/moose
f09524fc76e81f7cadacf9f0736493f9ac97cb8f
src/runner/console.cpp
src/runner/console.cpp
#include "console.h" #include <humblelogging/api.h> #include <iomanip> #include <boost/thread/lock_guard.hpp> #include <boost/thread/shared_lock_guard.hpp> #include <annis/util/helper.h> HUMBLE_LOGGER(logger, "default"); using namespace annis; Console::Console() : dbCache(1073741824l*8l), db(dbCache.get(currentDBPath.string(), true)) { currentDBPath = boost::filesystem::unique_path( boost::filesystem::temp_directory_path().string() + "/annis-temporary-workspace-%%%%-%%%%-%%%%-%%%%"); HL_INFO(logger, "Using " + currentDBPath.string() + " as temporary path"); unsigned int numOfCPUs = std::thread::hardware_concurrency(); if(numOfCPUs >= 4) { config.threadPool = std::make_shared<ThreadPool>(numOfCPUs-1); config.numOfBackgroundTasks = numOfCPUs-1; } } bool Console::execute(const std::string &cmd, const std::vector<std::string> &args) { try { if (cmd == "import") { import(args); } else if(cmd == "save") { save(args); } else if(cmd == "load") { load(args); } else if(cmd == "info") { info(); } else if(cmd == "optimize") { optimize(); } else if(cmd == "count") { count(args); } else if(cmd == "find") { find(args); } else if(cmd == "update_statistics") { updateStatistics(); } else if(cmd == "guess") { guess(args); } else if(cmd == "guess_regex") { guessRegex(args); } else if(cmd == "plan") { plan(args); } else if(cmd == "memory") { memory(args); } else if (cmd == "quit" || cmd == "exit") { return true; } else { std::cout << "Unknown command \"" << cmd << "\"" << std::endl; } } catch(std::string ex) { std::cerr << "Exception: " << ex << std::endl; } return false; } void Console::import(const std::vector<std::string> &args) { if(db) { if(args.size() > 0) { std::cout << "Import relANNIS from " << args[0] << std::endl; db->loadRelANNIS(args[0]); if(args.size() > 1) { // directly save the imported corpus to directory HL_INFO(logger, "saving to " + args[1]); db->save(args[1]); } } else { std::cout << "You have to give a path as argument" << std::endl; } } } void Console::save(const std::vector<std::string> &args) { if(db) { if(args.size() > 0) { std::cout << "Save to " << args[0] << std::endl; auto startTime = annis::Helper::getSystemTimeInMilliSeconds(); db->save(args[0]); auto endTime = annis::Helper::getSystemTimeInMilliSeconds(); std::cout << "Saved in " << (endTime - startTime) << " ms" << std::endl; } else { std::cout << "You have to give a path as argument" << std::endl; } } } void Console::load(const std::vector<std::string> &args) { if(args.size() > 0) { std::cout << "Loading from " << args[0] << std::endl; auto startTime = annis::Helper::getSystemTimeInMilliSeconds(); db = dbCache.get(args[0], args.size() > 1 && args[1] == "preload"); auto endTime = annis::Helper::getSystemTimeInMilliSeconds(); std::cout << "Loaded in " << (endTime - startTime) << " ms" << std::endl; } else { std::cout << "You have to give a path as argument" << std::endl; } } void Console::info() { if(db) { std::cout << db->info() << std::endl; } } void Console::optimize() { if(db) { std::cout << "Optimizing..." << std::endl; db->optimizeAll(); std::cout << "Finished." << std::endl; } } void Console::count(const std::vector<std::string> &args) { if(db) { if(args.size() > 0) { std::string json = boost::join(args, " "); std::cout << "Counting..." << std::endl; std::stringstream ss; ss << json; try { std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss, config); int counter =0; auto startTime = annis::Helper::getSystemTimeInMilliSeconds(); while(q->next()) { counter++; } auto endTime = annis::Helper::getSystemTimeInMilliSeconds(); std::cout << counter << " matches in " << (endTime - startTime) << " ms" << std::endl; } catch(Json::RuntimeError err) { std::cout << "JSON error: " << err.what() << std::endl; } } else { std::cout << "you need to give the query JSON as argument" << std::endl; } } } void Console::find(const std::vector<std::string> &args) { if(db) { if(args.size() > 0) { std::string json = boost::join(args, " "); std::cout << "Finding..." << std::endl; std::stringstream ss; ss << json; try { std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss, config); int counter =0; while(q->next()) { std::vector<annis::Match> m = q->getCurrent(); for(size_t i = 0; i < m.size(); i++) { const auto& n = m[i]; std::cout << db->getNodeDebugName(n.node); if(n.anno.ns != 0 && n.anno.name != 0) { std::cout << " " << db->strings.str(n.anno.ns) << "::" << db->strings.str(n.anno.name); } if(i < m.size()-1) { std::cout << ", "; } } std::cout << std::endl; counter++; } std::cout << counter << " matches" << std::endl; } catch(Json::RuntimeError err) { std::cout << "JSON error: " << err.what() << std::endl; } } else { std::cout << "you need to give the query JSON as argument" << std::endl; } } } void Console::updateStatistics() { if(db) { std::cout << "Updating statistics..."; db->nodeAnnos.calculateStatistics(db->strings); std::cout << " Done" << std::endl; } } void Console::guess(const std::vector<std::string> &args) { if(db) { if(args.size() == 3) { std::cout << "Guessed maximum count: " << db->nodeAnnos.guessMaxCount(db->strings, args[0], args[1], args[2]) << std::endl; } else if(args.size() == 2) { std::cout << "Guessed maximum count: " << db->nodeAnnos.guessMaxCount(db->strings, args[0], args[1]) << std::endl; } else { std::cout << "Must provide at two (name and value) or three (namespace name value) arguments" << std::endl; } } } void Console::guessRegex(const std::vector<std::string> &args) { if(db) { if(args.size() == 3) { std::cout << "Guessed maximum count: " << db->nodeAnnos.guessMaxCountRegex(db->strings, args[0], args[1], args[2]) << std::endl; } else if(args.size() == 2) { std::cout << "Guessed maximum count: " << db->nodeAnnos.guessMaxCountRegex(db->strings, args[0], args[1]) << std::endl; } else { std::cout << "Must provide at two (name and regex) or three (namespace name regex) arguments" << std::endl; } } } void Console::plan(const std::vector<std::string> &args) { if(db) { if(args.size() > 0) { std::string json = boost::join(args, " "); std::cout << "Planning..." << std::endl; std::stringstream ss; ss << json; try { std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss, config); std::cout << q->getBestPlan()->debugString() << std::endl; } catch(Json::RuntimeError err) { std::cout << "JSON error: " << err.what() << std::endl; } } else { std::cout << "you need to give the query JSON as argument" << std::endl; } } } void Console::memory(const std::vector<std::string> args) { if(args.empty()) { auto corpusSizes = dbCache.estimateCorpusSizes(); for(auto it = corpusSizes.begin(); it != corpusSizes.end(); it++) { if(!it->first.corpusPath.empty()) { const DBCache::CorpusSize& size = it->second; std::cout << it->first.corpusPath << ": " << Helper::inMB(size.estimated) << " MB (estimated) " << Helper::inMB(size.measured) << " MB (measured)" << std::endl; } } DBCache::CorpusSize total = dbCache.calculateTotalSize(); std::cout << "Used total memory (estimated): " << Helper::inMB(total.estimated) << " MB" << std::endl; std::cout << "Used total memory (measured): " << Helper::inMB(total.measured) << " MB" << std::endl; } else if(args[0] == "clear") { dbCache.releaseAll(); std::cout << "Cleared cache" << std::endl; } }
#include "console.h" #include <humblelogging/api.h> #include <iomanip> #include <boost/thread/lock_guard.hpp> #include <boost/thread/shared_lock_guard.hpp> #include <annis/util/helper.h> HUMBLE_LOGGER(logger, "default"); using namespace annis; Console::Console() : dbCache(1073741824l*8l), db(dbCache.get(currentDBPath.string(), true)) { currentDBPath = boost::filesystem::unique_path( boost::filesystem::temp_directory_path().string() + "/annis-temporary-workspace-%%%%-%%%%-%%%%-%%%%"); HL_INFO(logger, "Using " + currentDBPath.string() + " as temporary path"); unsigned int numOfCPUs = std::thread::hardware_concurrency(); if(numOfCPUs >= 4) { config.threadPool = std::make_shared<ThreadPool>(numOfCPUs); config.numOfBackgroundTasks = numOfCPUs; } } bool Console::execute(const std::string &cmd, const std::vector<std::string> &args) { try { if (cmd == "import") { import(args); } else if(cmd == "save") { save(args); } else if(cmd == "load") { load(args); } else if(cmd == "info") { info(); } else if(cmd == "optimize") { optimize(); } else if(cmd == "count") { count(args); } else if(cmd == "find") { find(args); } else if(cmd == "update_statistics") { updateStatistics(); } else if(cmd == "guess") { guess(args); } else if(cmd == "guess_regex") { guessRegex(args); } else if(cmd == "plan") { plan(args); } else if(cmd == "memory") { memory(args); } else if (cmd == "quit" || cmd == "exit") { return true; } else { std::cout << "Unknown command \"" << cmd << "\"" << std::endl; } } catch(std::string ex) { std::cerr << "Exception: " << ex << std::endl; } return false; } void Console::import(const std::vector<std::string> &args) { if(db) { if(args.size() > 0) { std::cout << "Import relANNIS from " << args[0] << std::endl; db->loadRelANNIS(args[0]); if(args.size() > 1) { // directly save the imported corpus to directory HL_INFO(logger, "saving to " + args[1]); db->save(args[1]); } } else { std::cout << "You have to give a path as argument" << std::endl; } } } void Console::save(const std::vector<std::string> &args) { if(db) { if(args.size() > 0) { std::cout << "Save to " << args[0] << std::endl; auto startTime = annis::Helper::getSystemTimeInMilliSeconds(); db->save(args[0]); auto endTime = annis::Helper::getSystemTimeInMilliSeconds(); std::cout << "Saved in " << (endTime - startTime) << " ms" << std::endl; } else { std::cout << "You have to give a path as argument" << std::endl; } } } void Console::load(const std::vector<std::string> &args) { if(args.size() > 0) { std::cout << "Loading from " << args[0] << std::endl; auto startTime = annis::Helper::getSystemTimeInMilliSeconds(); db = dbCache.get(args[0], args.size() > 1 && args[1] == "preload"); auto endTime = annis::Helper::getSystemTimeInMilliSeconds(); std::cout << "Loaded in " << (endTime - startTime) << " ms" << std::endl; } else { std::cout << "You have to give a path as argument" << std::endl; } } void Console::info() { if(db) { std::cout << db->info() << std::endl; } } void Console::optimize() { if(db) { std::cout << "Optimizing..." << std::endl; db->optimizeAll(); std::cout << "Finished." << std::endl; } } void Console::count(const std::vector<std::string> &args) { if(db) { if(args.size() > 0) { std::string json = boost::join(args, " "); std::cout << "Counting..." << std::endl; std::stringstream ss; ss << json; try { std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss, config); int counter =0; auto startTime = annis::Helper::getSystemTimeInMilliSeconds(); while(q->next()) { counter++; } auto endTime = annis::Helper::getSystemTimeInMilliSeconds(); std::cout << counter << " matches in " << (endTime - startTime) << " ms" << std::endl; } catch(Json::RuntimeError err) { std::cout << "JSON error: " << err.what() << std::endl; } } else { std::cout << "you need to give the query JSON as argument" << std::endl; } } } void Console::find(const std::vector<std::string> &args) { if(db) { if(args.size() > 0) { std::string json = boost::join(args, " "); std::cout << "Finding..." << std::endl; std::stringstream ss; ss << json; try { std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss, config); int counter =0; while(q->next()) { std::vector<annis::Match> m = q->getCurrent(); for(size_t i = 0; i < m.size(); i++) { const auto& n = m[i]; std::cout << db->getNodeDebugName(n.node); if(n.anno.ns != 0 && n.anno.name != 0) { std::cout << " " << db->strings.str(n.anno.ns) << "::" << db->strings.str(n.anno.name); } if(i < m.size()-1) { std::cout << ", "; } } std::cout << std::endl; counter++; } std::cout << counter << " matches" << std::endl; } catch(Json::RuntimeError err) { std::cout << "JSON error: " << err.what() << std::endl; } } else { std::cout << "you need to give the query JSON as argument" << std::endl; } } } void Console::updateStatistics() { if(db) { std::cout << "Updating statistics..."; db->nodeAnnos.calculateStatistics(db->strings); std::cout << " Done" << std::endl; } } void Console::guess(const std::vector<std::string> &args) { if(db) { if(args.size() == 3) { std::cout << "Guessed maximum count: " << db->nodeAnnos.guessMaxCount(db->strings, args[0], args[1], args[2]) << std::endl; } else if(args.size() == 2) { std::cout << "Guessed maximum count: " << db->nodeAnnos.guessMaxCount(db->strings, args[0], args[1]) << std::endl; } else { std::cout << "Must provide at two (name and value) or three (namespace name value) arguments" << std::endl; } } } void Console::guessRegex(const std::vector<std::string> &args) { if(db) { if(args.size() == 3) { std::cout << "Guessed maximum count: " << db->nodeAnnos.guessMaxCountRegex(db->strings, args[0], args[1], args[2]) << std::endl; } else if(args.size() == 2) { std::cout << "Guessed maximum count: " << db->nodeAnnos.guessMaxCountRegex(db->strings, args[0], args[1]) << std::endl; } else { std::cout << "Must provide at two (name and regex) or three (namespace name regex) arguments" << std::endl; } } } void Console::plan(const std::vector<std::string> &args) { if(db) { if(args.size() > 0) { std::string json = boost::join(args, " "); std::cout << "Planning..." << std::endl; std::stringstream ss; ss << json; try { std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss, config); std::cout << q->getBestPlan()->debugString() << std::endl; } catch(Json::RuntimeError err) { std::cout << "JSON error: " << err.what() << std::endl; } } else { std::cout << "you need to give the query JSON as argument" << std::endl; } } } void Console::memory(const std::vector<std::string> args) { if(args.empty()) { auto corpusSizes = dbCache.estimateCorpusSizes(); for(auto it = corpusSizes.begin(); it != corpusSizes.end(); it++) { if(!it->first.corpusPath.empty()) { const DBCache::CorpusSize& size = it->second; std::cout << it->first.corpusPath << ": " << Helper::inMB(size.estimated) << " MB (estimated) " << Helper::inMB(size.measured) << " MB (measured)" << std::endl; } } DBCache::CorpusSize total = dbCache.calculateTotalSize(); std::cout << "Used total memory (estimated): " << Helper::inMB(total.estimated) << " MB" << std::endl; std::cout << "Used total memory (measured): " << Helper::inMB(total.measured) << " MB" << std::endl; } else if(args[0] == "clear") { dbCache.releaseAll(); std::cout << "Cleared cache" << std::endl; } }
Use the number of all CPUs as number of background tasks in console.
Use the number of all CPUs as number of background tasks in console.
C++
apache-2.0
thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS,thomaskrause/graphANNIS
d49f2131b7d0da9fd398755513d257f561a5ad46
src/server/listener.cc
src/server/listener.cc
/* listener.cc Mathieu Stefani, 12 August 2015 */ #include <pistache/listener.h> #include <pistache/peer.h> #include <pistache/common.h> #include <pistache/os.h> #include <pistache/transport.h> #include <pistache/errors.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <sys/types.h> #include <netdb.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <chrono> #include <memory> #include <vector> #include <cerrno> #include <signal.h> #ifdef PISTACHE_USE_SSL #include <openssl/ssl.h> #include <openssl/err.h> #endif /* PISTACHE_USE_SSL */ namespace Pistache { namespace Tcp { void setSocketOptions(Fd fd, Flags<Options> options) { if (options.hasFlag(Options::ReuseAddr)) { int one = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof (one))); } if (options.hasFlag(Options::Linger)) { struct linger opt; opt.l_onoff = 1; opt.l_linger = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_LINGER, &opt, sizeof (opt))); } if (options.hasFlag(Options::FastOpen)) { int hint = 5; TRY(::setsockopt(fd, SOL_TCP, TCP_FASTOPEN, &hint, sizeof (hint))); } if (options.hasFlag(Options::NoDelay)) { int one = 1; TRY(::setsockopt(fd, SOL_TCP, TCP_NODELAY, &one, sizeof (one))); } } Listener::Listener() : addr_() , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , workersName_() , reactor_() , transportKey() , useSSL_(false) { } Listener::Listener(const Address& address) : addr_(address) , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , workersName_() , reactor_() , transportKey() , useSSL_(false) { } Listener::~Listener() { if (isBound()) shutdown(); if (acceptThread.joinable()) acceptThread.join(); #ifdef PISTACHE_USE_SSL if (this->useSSL_) { SSL_CTX_free((SSL_CTX *)this->ssl_ctx_); EVP_cleanup(); } #endif /* PISTACHE_USE_SSL */ } void Listener::init( size_t workers, Flags<Options> options, const char * workersName, int backlog) { if (workers > hardware_concurrency()) { // Log::warning() << "More workers than available cores" } options_ = options; backlog_ = backlog; useSSL_ = false; workers_ = workers; strcpy(workersName_, workersName); } void Listener::setHandler(const std::shared_ptr<Handler>& handler) { handler_ = handler; } void Listener::pinWorker(size_t worker, const CpuSet& set) { UNUSED(worker) UNUSED(set) #if 0 if (ioGroup.empty()) { throw std::domain_error("Invalid operation, did you call init() before ?"); } if (worker > ioGroup.size()) { throw std::invalid_argument("Trying to pin invalid worker"); } auto &wrk = ioGroup[worker]; wrk->pin(set); #endif } void Listener::bind() { bind(addr_); } void Listener::bind(const Address& address) { if (!handler_) throw std::runtime_error("Call setHandler before calling bind()"); addr_ = address; struct addrinfo hints; hints.ai_family = address.family(); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; hints.ai_protocol = 0; const auto& host = addr_.host(); const auto& port = addr_.port().toString(); AddrInfo addr_info; TRY(addr_info.invoke(host.c_str(), port.c_str(), &hints)); int fd = -1; const addrinfo * addr = nullptr; for (addr = addr_info.get_info_ptr(); addr; addr = addr->ai_next) { fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (fd < 0) continue; setSocketOptions(fd, options_); if (::bind(fd, addr->ai_addr, addr->ai_addrlen) < 0) { close(fd); continue; } TRY(::listen(fd, backlog_)); break; } // At this point, it is still possible that we couldn't bind any socket. If it is the case, the previous // loop would have exited naturally and addr will be null. if (addr == nullptr) { throw std::runtime_error(strerror(errno)); } make_non_blocking(fd); poller.addFd(fd, Polling::NotifyOn::Read, Polling::Tag(fd)); listen_fd = fd; auto transport = std::make_shared<Transport>(handler_); reactor_.init(Aio::AsyncContext(workers_, workersName_)); transportKey = reactor_.addHandler(transport); } bool Listener::isBound() const { return listen_fd != -1; } // Return actual TCP port Listener is on, or 0 on error / no port. // Notes: // 1) Default constructor for 'Port()' sets value to 0. // 2) Socket is created inside 'Listener::run()', which is called from // 'Endpoint::serve()' and 'Endpoint::serveThreaded()'. So getting the // port is only useful if you attempt to do so from a _different_ thread // than the one running 'Listener::run()'. So for a traditional single- // threaded program this method is of little value. Port Listener::getPort() const { if (listen_fd == -1) { return Port(); } struct sockaddr_in sock_addr = {0}; socklen_t addrlen = sizeof(sock_addr); auto sock_addr_alias = reinterpret_cast<struct sockaddr*>(&sock_addr); if (-1 == getsockname(listen_fd, sock_addr_alias, &addrlen)) { return Port(); } return Port(ntohs(sock_addr.sin_port)); } void Listener::run() { shutdownFd.bind(poller); reactor_.run(); for (;;) { std::vector<Polling::Event> events; int ready_fds = poller.poll(events); if (ready_fds == -1) { throw Error::system("Polling"); } for (const auto& event: events) { if (event.tag == shutdownFd.tag()) return; if (event.flags.hasFlag(Polling::NotifyOn::Read)) { auto fd = event.tag.value(); if (static_cast<ssize_t>(fd) == listen_fd) { try { handleNewConnection(); } catch (SocketError& ex) { std::cerr << "Server: " << ex.what() << std::endl; } catch (ServerError& ex) { std::cerr << "Server: " << ex.what() << std::endl; throw; } } } } } } void Listener::runThreaded() { acceptThread = std::thread([=]() { this->run(); }); } void Listener::shutdown() { if (shutdownFd.isBound()) shutdownFd.notify(); reactor_.shutdown(); } Async::Promise<Listener::Load> Listener::requestLoad(const Listener::Load& old) { auto handlers = reactor_.handlers(transportKey); std::vector<Async::Promise<rusage>> loads; for (const auto& handler: handlers) { auto transport = std::static_pointer_cast<Transport>(handler); loads.push_back(transport->load()); } return Async::whenAll(std::begin(loads), std::end(loads)).then([=](const std::vector<rusage>& usages) { Load res; res.raw = usages; if (old.raw.empty()) { res.global = 0.0; for (size_t i = 0; i < handlers.size(); ++i) res.workers.push_back(0.0); } else { auto totalElapsed = [](rusage usage) { return (usage.ru_stime.tv_sec * 1e6 + usage.ru_stime.tv_usec) + (usage.ru_utime.tv_sec * 1e6 + usage.ru_utime.tv_usec); }; auto now = std::chrono::system_clock::now(); auto diff = now - old.tick; auto tick = std::chrono::duration_cast<std::chrono::microseconds>(diff); res.tick = now; for (size_t i = 0; i < usages.size(); ++i) { auto last = old.raw[i]; const auto& usage = usages[i]; auto nowElapsed = totalElapsed(usage); auto timeElapsed = nowElapsed - totalElapsed(last); auto loadPct = (timeElapsed * 100.0) / tick.count(); res.workers.push_back(loadPct); res.global += loadPct; } res.global /= usages.size(); } return res; }, Async::Throw); } Address Listener::address() const { return addr_; } Options Listener::options() const { return options_; } void Listener::handleNewConnection() { struct sockaddr_in peer_addr; int client_fd = acceptConnection(peer_addr); #ifdef PISTACHE_USE_SSL SSL *ssl = nullptr; if (this->useSSL_) { ssl = SSL_new((SSL_CTX *)this->ssl_ctx_); if (ssl == NULL) throw std::runtime_error("Cannot create SSL connection"); SSL_set_fd(ssl, client_fd); SSL_set_accept_state(ssl); if (SSL_accept(ssl) <= 0) { ERR_print_errors_fp(stderr); SSL_free(ssl); close(client_fd); return ; } } #endif /* PISTACHE_USE_SSL */ make_non_blocking(client_fd); auto peer = std::make_shared<Peer>(Address::fromUnix((struct sockaddr *)&peer_addr)); peer->associateFd(client_fd); #ifdef PISTACHE_USE_SSL if (this->useSSL_) peer->associateSSL(ssl); #endif /* PISTACHE_USE_SSL */ dispatchPeer(peer); } int Listener::acceptConnection(struct sockaddr_in& peer_addr) const { socklen_t peer_addr_len = sizeof(peer_addr); int client_fd = ::accept(listen_fd, (struct sockaddr *)&peer_addr, &peer_addr_len); if (client_fd < 0) { if (errno == EBADF || errno == ENOTSOCK) throw ServerError(strerror(errno)); else throw SocketError(strerror(errno)); } return client_fd; } void Listener::dispatchPeer(const std::shared_ptr<Peer>& peer) { auto handlers = reactor_.handlers(transportKey); auto idx = peer->fd() % handlers.size(); auto transport = std::static_pointer_cast<Transport>(handlers[idx]); transport->handleNewPeer(peer); } #ifdef PISTACHE_USE_SSL static SSL_CTX *ssl_create_context(const std::string &cert, const std::string &key, bool use_compression) { const SSL_METHOD *method; SSL_CTX *ctx; method = SSLv23_server_method(); ctx = SSL_CTX_new(method); if (ctx == NULL) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot setup SSL context"); } if (!use_compression) { /* Disable compression to prevent BREACH and CRIME vulnerabilities. */ if (!SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION)) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot disable compression"); } } /* Function introduced in 1.0.2 */ #if OPENSSL_VERSION_NUMBER >= 0x10002000L SSL_CTX_set_ecdh_auto(ctx, 1); #endif /* OPENSSL_VERSION_NUMBER */ if (SSL_CTX_use_certificate_file(ctx, cert.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL certificate"); } if (SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL private key"); } if (!SSL_CTX_check_private_key(ctx)) { ERR_print_errors_fp(stderr); throw std::runtime_error("Private key does not match public key in the certificate"); } return ctx; } void Listener::setupSSLAuth(const std::string &ca_file, const std::string &ca_path, int (*cb)(int, void *) = NULL) { const char *__ca_file = NULL; const char *__ca_path = NULL; if (this->ssl_ctx_ == NULL) throw std::runtime_error("SSL Context is not initialized"); if (!ca_file.empty()) __ca_file = ca_file.c_str(); if (!ca_path.empty()) __ca_path = ca_path.c_str(); if (SSL_CTX_load_verify_locations((SSL_CTX *)this->ssl_ctx_, __ca_file, __ca_path) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot verify SSL locations"); } SSL_CTX_set_verify((SSL_CTX *)this->ssl_ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, /* Callback type did change in 1.0.1 */ #if OPENSSL_VERSION_NUMBER < 0x10100000L (int (*)(int, X509_STORE_CTX *))cb #else (SSL_verify_cb)cb #endif /* OPENSSL_VERSION_NUMBER */ ); } void Listener::setupSSL(const std::string &cert_path, const std::string &key_path, bool use_compression) { SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); this->ssl_ctx_ = ssl_create_context(cert_path, key_path, use_compression); this->useSSL_ = true; } #endif /* PISTACHE_USE_SSL */ } // namespace Tcp } // namespace Pistache
/* listener.cc Mathieu Stefani, 12 August 2015 */ #include <pistache/listener.h> #include <pistache/peer.h> #include <pistache/common.h> #include <pistache/os.h> #include <pistache/transport.h> #include <pistache/errors.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <sys/types.h> #include <netdb.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <chrono> #include <memory> #include <vector> #include <cerrno> #include <signal.h> #ifdef PISTACHE_USE_SSL #include <openssl/ssl.h> #include <openssl/err.h> #endif /* PISTACHE_USE_SSL */ namespace Pistache { namespace Tcp { void setSocketOptions(Fd fd, Flags<Options> options) { if (options.hasFlag(Options::ReuseAddr)) { int one = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof (one))); } if (options.hasFlag(Options::Linger)) { struct linger opt; opt.l_onoff = 1; opt.l_linger = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_LINGER, &opt, sizeof (opt))); } if (options.hasFlag(Options::FastOpen)) { int hint = 5; TRY(::setsockopt(fd, SOL_TCP, TCP_FASTOPEN, &hint, sizeof (hint))); } if (options.hasFlag(Options::NoDelay)) { int one = 1; TRY(::setsockopt(fd, SOL_TCP, TCP_NODELAY, &one, sizeof (one))); } } Listener::Listener() : addr_() , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , workersName_() , reactor_() , transportKey() , useSSL_(false) { } Listener::Listener(const Address& address) : addr_(address) , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , workersName_() , reactor_() , transportKey() , useSSL_(false) { } Listener::~Listener() { if (isBound()) shutdown(); if (acceptThread.joinable()) acceptThread.join(); #ifdef PISTACHE_USE_SSL if (this->useSSL_) { SSL_CTX_free((SSL_CTX *)this->ssl_ctx_); EVP_cleanup(); } #endif /* PISTACHE_USE_SSL */ } void Listener::init( size_t workers, Flags<Options> options, std::string workersName, int backlog) { if (workers > hardware_concurrency()) { // Log::warning() << "More workers than available cores" } options_ = options; backlog_ = backlog; useSSL_ = false; workers_ = workers; workersName_ = workersName; } void Listener::setHandler(const std::shared_ptr<Handler>& handler) { handler_ = handler; } void Listener::pinWorker(size_t worker, const CpuSet& set) { UNUSED(worker) UNUSED(set) #if 0 if (ioGroup.empty()) { throw std::domain_error("Invalid operation, did you call init() before ?"); } if (worker > ioGroup.size()) { throw std::invalid_argument("Trying to pin invalid worker"); } auto &wrk = ioGroup[worker]; wrk->pin(set); #endif } void Listener::bind() { bind(addr_); } void Listener::bind(const Address& address) { if (!handler_) throw std::runtime_error("Call setHandler before calling bind()"); addr_ = address; struct addrinfo hints; hints.ai_family = address.family(); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; hints.ai_protocol = 0; const auto& host = addr_.host(); const auto& port = addr_.port().toString(); AddrInfo addr_info; TRY(addr_info.invoke(host.c_str(), port.c_str(), &hints)); int fd = -1; const addrinfo * addr = nullptr; for (addr = addr_info.get_info_ptr(); addr; addr = addr->ai_next) { fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (fd < 0) continue; setSocketOptions(fd, options_); if (::bind(fd, addr->ai_addr, addr->ai_addrlen) < 0) { close(fd); continue; } TRY(::listen(fd, backlog_)); break; } // At this point, it is still possible that we couldn't bind any socket. If it is the case, the previous // loop would have exited naturally and addr will be null. if (addr == nullptr) { throw std::runtime_error(strerror(errno)); } make_non_blocking(fd); poller.addFd(fd, Polling::NotifyOn::Read, Polling::Tag(fd)); listen_fd = fd; auto transport = std::make_shared<Transport>(handler_); reactor_.init(Aio::AsyncContext(workers_, workersName_)); transportKey = reactor_.addHandler(transport); } bool Listener::isBound() const { return listen_fd != -1; } // Return actual TCP port Listener is on, or 0 on error / no port. // Notes: // 1) Default constructor for 'Port()' sets value to 0. // 2) Socket is created inside 'Listener::run()', which is called from // 'Endpoint::serve()' and 'Endpoint::serveThreaded()'. So getting the // port is only useful if you attempt to do so from a _different_ thread // than the one running 'Listener::run()'. So for a traditional single- // threaded program this method is of little value. Port Listener::getPort() const { if (listen_fd == -1) { return Port(); } struct sockaddr_in sock_addr = {0}; socklen_t addrlen = sizeof(sock_addr); auto sock_addr_alias = reinterpret_cast<struct sockaddr*>(&sock_addr); if (-1 == getsockname(listen_fd, sock_addr_alias, &addrlen)) { return Port(); } return Port(ntohs(sock_addr.sin_port)); } void Listener::run() { shutdownFd.bind(poller); reactor_.run(); for (;;) { std::vector<Polling::Event> events; int ready_fds = poller.poll(events); if (ready_fds == -1) { throw Error::system("Polling"); } for (const auto& event: events) { if (event.tag == shutdownFd.tag()) return; if (event.flags.hasFlag(Polling::NotifyOn::Read)) { auto fd = event.tag.value(); if (static_cast<ssize_t>(fd) == listen_fd) { try { handleNewConnection(); } catch (SocketError& ex) { std::cerr << "Server: " << ex.what() << std::endl; } catch (ServerError& ex) { std::cerr << "Server: " << ex.what() << std::endl; throw; } } } } } } void Listener::runThreaded() { acceptThread = std::thread([=]() { this->run(); }); } void Listener::shutdown() { if (shutdownFd.isBound()) shutdownFd.notify(); reactor_.shutdown(); } Async::Promise<Listener::Load> Listener::requestLoad(const Listener::Load& old) { auto handlers = reactor_.handlers(transportKey); std::vector<Async::Promise<rusage>> loads; for (const auto& handler: handlers) { auto transport = std::static_pointer_cast<Transport>(handler); loads.push_back(transport->load()); } return Async::whenAll(std::begin(loads), std::end(loads)).then([=](const std::vector<rusage>& usages) { Load res; res.raw = usages; if (old.raw.empty()) { res.global = 0.0; for (size_t i = 0; i < handlers.size(); ++i) res.workers.push_back(0.0); } else { auto totalElapsed = [](rusage usage) { return (usage.ru_stime.tv_sec * 1e6 + usage.ru_stime.tv_usec) + (usage.ru_utime.tv_sec * 1e6 + usage.ru_utime.tv_usec); }; auto now = std::chrono::system_clock::now(); auto diff = now - old.tick; auto tick = std::chrono::duration_cast<std::chrono::microseconds>(diff); res.tick = now; for (size_t i = 0; i < usages.size(); ++i) { auto last = old.raw[i]; const auto& usage = usages[i]; auto nowElapsed = totalElapsed(usage); auto timeElapsed = nowElapsed - totalElapsed(last); auto loadPct = (timeElapsed * 100.0) / tick.count(); res.workers.push_back(loadPct); res.global += loadPct; } res.global /= usages.size(); } return res; }, Async::Throw); } Address Listener::address() const { return addr_; } Options Listener::options() const { return options_; } void Listener::handleNewConnection() { struct sockaddr_in peer_addr; int client_fd = acceptConnection(peer_addr); #ifdef PISTACHE_USE_SSL SSL *ssl = nullptr; if (this->useSSL_) { ssl = SSL_new((SSL_CTX *)this->ssl_ctx_); if (ssl == NULL) throw std::runtime_error("Cannot create SSL connection"); SSL_set_fd(ssl, client_fd); SSL_set_accept_state(ssl); if (SSL_accept(ssl) <= 0) { ERR_print_errors_fp(stderr); SSL_free(ssl); close(client_fd); return ; } } #endif /* PISTACHE_USE_SSL */ make_non_blocking(client_fd); auto peer = std::make_shared<Peer>(Address::fromUnix((struct sockaddr *)&peer_addr)); peer->associateFd(client_fd); #ifdef PISTACHE_USE_SSL if (this->useSSL_) peer->associateSSL(ssl); #endif /* PISTACHE_USE_SSL */ dispatchPeer(peer); } int Listener::acceptConnection(struct sockaddr_in& peer_addr) const { socklen_t peer_addr_len = sizeof(peer_addr); int client_fd = ::accept(listen_fd, (struct sockaddr *)&peer_addr, &peer_addr_len); if (client_fd < 0) { if (errno == EBADF || errno == ENOTSOCK) throw ServerError(strerror(errno)); else throw SocketError(strerror(errno)); } return client_fd; } void Listener::dispatchPeer(const std::shared_ptr<Peer>& peer) { auto handlers = reactor_.handlers(transportKey); auto idx = peer->fd() % handlers.size(); auto transport = std::static_pointer_cast<Transport>(handlers[idx]); transport->handleNewPeer(peer); } #ifdef PISTACHE_USE_SSL static SSL_CTX *ssl_create_context(const std::string &cert, const std::string &key, bool use_compression) { const SSL_METHOD *method; SSL_CTX *ctx; method = SSLv23_server_method(); ctx = SSL_CTX_new(method); if (ctx == NULL) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot setup SSL context"); } if (!use_compression) { /* Disable compression to prevent BREACH and CRIME vulnerabilities. */ if (!SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION)) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot disable compression"); } } /* Function introduced in 1.0.2 */ #if OPENSSL_VERSION_NUMBER >= 0x10002000L SSL_CTX_set_ecdh_auto(ctx, 1); #endif /* OPENSSL_VERSION_NUMBER */ if (SSL_CTX_use_certificate_file(ctx, cert.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL certificate"); } if (SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot load SSL private key"); } if (!SSL_CTX_check_private_key(ctx)) { ERR_print_errors_fp(stderr); throw std::runtime_error("Private key does not match public key in the certificate"); } return ctx; } void Listener::setupSSLAuth(const std::string &ca_file, const std::string &ca_path, int (*cb)(int, void *) = NULL) { const char *__ca_file = NULL; const char *__ca_path = NULL; if (this->ssl_ctx_ == NULL) throw std::runtime_error("SSL Context is not initialized"); if (!ca_file.empty()) __ca_file = ca_file.c_str(); if (!ca_path.empty()) __ca_path = ca_path.c_str(); if (SSL_CTX_load_verify_locations((SSL_CTX *)this->ssl_ctx_, __ca_file, __ca_path) <= 0) { ERR_print_errors_fp(stderr); throw std::runtime_error("Cannot verify SSL locations"); } SSL_CTX_set_verify((SSL_CTX *)this->ssl_ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE, /* Callback type did change in 1.0.1 */ #if OPENSSL_VERSION_NUMBER < 0x10100000L (int (*)(int, X509_STORE_CTX *))cb #else (SSL_verify_cb)cb #endif /* OPENSSL_VERSION_NUMBER */ ); } void Listener::setupSSL(const std::string &cert_path, const std::string &key_path, bool use_compression) { SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); this->ssl_ctx_ = ssl_create_context(cert_path, key_path, use_compression); this->useSSL_ = true; } #endif /* PISTACHE_USE_SSL */ } // namespace Tcp } // namespace Pistache
Update listener.cc
Update listener.cc using std::string, fix code style
C++
apache-2.0
oktal/rest,oktal/pistache,oktal/pistache,oktal/rest,oktal/pistache,oktal/rest,oktal/rest,oktal/pistache,oktal/pistache
35413e27e7c9eaa46c1c2101c5750758a3592440
src/service_handler.cc
src/service_handler.cc
/* * Copyright (c) 2010, The Infrastructure Developers Group * All rights reserved. * * This file is subject to the New BSD License (see the LICENSE file). */ #include "service_handler.h" #include <sys/select.h> #include "loop.h" #include "process.h" #include "settings.h" #include "utils.h" #ifndef FD_COPY #define FD_COPY(f, t) memcpy(t, f, sizeof(*(f))) #endif namespace tyrion { ServiceHandler::ServiceHandler() : rfds_(), highest_fd_(0), list_(), polling_(0), loop_(NULL) { FD_ZERO(&rfds_); } void ServiceHandler::Request(Envelope* envelope) { Post(this, MSG_REQUEST, new ServiceHandlerData(envelope)); } void ServiceHandler::WakeTasks() { txmpp::Thread::Current()->Post(this); } void ServiceHandler::DoRequest(ServiceData* service) { Envelope* envelope = service->envelope(); bool issue = false; std::string config = "service:" + envelope->type(); std::string user = loop_->settings()->Get(config, "user"); bool user_lock = loop_->settings()->GetBool(config, "user_lock"); std::string group = loop_->settings()->Get(config, "group"); bool group_lock = loop_->settings()->GetBool(config, "group_lock"); int timeout = loop_->settings()->GetInt(config, "timeout"); bool timeout_lock = loop_->settings()->GetBool(config, "timeout_lock"); if (!issue && user_lock) { if (user.empty()) { envelope->append_error( CreateError("user.lock", "Unable to lock user because none set.")); issue = true; } } else if (!issue && !envelope->user().empty()) { user = envelope->user(); } if (!issue && group_lock) { if (group.empty()) { envelope->append_error( CreateError("group.lock", "Unable to lock group because none set.")); issue = true; } } else if (!issue && !envelope->group().empty()) group = envelope->group(); if (!issue && timeout_lock) { if (!timeout > 0) { envelope->append_error( CreateError("timeout.lock", "Unable to lock timeout because none set.")); issue = true; } } else { timeout = envelope->timeout(); } Process* process = new Process(envelope->Path(), false, timeout); service->set_process(process); if (!issue && !user.empty() && !process->set_user(user)) { envelope->append_error( CreateError("user.lookup", "Unable to find user '" + user + "'")); issue = true; } if (!issue && !group.empty() && !process->set_group(group)) { envelope->append_error( CreateError("group.lookup", "Unable to find group '" + group + "'")); issue = true; } if (!issue) { FD_SET(process->outfd[Process::Stdout][0], &rfds_); FD_SET(process->outfd[Process::Stderr][0], &rfds_); if (process->outfd[Process::Stdout][0] > highest_fd_) highest_fd_ = process->outfd[Process::Stdout][0]; if (process->outfd[Process::Stderr][0] > highest_fd_) highest_fd_ = process->outfd[Process::Stderr][0]; process->Run(); process->Write(envelope->input()); list_.push_back(service); Poll(); } else { Post(this, MSG_HANDLE_RESPONSE, service); } } void ServiceHandler::DoHandleResponse(ServiceData* service) { Envelope* envelope = service->envelope(); Process* process = service->process(); ServiceList::iterator remove = list_.end(); int highest_fd = 0; Envelope* e = NULL; Process* p = NULL; for (ServiceList::iterator it = list_.begin(); it != list_.end(); it++) { e = (*it)->envelope(); p = (*it)->process(); if (*it == service) { remove = it; } else { // Get highest fd that are not the two we're removing if (p->outfd[Process::Stdout][0] >= highest_fd) highest_fd = p->outfd[Process::Stdout][0]; if (p->outfd[Process::Stderr][0] >= highest_fd) highest_fd = p->outfd[Process::Stderr][0]; } } highest_fd_ = highest_fd; if (remove != list_.end()) { envelope->set_code(process->Close()); FD_CLR(process->outfd[Process::Stdout][0], &rfds_); FD_CLR(process->outfd[Process::Stderr][0], &rfds_); list_.erase(remove); } delete process; delete service; Post(this, MSG_RESPONSE, new EnvelopeData(envelope)); } void ServiceHandler::DoResponse(EnvelopeData* service) { // TODO(silas): Ready call probably isn't thread safe, figure out // alternative if (loop_->Ready()) { loop_->Response(service->data()); delete service; } else { int retry = service->data()->Retry(); TLOG(WARNING) << "Retrying service response in " << retry << " seconds (" << service->data()->iq_id() << ")"; PostDelayed(retry * 1000, this, MSG_RESPONSE, service); } } void ServiceHandler::DoPoll() { polling_--; if (list_.empty()) return; struct timeval tv; tv.tv_sec = PROCESS_BUFFER_SLEEP; tv.tv_usec = 0; fd_set rfds; FD_ZERO(&rfds); FD_COPY(&rfds_, &rfds); int sr = select(highest_fd_ + 1, &rfds, NULL, NULL, &tv); Envelope* e; Process *p; for (ServiceList::iterator it = list_.begin(); it != list_.end(); it++) { e = (*it)->envelope(); p = (*it)->process(); if (sr > 0) { // check both stdout and stderr for (int i = Process::Stdout; i <= Process::Stderr; i++) { // check if ready for reading if (FD_ISSET(p->outfd[i][0], &rfds)) { char data[PROCESS_BUFFER]; int rc = read(p->outfd[i][0], data, PROCESS_BUFFER-1); if (rc == 0) { // got eof for this fd p->outfdeof[i] = true; } else { // update output/error in process data[rc] = 0; if (Process::Stdout == i) { e->append_output(data); } else { e->append_error(data); } } } } } if (p->Done()) { Post(this, MSG_HANDLE_RESPONSE, *it); } } Poll(PROCESS_POLL_TIMEOUT); } bool ServiceHandler::Poll(int timeout) { if (polling_ > 0) { return false; } polling_++; PostDelayed(timeout, this, MSG_POLL); return true; } void ServiceHandler::OnMessage(txmpp::Message *pmsg) { switch (pmsg->message_id) { case MSG_REQUEST: assert(pmsg->pdata); DoRequest(reinterpret_cast<ServiceData*>(pmsg->pdata)); break; case MSG_HANDLE_RESPONSE: assert(pmsg->pdata); DoHandleResponse(reinterpret_cast<ServiceData*>(pmsg->pdata)); break; case MSG_RESPONSE: assert(pmsg->pdata); DoResponse(reinterpret_cast<EnvelopeData*>(pmsg->pdata)); break; case MSG_POLL: DoPoll(); break; default: assert(false); } } int64 ServiceHandler::CurrentTime() { return (int64)txmpp::Time(); } } // namespace tyrion
/* * Copyright (c) 2010, The Infrastructure Developers Group * All rights reserved. * * This file is subject to the New BSD License (see the LICENSE file). */ #include "service_handler.h" #include <sys/select.h> #include "loop.h" #include "process.h" #include "settings.h" #include "utils.h" #ifndef FD_COPY #define FD_COPY(f, t) memcpy(t, f, sizeof(*(f))) #endif namespace tyrion { ServiceHandler::ServiceHandler() : rfds_(), highest_fd_(0), list_(), polling_(0), loop_(NULL) { FD_ZERO(&rfds_); } void ServiceHandler::Request(Envelope* envelope) { Post(this, MSG_REQUEST, new ServiceHandlerData(envelope)); } void ServiceHandler::WakeTasks() { txmpp::Thread::Current()->Post(this); } void ServiceHandler::DoRequest(ServiceData* service) { Envelope* envelope = service->envelope(); bool issue = false; std::string config = "service:" + envelope->type(); std::string user = loop_->settings()->Get(config, "user"); bool user_lock = loop_->settings()->GetBool(config, "user_lock"); std::string group = loop_->settings()->Get(config, "group"); bool group_lock = loop_->settings()->GetBool(config, "group_lock"); int timeout = loop_->settings()->GetInt(config, "timeout"); bool timeout_lock = loop_->settings()->GetBool(config, "timeout_lock"); if (!issue && user_lock) { if (user.empty()) { envelope->append_error( CreateError("user.lock", "Unable to lock user because none set.")); issue = true; } } else if (!issue && !envelope->user().empty()) { user = envelope->user(); } if (!issue && group_lock) { if (group.empty()) { envelope->append_error( CreateError("group.lock", "Unable to lock group because none set.")); issue = true; } } else if (!issue && !envelope->group().empty()) group = envelope->group(); if (!issue && timeout_lock) { if (!timeout > 0) { envelope->append_error( CreateError("timeout.lock", "Unable to lock timeout because none set.")); issue = true; } } else { timeout = envelope->timeout(); } Process* process = new Process(envelope->Path(), false, timeout); service->set_process(process); if (!issue && !user.empty() && !process->set_user(user)) { envelope->append_error( CreateError("user.lookup", "Unable to find user '" + user + "'")); issue = true; } if (!issue && !group.empty() && !process->set_group(group)) { envelope->append_error( CreateError("group.lookup", "Unable to find group '" + group + "'")); issue = true; } if (!issue) { FD_SET(process->outfd[Process::Stdout][0], &rfds_); FD_SET(process->outfd[Process::Stderr][0], &rfds_); if (process->outfd[Process::Stdout][0] > highest_fd_) highest_fd_ = process->outfd[Process::Stdout][0]; if (process->outfd[Process::Stderr][0] > highest_fd_) highest_fd_ = process->outfd[Process::Stderr][0]; process->Run(); process->Write(envelope->input()); list_.push_back(service); Poll(); } else { Post(this, MSG_HANDLE_RESPONSE, service); } } void ServiceHandler::DoHandleResponse(ServiceData* service) { Envelope* envelope = service->envelope(); Process* process = service->process(); ServiceList::iterator remove = list_.end(); int highest_fd = 0; Envelope* e = NULL; Process* p = NULL; for (ServiceList::iterator it = list_.begin(); it != list_.end(); it++) { e = (*it)->envelope(); p = (*it)->process(); if (*it == service) { remove = it; } else { // Get highest fd that are not the two we're removing if (p->outfd[Process::Stdout][0] >= highest_fd) highest_fd = p->outfd[Process::Stdout][0]; if (p->outfd[Process::Stderr][0] >= highest_fd) highest_fd = p->outfd[Process::Stderr][0]; } } highest_fd_ = highest_fd; if (remove != list_.end()) { envelope->set_code(process->Close()); FD_CLR(process->outfd[Process::Stdout][0], &rfds_); FD_CLR(process->outfd[Process::Stderr][0], &rfds_); list_.erase(remove); } delete process; delete service; Post(this, MSG_RESPONSE, new EnvelopeData(envelope)); } void ServiceHandler::DoResponse(EnvelopeData* service) { // TODO(silas): the Ready call probably isn't thread safe, figure out // alternative if (loop_->Ready()) { loop_->Response(service->data()); delete service; } else { int retry = service->data()->Retry(); TLOG(WARNING) << "Retrying service response in " << retry << " seconds (" << service->data()->iq_id() << ")"; PostDelayed(retry * 1000, this, MSG_RESPONSE, service); } } void ServiceHandler::DoPoll() { polling_--; if (list_.empty()) return; struct timeval tv; tv.tv_sec = PROCESS_BUFFER_SLEEP; tv.tv_usec = 0; fd_set rfds; FD_ZERO(&rfds); FD_COPY(&rfds_, &rfds); int sr = select(highest_fd_ + 1, &rfds, NULL, NULL, &tv); Envelope* e; Process *p; for (ServiceList::iterator it = list_.begin(); it != list_.end(); it++) { e = (*it)->envelope(); p = (*it)->process(); if (sr > 0) { // check both stdout and stderr for (int i = Process::Stdout; i <= Process::Stderr; i++) { // check if ready for reading if (FD_ISSET(p->outfd[i][0], &rfds)) { char data[PROCESS_BUFFER]; int rc = read(p->outfd[i][0], data, PROCESS_BUFFER-1); if (rc == 0) { // got eof for this fd p->outfdeof[i] = true; } else { // update output/error in process data[rc] = 0; if (Process::Stdout == i) { e->append_output(data); } else { e->append_error(data); } } } } } if (p->Done()) { Post(this, MSG_HANDLE_RESPONSE, *it); } } Poll(PROCESS_POLL_TIMEOUT); } bool ServiceHandler::Poll(int timeout) { if (polling_ > 0) { return false; } polling_++; PostDelayed(timeout, this, MSG_POLL); return true; } void ServiceHandler::OnMessage(txmpp::Message *pmsg) { switch (pmsg->message_id) { case MSG_REQUEST: assert(pmsg->pdata); DoRequest(reinterpret_cast<ServiceData*>(pmsg->pdata)); break; case MSG_HANDLE_RESPONSE: assert(pmsg->pdata); DoHandleResponse(reinterpret_cast<ServiceData*>(pmsg->pdata)); break; case MSG_RESPONSE: assert(pmsg->pdata); DoResponse(reinterpret_cast<EnvelopeData*>(pmsg->pdata)); break; case MSG_POLL: DoPoll(); break; default: assert(false); } } int64 ServiceHandler::CurrentTime() { return (int64)txmpp::Time(); } } // namespace tyrion
Tweak todo
Tweak todo
C++
mit
silas/tyrion,silas/tyrion,silas/tyrion,silas/tyrion,silas/tyrion
3283d4fe871ad6728e16e1f65c731b1c26dc60ed
src/slib/ui/ui_app.cpp
src/slib/ui/ui_app.cpp
/* * Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO> * * 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 "slib/ui/app.h" #include "slib/ui/core.h" #include "slib/ui/window.h" #include "slib/ui/menu.h" #include "slib/network/url_request.h" namespace slib { SLIB_DEFINE_OBJECT(UIApp, Application) UIApp::UIApp() { } UIApp::~UIApp() { } Ref<UIApp> UIApp::getApp() { return CastRef<UIApp>(Application::getApp()); } AppType UIApp::getAppType() { return AppType::UI; } void UIApp::quit() { UI::quitApp(); } Ref<Window> UIApp::getMainWindow() { return m_mainWindow; } void UIApp::setMainWindow(const Ref<Window>& window) { void* _thiz = this; if (_thiz) { m_mainWindow = window; #ifdef SLIB_PLATFORM_IS_DESKTOP if (window.isNotNull()) { window->addOnDestroy([](Window*) { UI::quitApp(); }); } #endif } } Ref<Menu> UIApp::getMenu() { return m_mainMenu; } #if !defined(SLIB_UI_IS_MACOS) void UIApp::setMenu(const Ref<Menu>& menu) { m_mainMenu = menu; } #endif void UIApp::onRunApp() { UI::runApp(); } SLIB_DEFINE_EVENT_HANDLER(UIApp, Start) void UIApp::dispatchStart() { UrlRequest::setDefaultDispatcher(UI::getDispatcher()); SLIB_INVOKE_EVENT_HANDLER(Start) } void UIApp::dispatchStartToApp() { Ref<UIApp> app = getApp(); if (app.isNotNull()) { app->dispatchStart(); } } SLIB_DEFINE_EVENT_HANDLER(UIApp, Exit) void UIApp::dispatchExit() { SLIB_INVOKE_EVENT_HANDLER(Exit) } void UIApp::dispatchExitToApp() { Ref<UIApp> app = getApp(); if (app.isNotNull()) { app->dispatchExit(); } } }
/* * Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO> * * 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 "slib/ui/app.h" #include "slib/ui/core.h" #include "slib/ui/window.h" #include "slib/ui/menu.h" #include "slib/network/url_request.h" namespace slib { SLIB_DEFINE_OBJECT(UIApp, Application) UIApp::UIApp() { } UIApp::~UIApp() { } Ref<UIApp> UIApp::getApp() { return CastRef<UIApp>(Application::getApp()); } AppType UIApp::getAppType() { return AppType::UI; } void UIApp::quit() { UI::quitApp(); } Ref<Window> UIApp::getMainWindow() { return m_mainWindow; } void UIApp::setMainWindow(const Ref<Window>& window) { void* _thiz = this; if (_thiz) { m_mainWindow = window; #ifdef SLIB_PLATFORM_IS_DESKTOP if (window.isNotNull()) { window->addOnDestroy([](Window*) { UI::quitApp(); }); #ifdef SLIB_UI_IS_MACOS Ref<Menu> menu = window->getMenu(); if (menu.isNotNull()) { setMenu(menu); } #endif } #endif } } Ref<Menu> UIApp::getMenu() { return m_mainMenu; } #if !defined(SLIB_UI_IS_MACOS) void UIApp::setMenu(const Ref<Menu>& menu) { m_mainMenu = menu; } #endif void UIApp::onRunApp() { UI::runApp(); } SLIB_DEFINE_EVENT_HANDLER(UIApp, Start) void UIApp::dispatchStart() { UrlRequest::setDefaultDispatcher(UI::getDispatcher()); SLIB_INVOKE_EVENT_HANDLER(Start) } void UIApp::dispatchStartToApp() { Ref<UIApp> app = getApp(); if (app.isNotNull()) { app->dispatchStart(); } } SLIB_DEFINE_EVENT_HANDLER(UIApp, Exit) void UIApp::dispatchExit() { SLIB_INVOKE_EVENT_HANDLER(Exit) } void UIApp::dispatchExitToApp() { Ref<UIApp> app = getApp(); if (app.isNotNull()) { app->dispatchExit(); } } }
set main window's menu as application menu automatically
[macOS] ui/Menu: set main window's menu as application menu automatically
C++
mit
SLIBIO/SLib,SLIBIO/SLib,SLIBIO/SLib,SLIBIO/SLib,SLIBIO/SLib
8eeaa4f21203f669fb202bc345dcfdb2f5dc19fb
src/test/net_tests.cpp
src/test/net_tests.cpp
// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addrman.h" #include "test/test_dash.h" #include <string> #include <boost/test/unit_test.hpp> #include "hash.h" #include "serialize.h" #include "streams.h" #include "net.h" #include "netbase.h" #include "chainparams.h" using namespace std; class CAddrManSerializationMock : public CAddrMan { public: virtual void Serialize(CDataStream& s, int nType, int nVersionDummy) const = 0; //! Ensure that bucket placement is always the same for testing purposes. void MakeDeterministic() { nKey.SetNull(); seed_insecure_rand(true); } }; class CAddrManUncorrupted : public CAddrManSerializationMock { public: void Serialize(CDataStream& s, int nType, int nVersionDummy) const { CAddrMan::Serialize(s, nType, nVersionDummy); } }; class CAddrManCorrupted : public CAddrManSerializationMock { public: void Serialize(CDataStream& s, int nType, int nVersionDummy) const { // Produces corrupt output that claims addrman has 20 addrs when it only has one addr. unsigned char nVersion = 1; s << nVersion; s << ((unsigned char)32); s << nKey; s << 10; // nNew s << 10; // nTried int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30); s << nUBuckets; CService serv; Lookup("252.1.1.1", serv, 7777, false); CAddress addr = CAddress(serv, NODE_NONE); CNetAddr resolved; LookupHost("252.2.2.2", resolved, false); CAddrInfo info = CAddrInfo(addr, resolved); s << info; } }; CDataStream AddrmanToStream(CAddrManSerializationMock& addrman) { CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION); ssPeersIn << FLATDATA(Params().MessageStart()); ssPeersIn << addrman; std::string str = ssPeersIn.str(); vector<unsigned char> vchData(str.begin(), str.end()); return CDataStream(vchData, SER_DISK, CLIENT_VERSION); } BOOST_FIXTURE_TEST_SUITE(net_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(caddrdb_read) { CAddrManUncorrupted addrmanUncorrupted; addrmanUncorrupted.MakeDeterministic(); CService addr1, addr2, addr3; Lookup("250.7.1.1", addr1, 8333, false); Lookup("250.7.2.2", addr2, 9999, false); Lookup("250.7.3.3", addr3, 9999, false); // Add three addresses to new table. CService source; Lookup("252.5.1.1", source, 8333, false); addrmanUncorrupted.Add(CAddress(addr1, NODE_NONE), source); addrmanUncorrupted.Add(CAddress(addr2, NODE_NONE), source); addrmanUncorrupted.Add(CAddress(addr3, NODE_NONE), source); // Test that the de-serialization does not throw an exception. CDataStream ssPeers1 = AddrmanToStream(addrmanUncorrupted); bool exceptionThrown = false; CAddrMan addrman1; BOOST_CHECK(addrman1.size() == 0); try { unsigned char pchMsgTmp[4]; ssPeers1 >> FLATDATA(pchMsgTmp); ssPeers1 >> addrman1; } catch (const std::exception& e) { exceptionThrown = true; } BOOST_CHECK(addrman1.size() == 3); BOOST_CHECK(exceptionThrown == false); // Test that CAddrDB::Read creates an addrman with the correct number of addrs. CDataStream ssPeers2 = AddrmanToStream(addrmanUncorrupted); CAddrMan addrman2; CAddrDB adb; BOOST_CHECK(addrman2.size() == 0); adb.Read(addrman2, ssPeers2); BOOST_CHECK(addrman2.size() == 3); } BOOST_AUTO_TEST_CASE(caddrdb_read_corrupted) { CAddrManCorrupted addrmanCorrupted; addrmanCorrupted.MakeDeterministic(); // Test that the de-serialization of corrupted addrman throws an exception. CDataStream ssPeers1 = AddrmanToStream(addrmanCorrupted); bool exceptionThrown = false; CAddrMan addrman1; BOOST_CHECK(addrman1.size() == 0); try { unsigned char pchMsgTmp[4]; ssPeers1 >> FLATDATA(pchMsgTmp); ssPeers1 >> addrman1; } catch (const std::exception& e) { exceptionThrown = true; } // Even through de-serialization failed adddrman is not left in a clean state. BOOST_CHECK(addrman1.size() == 1); BOOST_CHECK(exceptionThrown); // Test that CAddrDB::Read leaves addrman in a clean state if de-serialization fails. CDataStream ssPeers2 = AddrmanToStream(addrmanCorrupted); CAddrMan addrman2; CAddrDB adb; BOOST_CHECK(addrman2.size() == 0); adb.Read(addrman2, ssPeers2); BOOST_CHECK(addrman2.size() == 0); } BOOST_AUTO_TEST_CASE(cnode_simple_test) { SOCKET hSocket = INVALID_SOCKET; NodeId id = 0; int height = 0; in_addr ipv4Addr; ipv4Addr.s_addr = 0xa0b0c001; CAddress addr = CAddress(CService(ipv4Addr, 7777), NODE_NETWORK); std::string pszDest = ""; bool fInboundIn = false; // Test that fFeeler is false by default. CNode* pnode1 = new CNode(id++, NODE_NETWORK, height, hSocket, addr, pszDest, fInboundIn); BOOST_CHECK(pnode1->fInbound == false); BOOST_CHECK(pnode1->fFeeler == false); fInboundIn = true; CNode* pnode2 = new CNode(id++, NODE_NETWORK, height, hSocket, addr, pszDest, fInboundIn); BOOST_CHECK(pnode2->fInbound == true); BOOST_CHECK(pnode2->fFeeler == false); } BOOST_AUTO_TEST_SUITE_END()
// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addrman.h" #include "test/test_dash.h" #include <string> #include <boost/test/unit_test.hpp> #include "hash.h" #include "serialize.h" #include "streams.h" #include "net.h" #include "netbase.h" #include "chainparams.h" using namespace std; class CAddrManSerializationMock : public CAddrMan { public: virtual void Serialize(CDataStream& s, int nType, int nVersionDummy) const = 0; //! Ensure that bucket placement is always the same for testing purposes. void MakeDeterministic() { nKey.SetNull(); seed_insecure_rand(true); } }; class CAddrManUncorrupted : public CAddrManSerializationMock { public: void Serialize(CDataStream& s, int nType, int nVersionDummy) const { CAddrMan::Serialize(s, nType, nVersionDummy); } }; class CAddrManCorrupted : public CAddrManSerializationMock { public: void Serialize(CDataStream& s, int nType, int nVersionDummy) const { // Produces corrupt output that claims addrman has 20 addrs when it only has one addr. unsigned char nVersion = 1; s << nVersion; s << ((unsigned char)32); s << nKey; s << 10; // nNew s << 10; // nTried int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30); s << nUBuckets; CService serv; Lookup("252.1.1.1", serv, 7777, false); CAddress addr = CAddress(serv, NODE_NONE); CNetAddr resolved; LookupHost("252.2.2.2", resolved, false); CAddrInfo info = CAddrInfo(addr, resolved); s << info; } }; CDataStream AddrmanToStream(CAddrManSerializationMock& addrman) { CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION); ssPeersIn << FLATDATA(Params().MessageStart()); ssPeersIn << addrman; std::string str = ssPeersIn.str(); vector<unsigned char> vchData(str.begin(), str.end()); return CDataStream(vchData, SER_DISK, CLIENT_VERSION); } BOOST_FIXTURE_TEST_SUITE(net_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(caddrdb_read) { CAddrManUncorrupted addrmanUncorrupted; addrmanUncorrupted.MakeDeterministic(); CService addr1, addr2, addr3; Lookup("250.7.1.1", addr1, 8333, false); Lookup("250.7.2.2", addr2, 9999, false); Lookup("250.7.3.3", addr3, 9999, false); // Add three addresses to new table. CService source; Lookup("252.5.1.1", source, 8333, false); addrmanUncorrupted.Add(CAddress(addr1, NODE_NONE), source); addrmanUncorrupted.Add(CAddress(addr2, NODE_NONE), source); addrmanUncorrupted.Add(CAddress(addr3, NODE_NONE), source); // Test that the de-serialization does not throw an exception. CDataStream ssPeers1 = AddrmanToStream(addrmanUncorrupted); bool exceptionThrown = false; CAddrMan addrman1; BOOST_CHECK(addrman1.size() == 0); try { unsigned char pchMsgTmp[4]; ssPeers1 >> FLATDATA(pchMsgTmp); ssPeers1 >> addrman1; } catch (const std::exception& e) { exceptionThrown = true; } BOOST_CHECK(addrman1.size() == 3); BOOST_CHECK(exceptionThrown == false); // Test that CAddrDB::Read creates an addrman with the correct number of addrs. CDataStream ssPeers2 = AddrmanToStream(addrmanUncorrupted); CAddrMan addrman2; CAddrDB adb; BOOST_CHECK(addrman2.size() == 0); adb.Read(addrman2, ssPeers2); BOOST_CHECK(addrman2.size() == 3); } BOOST_AUTO_TEST_CASE(caddrdb_read_corrupted) { CAddrManCorrupted addrmanCorrupted; addrmanCorrupted.MakeDeterministic(); // Test that the de-serialization of corrupted addrman throws an exception. CDataStream ssPeers1 = AddrmanToStream(addrmanCorrupted); bool exceptionThrown = false; CAddrMan addrman1; BOOST_CHECK(addrman1.size() == 0); try { unsigned char pchMsgTmp[4]; ssPeers1 >> FLATDATA(pchMsgTmp); ssPeers1 >> addrman1; } catch (const std::exception& e) { exceptionThrown = true; } // Even through de-serialization failed addrman is not left in a clean state. BOOST_CHECK(addrman1.size() == 1); BOOST_CHECK(exceptionThrown); // Test that CAddrDB::Read leaves addrman in a clean state if de-serialization fails. CDataStream ssPeers2 = AddrmanToStream(addrmanCorrupted); CAddrMan addrman2; CAddrDB adb; BOOST_CHECK(addrman2.size() == 0); adb.Read(addrman2, ssPeers2); BOOST_CHECK(addrman2.size() == 0); } BOOST_AUTO_TEST_CASE(cnode_simple_test) { SOCKET hSocket = INVALID_SOCKET; NodeId id = 0; int height = 0; in_addr ipv4Addr; ipv4Addr.s_addr = 0xa0b0c001; CAddress addr = CAddress(CService(ipv4Addr, 7777), NODE_NETWORK); std::string pszDest = ""; bool fInboundIn = false; // Test that fFeeler is false by default. CNode* pnode1 = new CNode(id++, NODE_NETWORK, height, hSocket, addr, pszDest, fInboundIn); BOOST_CHECK(pnode1->fInbound == false); BOOST_CHECK(pnode1->fFeeler == false); fInboundIn = true; CNode* pnode2 = new CNode(id++, NODE_NETWORK, height, hSocket, addr, pszDest, fInboundIn); BOOST_CHECK(pnode2->fInbound == true); BOOST_CHECK(pnode2->fFeeler == false); } BOOST_AUTO_TEST_SUITE_END()
Fix typo adddrman to addrman as requested in #8070
Fix typo adddrman to addrman as requested in #8070
C++
mit
dashpay/dash,thelazier/dash,ivansib/sibcoin,crowning-/dash,biblepay/biblepay,crowning-/dash,dashpay/dash,nmarley/dash,UdjinM6/dash,dashpay/dash,crowning-/dash,nmarley/dash,ionomy/ion,UdjinM6/dash,biblepay/biblepay,dashpay/dash,thelazier/dash,thelazier/dash,thelazier/dash,ionomy/ion,crowning-/dash,biblepay/biblepay,UdjinM6/dash,nmarley/dash,biblepay/biblepay,UdjinM6/dash,nmarley/dash,nmarley/dash,ionomy/ion,thelazier/dash,biblepay/biblepay,ionomy/ion,crowning-/dash,nmarley/dash,nmarley/dash,biblepay/biblepay,ivansib/sibcoin,biblepay/biblepay,UdjinM6/dash,crowning-/dash,ionomy/ion,ivansib/sibcoin,biblepay/biblepay,ivansib/sibcoin,ivansib/sibcoin,ionomy/ion,ivansib/sibcoin,dashpay/dash
a140e7c6f11d4985997e6c7db70e78ed103b5fa9
src/vm/weak_object.cpp
src/vm/weak_object.cpp
/* * Copyright (C) 2010-2011 O01eg <[email protected]> * * This file is part of Genetic Function Programming. * * Genetic Function Programming is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Genetic Function Programming 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 Genetic Function Programming. If not, see <http://www.gnu.org/licenses/>. */ #include <stack> #include "weak_object.h" using namespace VM; WeakObject& WeakObject::operator=(const WeakObject& obj) { if(this != &obj) { if(&m_Env != &obj.m_Env) { THROW(FormatString("WeakObject 0x", this, " and 0x", &obj, ": Different environments.")); } m_Pos = obj.m_Pos; } return *this; } Heap::UInt WeakObject::GetValue() const { #if _DEBUG_OBJECT_ Types type = GetType(); if((type != INTEGER) && (type != FUNC) && (type != ADF)) { THROW(FormatString("Object 0x", this, ": Non one-parameter type ", type, ".")); } #endif return m_Env.heap.At(m_Pos).value; } WeakObject WeakObject::GetHead() const { #if _DEBUG_OBJECT_ if(GetType() != LIST) { THROW(FormatString("Object 0x", this, ": Non LIST type ", GetType(), ".")); } #endif return GetWeakObjectFrom(m_Env, m_Env.heap.At(m_Pos).value); } WeakObject WeakObject::GetTail() const { #if _DEBUG_OBJECT_ if(GetType() != LIST) { THROW(FormatString("Object 0x", this, ": Non LIST type ", GetType(), ".")); } #endif return GetWeakObjectFrom(m_Env, m_Env.heap.At(m_Pos).tail); } WeakObject WeakObject::GetWeakObjectFrom(const Environment &env, Heap::UInt pos) { WeakObject res(env); res.m_Pos = pos; return res; } bool WeakObject::operator==(const WeakObject& obj) const { #if _DEBUG_OBJECT_ if(&m_Env != &obj.m_Env) { THROW(FormatString("WeakObject 0x", this, " and 0x", &obj, ": Different environments.")); } #endif if(m_Pos == obj.m_Pos) { return true; } else { if(IsNIL() || obj.IsNIL()) { // one is NIL but another isn't return false; } else { if(GetType() == obj.GetType()) { /// \todo Rewrite this into low-level work with heap data. switch(GetType()) { case ERROR: case PARAM: case QUOTE: case IF: case EVAL: return true; case INTEGER: case FUNC: case ADF: return GetValue() == obj.GetValue(); case LIST: { std::stack<VM::WeakObject> stack; stack.push(*this); stack.push(obj); while(! stack.empty()) { VM::WeakObject obj1 = stack.top(); stack.pop(); VM::WeakObject obj2 = stack.top(); stack.pop(); if(obj1.IsNIL()) { if(! obj2.IsNIL()) { return false; } } else { if(obj2.IsNIL()) { return false; } else { if((obj1.GetType() == LIST) && (obj2.GetType() == LIST)) { if(obj1.m_Pos != obj2.m_Pos) { stack.push(obj1.GetHead()); stack.push(obj2.GetHead()); stack.push(obj1.GetTail()); stack.push(obj2.GetTail()); } } else { if(obj1 != obj2) { return false; } } } } } return true; } } } else { // different types return false; } } } return false; }
/* * Copyright (C) 2010-2011 O01eg <[email protected]> * * This file is part of Genetic Function Programming. * * Genetic Function Programming is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Genetic Function Programming 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 Genetic Function Programming. If not, see <http://www.gnu.org/licenses/>. */ #include <stack> #include "weak_object.h" using namespace VM; WeakObject& WeakObject::operator=(const WeakObject& obj) { if(this != &obj) { if(&m_Env != &obj.m_Env) { THROW(FormatString("WeakObject 0x", this, " and 0x", &obj, ": Different environments.")); } m_Pos = obj.m_Pos; } return *this; } Heap::UInt WeakObject::GetValue() const { #if _DEBUG_OBJECT_ Types type = GetType(); if((type != INTEGER) && (type != FUNC) && (type != ADF)) { THROW(FormatString("Object 0x", this, ": Non one-parameter type ", type, ".")); } #endif return m_Env.heap.At(m_Pos).value; } WeakObject WeakObject::GetHead() const { #if _DEBUG_OBJECT_ if(GetType() != LIST) { THROW(FormatString("Object 0x", this, ": Non LIST type ", GetType(), ".")); } #endif return GetWeakObjectFrom(m_Env, m_Env.heap.At(m_Pos).value); } WeakObject WeakObject::GetTail() const { #if _DEBUG_OBJECT_ if(GetType() != LIST) { THROW(FormatString("Object 0x", this, ": Non LIST type ", GetType(), ".")); } #endif return GetWeakObjectFrom(m_Env, m_Env.heap.At(m_Pos).tail); } WeakObject WeakObject::GetWeakObjectFrom(const Environment &env, Heap::UInt pos) { WeakObject res(env); res.m_Pos = pos; return res; } bool WeakObject::operator==(const WeakObject& obj) const { #if _DEBUG_OBJECT_ if(&m_Env != &obj.m_Env) { THROW(FormatString("WeakObject 0x", this, " and 0x", &obj, ": Different environments.")); } #endif if(m_Pos == obj.m_Pos) { return true; } else { if(IsNIL() || obj.IsNIL()) { // one is NIL but another isn't return false; } else { if(m_Env.heap.At(m_Pos).hash == m_Env.heap.At(obj.m_Pos).hash) { /// \todo Rewrite this into low-level work with heap data. switch(GetType()) { case ERROR: case PARAM: case QUOTE: case IF: case EVAL: return true; case INTEGER: case FUNC: case ADF: return GetValue() == obj.GetValue(); case LIST: { std::stack<VM::WeakObject> stack; stack.push(*this); stack.push(obj); while(! stack.empty()) { VM::WeakObject obj1 = stack.top(); stack.pop(); VM::WeakObject obj2 = stack.top(); stack.pop(); if(obj1.IsNIL()) { if(! obj2.IsNIL()) { return false; } } else { if(obj2.IsNIL()) { return false; } else { if((obj1.GetType() == LIST) && (obj2.GetType() == LIST)) { if(obj1.m_Pos != obj2.m_Pos) { stack.push(obj1.GetHead()); stack.push(obj2.GetHead()); stack.push(obj1.GetTail()); stack.push(obj2.GetTail()); } } else { if(obj1 != obj2) { return false; } } } } } return true; } } } else { // different hashes return false; } } } return false; }
Speed up objects's compare .
Speed up objects's compare .
C++
mit
o01eg/gfp,o01eg/gfp,o01eg/gfp
36202cf7ddbaa7b3f654cd896de6ea301389c698
src/weston_backend.hpp
src/weston_backend.hpp
#ifndef WESTON_BACKEND_HPP #define WESTON_BACKEND_HPP #include "commonincludes.hpp" #include "core.hpp" #include <compositor-drm.h> #include <compositor-x11.h> #include <compositor-wayland.h> #include <windowed-output-api.h> #include <cstring> #include <assert.h> #include <libinput.h> wl_listener output_pending_listener; void set_output_pending_handler(weston_compositor *ec, wl_notify_func_t handler) { output_pending_listener.notify = handler; wl_signal_add(&ec->output_pending_signal, &output_pending_listener); } void configure_input_device(weston_compositor *ec, libinput_device *device) { if (libinput_device_config_tap_get_finger_count(device) > 0) { /* TODO: read option from config */ libinput_device_config_tap_set_enabled(device, LIBINPUT_CONFIG_TAP_ENABLED); } } bool backend_loaded = false; std::vector<weston_output*> pending_outputs; void configure_drm_backend_output (wl_listener *listener, void *data) { weston_output *output = (weston_output*)data; if (!backend_loaded) { pending_outputs.push_back(output); return; } auto api = weston_drm_output_get_api(output->compositor); weston_output_set_transform(output, WL_OUTPUT_TRANSFORM_NORMAL); weston_output_set_scale(output, 1); api->set_gbm_format(output, NULL); api->set_mode(output, WESTON_DRM_BACKEND_OUTPUT_CURRENT, NULL); api->set_seat(output, ""); weston_output_enable(output); } int load_drm_backend(weston_compositor *ec) { weston_drm_backend_config config; std::memset(&config, 0, sizeof(config)); config.base.struct_version = WESTON_DRM_BACKEND_CONFIG_VERSION; config.base.struct_size = sizeof(weston_drm_backend_config); config.configure_device = configure_input_device; config.gbm_format = 0; config.connector = 0; config.seat_id = 0; config.use_pixman = 0; config.tty = 0; set_output_pending_handler(ec, configure_drm_backend_output); auto ret = weston_compositor_load_backend(ec, WESTON_BACKEND_DRM, &config.base); if (ret >= 0) { backend_loaded = true; for (auto output : pending_outputs) configure_drm_backend_output(&output_pending_listener, output); pending_outputs.clear(); } core->backend = WESTON_BACKEND_DRM; return ret; } const int default_width = 800, default_height = 450; void configure_windowed_output (wl_listener *listener, void *data) { weston_output *output = (weston_output*)data; auto api = weston_windowed_output_get_api(output->compositor); assert(api != NULL); weston_output_set_scale(output, 1); weston_output_set_transform(output, WL_OUTPUT_TRANSFORM_NORMAL); if (api->output_set_size(output, default_width, default_height) < 0) { errio << "can't configure output " << output->id << std::endl; return; } weston_output_enable(output); } int load_wayland_backend(weston_compositor *ec) { weston_wayland_backend_config config; std::memset(&config, 0, sizeof(config)); config.base.struct_version = WESTON_WAYLAND_BACKEND_CONFIG_VERSION; config.base.struct_size = sizeof(weston_wayland_backend_config); config.cursor_size = 32; config.display_name = 0; config.use_pixman = 0; config.sprawl = 0; config.fullscreen = 0; config.cursor_theme = NULL; if (weston_compositor_load_backend(ec, WESTON_BACKEND_WAYLAND, &config.base) < 0) return -1; auto api = weston_windowed_output_get_api(ec); if (api == NULL) return -1; core->backend = WESTON_BACKEND_WAYLAND; set_output_pending_handler(ec, configure_windowed_output); if (api->output_create(ec, "wl1") < 0) return -1; return 0; } int load_x11_backend(weston_compositor *ec) { weston_x11_backend_config config; config.base.struct_version = WESTON_X11_BACKEND_CONFIG_VERSION; config.base.struct_size = sizeof(weston_x11_backend_config); config.use_pixman = false; config.fullscreen = false; config.no_input = false; if (weston_compositor_load_backend(ec, WESTON_BACKEND_X11, &config.base) < 0) return -1; set_output_pending_handler(ec, configure_windowed_output); auto api = weston_windowed_output_get_api(ec); if (!api || api->output_create(ec, "wl1") < 0) return -1; return 0; } #endif /* end of include guard: WESTON_BACKEND_HPP */
#ifndef WESTON_BACKEND_HPP #define WESTON_BACKEND_HPP #include "commonincludes.hpp" #include "core.hpp" #include <compositor-drm.h> #include <compositor-x11.h> #include <compositor-wayland.h> #include <windowed-output-api.h> #include <cstring> #include <assert.h> #include <libinput.h> wl_listener output_pending_listener; void set_output_pending_handler(weston_compositor *ec, wl_notify_func_t handler) { output_pending_listener.notify = handler; wl_signal_add(&ec->output_pending_signal, &output_pending_listener); } void configure_input_device(weston_compositor *ec, libinput_device *device) { if (libinput_device_config_tap_get_finger_count(device) > 0) { /* TODO: read option from config */ libinput_device_config_tap_set_enabled(device, LIBINPUT_CONFIG_TAP_ENABLED); } } bool backend_loaded = false; std::vector<weston_output*> pending_outputs; void configure_drm_backend_output (wl_listener *listener, void *data) { weston_output *output = (weston_output*)data; if (!backend_loaded) { pending_outputs.push_back(output); return; } auto api = weston_drm_output_get_api(output->compositor); weston_output_set_transform(output, WL_OUTPUT_TRANSFORM_NORMAL); weston_output_set_scale(output, 1); api->set_gbm_format(output, NULL); api->set_mode(output, WESTON_DRM_BACKEND_OUTPUT_CURRENT, NULL); api->set_seat(output, ""); weston_output_enable(output); } int load_drm_backend(weston_compositor *ec) { weston_drm_backend_config config; std::memset(&config, 0, sizeof(config)); config.base.struct_version = WESTON_DRM_BACKEND_CONFIG_VERSION; config.base.struct_size = sizeof(weston_drm_backend_config); config.configure_device = configure_input_device; config.gbm_format = 0; config.seat_id = 0; config.use_pixman = 0; config.tty = 0; set_output_pending_handler(ec, configure_drm_backend_output); auto ret = weston_compositor_load_backend(ec, WESTON_BACKEND_DRM, &config.base); if (ret >= 0) { backend_loaded = true; for (auto output : pending_outputs) configure_drm_backend_output(&output_pending_listener, output); pending_outputs.clear(); } core->backend = WESTON_BACKEND_DRM; return ret; } const int default_width = 800, default_height = 450; void configure_windowed_output (wl_listener *listener, void *data) { weston_output *output = (weston_output*)data; auto api = weston_windowed_output_get_api(output->compositor); assert(api != NULL); weston_output_set_scale(output, 1); weston_output_set_transform(output, WL_OUTPUT_TRANSFORM_NORMAL); if (api->output_set_size(output, default_width, default_height) < 0) { errio << "can't configure output " << output->id << std::endl; return; } weston_output_enable(output); } int load_wayland_backend(weston_compositor *ec) { weston_wayland_backend_config config; std::memset(&config, 0, sizeof(config)); config.base.struct_version = WESTON_WAYLAND_BACKEND_CONFIG_VERSION; config.base.struct_size = sizeof(weston_wayland_backend_config); config.cursor_size = 32; config.display_name = 0; config.use_pixman = 0; config.sprawl = 0; config.fullscreen = 0; config.cursor_theme = NULL; if (weston_compositor_load_backend(ec, WESTON_BACKEND_WAYLAND, &config.base) < 0) return -1; auto api = weston_windowed_output_get_api(ec); if (api == NULL) return -1; core->backend = WESTON_BACKEND_WAYLAND; set_output_pending_handler(ec, configure_windowed_output); if (api->output_create(ec, "wl1") < 0) return -1; return 0; } int load_x11_backend(weston_compositor *ec) { weston_x11_backend_config config; config.base.struct_version = WESTON_X11_BACKEND_CONFIG_VERSION; config.base.struct_size = sizeof(weston_x11_backend_config); config.use_pixman = false; config.fullscreen = false; config.no_input = false; if (weston_compositor_load_backend(ec, WESTON_BACKEND_X11, &config.base) < 0) return -1; set_output_pending_handler(ec, configure_windowed_output); auto api = weston_windowed_output_get_api(ec); if (!api || api->output_create(ec, "wl1") < 0) return -1; return 0; } #endif /* end of include guard: WESTON_BACKEND_HPP */
remove config.connection which is also removed from libweston
libweston: remove config.connection which is also removed from libweston
C++
mit
ammen99/wayfire,ammen99/wayfire
b9318d9d106666e430f4f278d1a38b5315fd4732
ScriptingProject/MapSelectUI.cpp
ScriptingProject/MapSelectUI.cpp
#include "stdafx.h" #include <string> #include <map> #include <vector> #include "../Application.h" #include "../ModuleScripting.h" #include "../ModuleInput.h" #include "../ModuleWindow.h" #include "../ComponentTransform.h" #include "../ModuleGOManager.h" #include "../GameObject.h" #include "../Component.h" #include "../ComponentScript.h" #include "../ComponentRectTransform.h" #include "../SDL/include/SDL_scancode.h" #include "../Globals.h" #include "../ComponentUiButton.h" #include "../ComponentCanvas.h" #include "../ModuleResourceManager.h" #include "../Random.h" #include "../Time.h" #include "../ComponentAudioSource.h" namespace MapSelectUI { GameObject* map_fields = nullptr; GameObject* map_umi = nullptr; GameObject* map_ricing = nullptr; GameObject* players_vote[4]; GameObject* right_arrow = nullptr; GameObject* left_arrow = nullptr; ComponentUiButton* c_players_vote[4]; // 0 - P1 Red, 1 - P2 Red, 2 - P1 Blue, 2 - P2 Blue, ComponentUiButton* c_right_arrow = nullptr; ComponentUiButton* c_left_arrow = nullptr; string path_map1 = "Scene_Map_1/Scene_Map_1.ezx"; string path_map2 = "Scene_Map_2/Scene_Map_2.ezx"; string path_map3 = "Scene_Map_3/Scene_Map_3.ezx"; bool players_ready[4] = { false, false, false, false }; bool a_pressed = false; bool b_pressed = false; bool dpad_left_pressed = false; bool dpad_right_pressed = false; int current_level = 0; int current_map = 0; // 1 - , 2 - , 3 - , int votes[4] = { 0, 0, 0, 0 }; int arrow_counter_left = 30; int arrow_counter_right = 30; int time = 30; int player_order[4]; void MapSelectUI_GetPublics(map<const char*, string>* public_chars, map<const char*, int>* public_ints, map<const char*, float>* public_float, map<const char*, bool>* public_bools, map<const char*, GameObject*>* public_gos) { public_gos->insert(std::pair<const char*, GameObject*>("Map Fields", map_fields)); public_gos->insert(std::pair<const char*, GameObject*>("Map Umi", map_umi)); public_gos->insert(std::pair<const char*, GameObject*>("Map Ricing", map_ricing)); public_gos->insert(std::pair<const char*, GameObject*>("P1-Red Vote", players_vote[2])); public_gos->insert(std::pair<const char*, GameObject*>("P2-Red Vote", players_vote[3])); public_gos->insert(std::pair<const char*, GameObject*>("P1-Blue Vote", players_vote[0])); public_gos->insert(std::pair<const char*, GameObject*>("P2-Blue Vote", players_vote[1])); public_gos->insert(std::pair<const char*, GameObject*>("R-Arrow", right_arrow)); public_gos->insert(std::pair<const char*, GameObject*>("L-Arrow", left_arrow)); public_ints->insert(std::pair<const char*, int>("Button Cooldown", time)); } void MapSelectUI_UpdatePublics(GameObject* game_object) { ComponentScript* test_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT); map_fields = test_script->public_gos.at("Map Fields"); map_umi = test_script->public_gos.at("Map Umi"); map_ricing = test_script->public_gos.at("Map Ricing"); players_vote[0] = test_script->public_gos.at("P1-Blue Vote"); players_vote[1] = test_script->public_gos.at("P2-Blue Vote"); players_vote[2] = test_script->public_gos.at("P1-Red Vote"); players_vote[3] = test_script->public_gos.at("P2-Red Vote"); right_arrow = test_script->public_gos.at("R-Arrow"); left_arrow = test_script->public_gos.at("L-Arrow"); time = test_script->public_ints.at("Button Cooldown"); c_players_vote[0] = (ComponentUiButton*)players_vote[0]->GetComponent(C_UI_BUTTON); c_players_vote[1] = (ComponentUiButton*)players_vote[1]->GetComponent(C_UI_BUTTON); c_players_vote[2] = (ComponentUiButton*)players_vote[2]->GetComponent(C_UI_BUTTON); c_players_vote[3] = (ComponentUiButton*)players_vote[3]->GetComponent(C_UI_BUTTON); c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON); c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON); } void MapSelectUI_ActualizePublics(GameObject* game_object) { ComponentScript* this_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT); this_script->public_gos.at("Map Fields") = map_fields; this_script->public_gos.at("Map Umi") = map_umi; this_script->public_gos.at("Map Ricing") = map_ricing; this_script->public_gos.at("P1-Blue Vote") = players_vote[0]; this_script->public_gos.at("P2-Blue Vote") = players_vote[1]; this_script->public_gos.at("P1-Red Vote") = players_vote[2]; this_script->public_gos.at("P2-Red Vote") = players_vote[3]; this_script->public_gos.at("R-Arrow") = right_arrow; this_script->public_gos.at("L-Arrow") = left_arrow; this_script->public_ints.at("Button Cooldown") = time; c_players_vote[0] = (ComponentUiButton*)players_vote[0]->GetComponent(C_UI_BUTTON); c_players_vote[1] = (ComponentUiButton*)players_vote[1]->GetComponent(C_UI_BUTTON); c_players_vote[2] = (ComponentUiButton*)players_vote[2]->GetComponent(C_UI_BUTTON); c_players_vote[3] = (ComponentUiButton*)players_vote[3]->GetComponent(C_UI_BUTTON); c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON); c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON); } void MapSelectUI_UpdatePublics(GameObject* game_object); void MapSelectUI_Start(GameObject* game_object) { // Play Move Selection ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE); if (a_comp) a_comp->PlayAudio(0); arrow_counter_left = time; arrow_counter_right = time; current_map = 0; current_level = 0; player_order[0] = App->go_manager->team1_front; player_order[1] = App->go_manager->team1_back; player_order[2] = App->go_manager->team2_front; player_order[3] = App->go_manager->team2_back; } void MapSelectUI_Update(GameObject* game_object) { for (int playerID = 0; playerID < 4; playerID++) { int id = 0; for (int j = 0; j < 4; j++) { if (player_order[j] == playerID) { id = j; } } if (App->input->GetJoystickButton(playerID, JOY_BUTTON::A) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_A) == KEY_DOWN) { if (!players_ready[id]) { c_players_vote[id]->OnPressId(current_level); // TO BE TESTED votes[id] = current_level; players_ready[id] = true; } } if (App->input->GetJoystickButton(playerID, JOY_BUTTON::B) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_B) == KEY_DOWN) { if (players_ready[id]) { c_players_vote[id]->OnPressId(votes[id]); // TO BE TESTED players_ready[id] = false; } } if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_LEFT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_DOWN) { // Play Move Selection ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE); if (a_comp) a_comp->PlayAudio(1); current_level--; if (current_level < 0) current_level = 2; switch (current_level) { case 0: map_fields->SetActive(true); map_umi->SetActive(false); map_ricing->SetActive(false); break; case 1: map_fields->SetActive(false); map_umi->SetActive(true); map_ricing->SetActive(false); break; case 2: map_fields->SetActive(false); map_umi->SetActive(false); map_ricing->SetActive(true); break; } if (arrow_counter_left >= time) { c_left_arrow->OnPress(); } arrow_counter_left = 0; } if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_RIGHT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_DOWN) { // Play Move Selection ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE); if (a_comp) a_comp->PlayAudio(1); current_level++; if (current_level > 2) current_level = 0; switch (current_level) { case 0: map_fields->SetActive(true); map_umi->SetActive(false); map_ricing->SetActive(false); break; case 1: map_fields->SetActive(false); map_umi->SetActive(true); map_ricing->SetActive(false); break; case 2: map_fields->SetActive(false); map_umi->SetActive(false); map_ricing->SetActive(true); break; } if (arrow_counter_right >= time) { c_right_arrow->OnPress(); } arrow_counter_right = 0; } } if (arrow_counter_left < time) { arrow_counter_left++; if (arrow_counter_left == time) c_left_arrow->OnPress(); } if (arrow_counter_right < time) { arrow_counter_right++; if (arrow_counter_right == time) c_right_arrow->OnPress(); } int total = 0; for (int j = 0; j < 4; j++) { if (players_ready[j]) total++; if (total == 4) { unsigned int k = App->rnd->RandomInt(1, 4); switch (votes[k]) { case 1: App->LoadScene(path_map1.data()); break; case 2: App->LoadScene(path_map2.data()); break; case 3: App->LoadScene(path_map3.data()); break; default: // Error Reset, but loads map 1 instead (because we need to cover bugs lol lmao pls don't kill me) App->LoadScene(path_map1.data()); break; } } else total = 0; // Redundancy } } void MapSelectUI_OnFocus() { } }
#include "stdafx.h" #include <string> #include <map> #include <vector> #include "../Application.h" #include "../ModuleScripting.h" #include "../ModuleInput.h" #include "../ModuleWindow.h" #include "../ComponentTransform.h" #include "../ModuleGOManager.h" #include "../GameObject.h" #include "../Component.h" #include "../ComponentScript.h" #include "../ComponentRectTransform.h" #include "../SDL/include/SDL_scancode.h" #include "../Globals.h" #include "../ComponentUiButton.h" #include "../ComponentCanvas.h" #include "../ModuleResourceManager.h" #include "../Random.h" #include "../Time.h" #include "../ComponentAudioSource.h" namespace MapSelectUI { GameObject* map_fields = nullptr; GameObject* map_umi = nullptr; GameObject* map_ricing = nullptr; GameObject* players_vote[4]; GameObject* right_arrow = nullptr; GameObject* left_arrow = nullptr; ComponentUiButton* c_players_vote[4]; // 0 - P1 Red, 1 - P2 Red, 2 - P1 Blue, 2 - P2 Blue, ComponentUiButton* c_right_arrow = nullptr; ComponentUiButton* c_left_arrow = nullptr; string path_map1 = "/Assets/Scene_Map_1/Scene_Map_1.ezx"; string path_map2 = "/Assets/Scene_Map_2/Scene_Map_2.ezx"; string path_map3 = "/Assets/Scene_Map_3/Scene_Map_3.ezx"; bool players_ready[4] = { false, false, false, false }; bool a_pressed = false; bool b_pressed = false; bool dpad_left_pressed = false; bool dpad_right_pressed = false; int current_level = 0; int current_map = 0; // 1 - , 2 - , 3 - , int votes[4] = { 0, 0, 0, 0 }; int arrow_counter_left = 30; int arrow_counter_right = 30; int time = 30; int player_order[4]; void MapSelectUI_GetPublics(map<const char*, string>* public_chars, map<const char*, int>* public_ints, map<const char*, float>* public_float, map<const char*, bool>* public_bools, map<const char*, GameObject*>* public_gos) { public_gos->insert(std::pair<const char*, GameObject*>("Map Fields", map_fields)); public_gos->insert(std::pair<const char*, GameObject*>("Map Umi", map_umi)); public_gos->insert(std::pair<const char*, GameObject*>("Map Ricing", map_ricing)); public_gos->insert(std::pair<const char*, GameObject*>("P1-Red Vote", players_vote[2])); public_gos->insert(std::pair<const char*, GameObject*>("P2-Red Vote", players_vote[3])); public_gos->insert(std::pair<const char*, GameObject*>("P1-Blue Vote", players_vote[0])); public_gos->insert(std::pair<const char*, GameObject*>("P2-Blue Vote", players_vote[1])); public_gos->insert(std::pair<const char*, GameObject*>("R-Arrow", right_arrow)); public_gos->insert(std::pair<const char*, GameObject*>("L-Arrow", left_arrow)); public_ints->insert(std::pair<const char*, int>("Button Cooldown", time)); } void MapSelectUI_UpdatePublics(GameObject* game_object) { ComponentScript* test_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT); map_fields = test_script->public_gos.at("Map Fields"); map_umi = test_script->public_gos.at("Map Umi"); map_ricing = test_script->public_gos.at("Map Ricing"); players_vote[0] = test_script->public_gos.at("P1-Blue Vote"); players_vote[1] = test_script->public_gos.at("P2-Blue Vote"); players_vote[2] = test_script->public_gos.at("P1-Red Vote"); players_vote[3] = test_script->public_gos.at("P2-Red Vote"); right_arrow = test_script->public_gos.at("R-Arrow"); left_arrow = test_script->public_gos.at("L-Arrow"); time = test_script->public_ints.at("Button Cooldown"); c_players_vote[0] = (ComponentUiButton*)players_vote[0]->GetComponent(C_UI_BUTTON); c_players_vote[1] = (ComponentUiButton*)players_vote[1]->GetComponent(C_UI_BUTTON); c_players_vote[2] = (ComponentUiButton*)players_vote[2]->GetComponent(C_UI_BUTTON); c_players_vote[3] = (ComponentUiButton*)players_vote[3]->GetComponent(C_UI_BUTTON); c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON); c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON); } void MapSelectUI_ActualizePublics(GameObject* game_object) { ComponentScript* this_script = (ComponentScript*)game_object->GetComponent(ComponentType::C_SCRIPT); this_script->public_gos.at("Map Fields") = map_fields; this_script->public_gos.at("Map Umi") = map_umi; this_script->public_gos.at("Map Ricing") = map_ricing; this_script->public_gos.at("P1-Blue Vote") = players_vote[0]; this_script->public_gos.at("P2-Blue Vote") = players_vote[1]; this_script->public_gos.at("P1-Red Vote") = players_vote[2]; this_script->public_gos.at("P2-Red Vote") = players_vote[3]; this_script->public_gos.at("R-Arrow") = right_arrow; this_script->public_gos.at("L-Arrow") = left_arrow; this_script->public_ints.at("Button Cooldown") = time; c_players_vote[0] = (ComponentUiButton*)players_vote[0]->GetComponent(C_UI_BUTTON); c_players_vote[1] = (ComponentUiButton*)players_vote[1]->GetComponent(C_UI_BUTTON); c_players_vote[2] = (ComponentUiButton*)players_vote[2]->GetComponent(C_UI_BUTTON); c_players_vote[3] = (ComponentUiButton*)players_vote[3]->GetComponent(C_UI_BUTTON); c_right_arrow = (ComponentUiButton*)right_arrow->GetComponent(C_UI_BUTTON); c_left_arrow = (ComponentUiButton*)left_arrow->GetComponent(C_UI_BUTTON); } void MapSelectUI_UpdatePublics(GameObject* game_object); void MapSelectUI_Start(GameObject* game_object) { // Play Move Selection ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE); if (a_comp) a_comp->PlayAudio(0); arrow_counter_left = time; arrow_counter_right = time; current_map = 0; current_level = 0; player_order[0] = App->go_manager->team1_front; player_order[1] = App->go_manager->team1_back; player_order[2] = App->go_manager->team2_front; player_order[3] = App->go_manager->team2_back; } void MapSelectUI_Update(GameObject* game_object) { for (int playerID = 0; playerID < 4; playerID++) { int id = 0; for (int j = 0; j < 4; j++) { if (player_order[j] == playerID) { id = j; } } if (App->input->GetJoystickButton(playerID, JOY_BUTTON::A) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_A) == KEY_DOWN) { if (!players_ready[id]) { c_players_vote[id]->OnPressId(current_level); // TO BE TESTED votes[id] = current_level; players_ready[id] = true; } } if (App->input->GetJoystickButton(playerID, JOY_BUTTON::B) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_B) == KEY_DOWN) { if (players_ready[id]) { c_players_vote[id]->OnPressId(votes[id]); // TO BE TESTED players_ready[id] = false; } } if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_LEFT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_DOWN) { // Play Move Selection ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE); if (a_comp) a_comp->PlayAudio(1); current_level--; if (current_level < 0) current_level = 2; switch (current_level) { case 0: map_fields->SetActive(true); map_umi->SetActive(false); map_ricing->SetActive(false); break; case 1: map_fields->SetActive(false); map_umi->SetActive(true); map_ricing->SetActive(false); break; case 2: map_fields->SetActive(false); map_umi->SetActive(false); map_ricing->SetActive(true); break; } if (arrow_counter_left >= time) { c_left_arrow->OnPress(); } arrow_counter_left = 0; } if (App->input->GetJoystickButton(playerID, JOY_BUTTON::DPAD_RIGHT) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_DOWN) { // Play Move Selection ComponentAudioSource *a_comp = (ComponentAudioSource*)game_object->GetComponent(ComponentType::C_AUDIO_SOURCE); if (a_comp) a_comp->PlayAudio(1); current_level++; if (current_level > 2) current_level = 0; switch (current_level) { case 0: map_fields->SetActive(true); map_umi->SetActive(false); map_ricing->SetActive(false); break; case 1: map_fields->SetActive(false); map_umi->SetActive(true); map_ricing->SetActive(false); break; case 2: map_fields->SetActive(false); map_umi->SetActive(false); map_ricing->SetActive(true); break; } if (arrow_counter_right >= time) { c_right_arrow->OnPress(); } arrow_counter_right = 0; } } if (arrow_counter_left < time) { arrow_counter_left++; if (arrow_counter_left == time) c_left_arrow->OnPress(); } if (arrow_counter_right < time) { arrow_counter_right++; if (arrow_counter_right == time) c_right_arrow->OnPress(); } int total = 0; for (int j = 0; j < 4; j++) { if (players_ready[j]) total++; if (total == 4) { unsigned int k = App->rnd->RandomInt(1, 4); switch (votes[k]) { case 1: App->LoadScene(path_map1.data()); break; case 2: App->LoadScene(path_map2.data()); break; case 3: App->LoadScene(path_map3.data()); break; default: // Error Reset, but loads map 1 instead (because we need to cover bugs lol lmao pls don't kill me) App->LoadScene(path_map1.data()); break; } } } } void MapSelectUI_OnFocus() { } }
Correct Path!
Correct Path!
C++
mit
CITMProject3/Project3,CITMProject3/Project3,CITMProject3/Project3,CITMProject3/Project3
3bfe8da6b6a96da626b5b7d9afd2cfc541530939
src/world/GMTicket.cpp
src/world/GMTicket.cpp
/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (C) 2014-2015 AscEmu Team <http://www.ascemu.org/> * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/> * Copyright (C) 2005-2007 Ascent Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "StdAfx.h" enum GMticketType { GM_TICKET_TYPE_STUCK = 1, GM_TICKET_TYPE_BEHAVIOR_HARASSMENT = 2, GM_TICKET_TYPE_GUILD = 3, GM_TICKET_TYPE_ITEM = 4, GM_TICKET_TYPE_ENVIRONMENTAL = 5, GM_TICKET_TYPE_NON_QUEST_CREEP = 6, GM_TICKET_TYPE_QUEST_QUEST_NPC = 7, GM_TICKET_TYPE_TECHNICAL = 8, GM_TICKET_TYPE_ACCOUNT_BILLING = 9, GM_TICKET_TYPE_CHARACTER = 10, }; enum LagReportType { LAP_REPORT_LOOT, LAP_REPORT_AH, LAP_REPORT_MAIL, LAP_REPORT_CHAT, LAP_REPORT_MOVEMENT, LAP_REPORT_SPELLS }; void WorldSession::HandleGMTicketCreateOpcode(WorldPacket& recv_data) { CHECK_INWORLD_RETURN uint32 map; float x, y, z; std::string message = ""; std::string message2 = ""; GM_Ticket* ticket = new GM_Ticket; WorldPacket data(SMSG_GMTICKET_CREATE, 4); // recv Data recv_data >> map; recv_data >> x; recv_data >> y; recv_data >> z; recv_data >> message; recv_data >> message2; // Remove pending tickets objmgr.RemoveGMTicketByPlayer(GetPlayer()->GetGUID()); ticket->guid = uint64(objmgr.GenerateTicketID()); ticket->playerGuid = GetPlayer()->GetGUID(); ticket->map = map; ticket->posX = x; ticket->posY = y; ticket->posZ = z; ticket->message = message; ticket->timestamp = (uint32)UNIXTIME; ticket->name = GetPlayer()->GetName(); ticket->level = GetPlayer()->getLevel(); ticket->deleted = false; ticket->assignedToPlayer = 0; ticket->comment = ""; // Add a new one objmgr.AddGMTicket(ticket, false); // Response - no errors data << uint32(2); SendPacket(&data); // send message indicating new ticket Channel* chn = channelmgr.GetChannel(sWorld.getGmClientChannel().c_str(), GetPlayer()); if (chn) { std::stringstream ss; #ifdef GM_TICKET_MY_MASTER_COMPATIBLE ss << "GmTicket 5, " << ticket->name; #else ss << "GmTicket:" << GM_TICKET_CHAT_OPCODE_NEWTICKET; ss << ":" << ticket->guid; ss << ":" << ticket->level; ss << ":" << ticket->name; #endif chn->Say(_player, ss.str().c_str(), NULL, true); } } void WorldSession::HandleGMTicketUpdateOpcode(WorldPacket& recv_data) { CHECK_INWORLD_RETURN std::string message = ""; WorldPacket data(SMSG_GMTICKET_UPDATETEXT, 4); // recv Data recv_data >> message; // Update Ticket GM_Ticket* ticket = objmgr.GetGMTicketByPlayer(GetPlayer()->GetGUID()); if (!ticket) // Player doesn't have a GM Ticket yet { // Response - error couldn't find existing Ticket data << uint32(1); SendPacket(&data); return; } ticket->message = message; ticket->timestamp = (uint32)UNIXTIME; objmgr.UpdateGMTicket(ticket); // Response - no errors data << uint32(2); SendPacket(&data); #ifndef GM_TICKET_MY_MASTER_COMPATIBLE Channel* chn = channelmgr.GetChannel(sWorld.getGmClientChannel().c_str(), GetPlayer()); if (chn) { std::stringstream ss; ss << "GmTicket:" << GM_TICKET_CHAT_OPCODE_UPDATED; ss << ":" << ticket->guid; chn->Say(_player, ss.str().c_str(), NULL, true); } #endif } void WorldSession::HandleGMTicketDeleteOpcode(WorldPacket& recv_data) { CHECK_INWORLD_RETURN GM_Ticket* ticket = objmgr.GetGMTicketByPlayer(GetPlayer()->GetGUID()); // Remove Tickets from Player objmgr.RemoveGMTicketByPlayer(GetPlayer()->GetGUID()); // Response - no errors WorldPacket data(SMSG_GMTICKET_DELETETICKET, 4); data << uint32(9); SendPacket(&data); // send message to gm_sync_chan Channel* chn = channelmgr.GetChannel(sWorld.getGmClientChannel().c_str(), GetPlayer()); if (chn && ticket != NULL) { std::stringstream ss; #ifdef GM_TICKET_MY_MASTER_COMPATIBLE ss << "GmTicket 1," << ticket->name; #else ss << "GmTicket:" << GM_TICKET_CHAT_OPCODE_REMOVED; ss << ":" << ticket->guid; #endif chn->Say(_player, ss.str().c_str(), NULL, true); } } void WorldSession::HandleGMTicketGetTicketOpcode(WorldPacket& recv_data) { CHECK_INWORLD_RETURN WorldPacket data(SMSG_GMTICKET_GETTICKET, 400); // no data // get Current Ticket GM_Ticket* ticket = objmgr.GetGMTicketByPlayer(GetPlayer()->GetGUID()); if (!ticket) // no Current Ticket { data << uint32(10); SendPacket(&data); return; } // Send current Ticket data << uint32(6); // unk data << ticket->message.c_str(); data << (uint8)ticket->map; SendPacket(&data); } void WorldSession::HandleGMTicketSystemStatusOpcode(WorldPacket& recv_data) { WorldPacket data(SMSG_GMTICKET_SYSTEMSTATUS, 4); // no data // Response - System is working Fine if (sWorld.getGMTicketStatus()) data << uint32(1); else data << uint32(0); SendPacket(&data); } void WorldSession::HandleGMTicketToggleSystemStatusOpcode(WorldPacket& recv_data) { if (!HasGMPermissions()) return; sWorld.toggleGMTicketStatus(); } void WorldSession::HandleReportLag(WorldPacket& recv_data) { uint32 lagType; uint32 mapId; float position_x; float position_y; float position_z; recv_data >> lagType; recv_data >> mapId; recv_data >> position_x; recv_data >> position_y; recv_data >> position_z; if (GetPlayer() != nullptr) { CharacterDatabase.Execute("INSERT INTO lag_reports (player, account, lag_type, map_id, position_x, position_y, position_z) VALUES(%u, %u, %u, %u, %f, %f, %f)", GetPlayer()->GetLowGUID(), _accountId, lagType, mapId, position_x, position_y, position_z); } Log.Debug("HandleReportLag", "Player %s has reported a lagreport with Type: %u on Map: %u", GetPlayer()->GetName(), lagType, mapId); }
/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (C) 2014-2015 AscEmu Team <http://www.ascemu.org/> * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/> * Copyright (C) 2005-2007 Ascent Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "StdAfx.h" enum GMticketType { GM_TICKET_TYPE_STUCK = 1, GM_TICKET_TYPE_BEHAVIOR_HARASSMENT = 2, GM_TICKET_TYPE_GUILD = 3, GM_TICKET_TYPE_ITEM = 4, GM_TICKET_TYPE_ENVIRONMENTAL = 5, GM_TICKET_TYPE_NON_QUEST_CREEP = 6, GM_TICKET_TYPE_QUEST_QUEST_NPC = 7, GM_TICKET_TYPE_TECHNICAL = 8, GM_TICKET_TYPE_ACCOUNT_BILLING = 9, GM_TICKET_TYPE_CHARACTER = 10 }; enum LagReportType { LAG_REPORT_LOOT, LAG_REPORT_AH, LAG_REPORT_MAIL, LAG_REPORT_CHAT, LAG_REPORT_MOVEMENT, LAG_REPORT_SPELLS }; void WorldSession::HandleGMTicketCreateOpcode(WorldPacket& recv_data) { CHECK_INWORLD_RETURN uint32 map; float x, y, z; std::string message = ""; std::string message2 = ""; GM_Ticket* ticket = new GM_Ticket; WorldPacket data(SMSG_GMTICKET_CREATE, 4); // recv Data recv_data >> map; recv_data >> x; recv_data >> y; recv_data >> z; recv_data >> message; recv_data >> message2; // Remove pending tickets objmgr.RemoveGMTicketByPlayer(GetPlayer()->GetGUID()); ticket->guid = uint64(objmgr.GenerateTicketID()); ticket->playerGuid = GetPlayer()->GetGUID(); ticket->map = map; ticket->posX = x; ticket->posY = y; ticket->posZ = z; ticket->message = message; ticket->timestamp = (uint32)UNIXTIME; ticket->name = GetPlayer()->GetName(); ticket->level = GetPlayer()->getLevel(); ticket->deleted = false; ticket->assignedToPlayer = 0; ticket->comment = ""; // Add a new one objmgr.AddGMTicket(ticket, false); // Response - no errors data << uint32(2); SendPacket(&data); // send message indicating new ticket Channel* chn = channelmgr.GetChannel(sWorld.getGmClientChannel().c_str(), GetPlayer()); if (chn) { std::stringstream ss; #ifdef GM_TICKET_MY_MASTER_COMPATIBLE ss << "GmTicket 5, " << ticket->name; #else ss << "GmTicket:" << GM_TICKET_CHAT_OPCODE_NEWTICKET; ss << ":" << ticket->guid; ss << ":" << ticket->level; ss << ":" << ticket->name; #endif chn->Say(_player, ss.str().c_str(), NULL, true); } } void WorldSession::HandleGMTicketUpdateOpcode(WorldPacket& recv_data) { CHECK_INWORLD_RETURN std::string message = ""; WorldPacket data(SMSG_GMTICKET_UPDATETEXT, 4); // recv Data recv_data >> message; // Update Ticket GM_Ticket* ticket = objmgr.GetGMTicketByPlayer(GetPlayer()->GetGUID()); if (!ticket) // Player doesn't have a GM Ticket yet { // Response - error couldn't find existing Ticket data << uint32(1); SendPacket(&data); return; } ticket->message = message; ticket->timestamp = (uint32)UNIXTIME; objmgr.UpdateGMTicket(ticket); // Response - no errors data << uint32(2); SendPacket(&data); #ifndef GM_TICKET_MY_MASTER_COMPATIBLE Channel* chn = channelmgr.GetChannel(sWorld.getGmClientChannel().c_str(), GetPlayer()); if (chn) { std::stringstream ss; ss << "GmTicket:" << GM_TICKET_CHAT_OPCODE_UPDATED; ss << ":" << ticket->guid; chn->Say(_player, ss.str().c_str(), NULL, true); } #endif } void WorldSession::HandleGMTicketDeleteOpcode(WorldPacket& recv_data) { CHECK_INWORLD_RETURN GM_Ticket* ticket = objmgr.GetGMTicketByPlayer(GetPlayer()->GetGUID()); // Remove Tickets from Player objmgr.RemoveGMTicketByPlayer(GetPlayer()->GetGUID()); // Response - no errors WorldPacket data(SMSG_GMTICKET_DELETETICKET, 4); data << uint32(9); SendPacket(&data); // send message to gm_sync_chan Channel* chn = channelmgr.GetChannel(sWorld.getGmClientChannel().c_str(), GetPlayer()); if (chn && ticket != NULL) { std::stringstream ss; #ifdef GM_TICKET_MY_MASTER_COMPATIBLE ss << "GmTicket 1," << ticket->name; #else ss << "GmTicket:" << GM_TICKET_CHAT_OPCODE_REMOVED; ss << ":" << ticket->guid; #endif chn->Say(_player, ss.str().c_str(), NULL, true); } } void WorldSession::HandleGMTicketGetTicketOpcode(WorldPacket& recv_data) { CHECK_INWORLD_RETURN WorldPacket data(SMSG_GMTICKET_GETTICKET, 400); // no data // get Current Ticket GM_Ticket* ticket = objmgr.GetGMTicketByPlayer(GetPlayer()->GetGUID()); if (!ticket) // no Current Ticket { data << uint32(10); SendPacket(&data); return; } // Send current Ticket data << uint32(6); // unk data << ticket->message.c_str(); data << (uint8)ticket->map; SendPacket(&data); } void WorldSession::HandleGMTicketSystemStatusOpcode(WorldPacket& recv_data) { WorldPacket data(SMSG_GMTICKET_SYSTEMSTATUS, 4); // no data // Response - System is working Fine if (sWorld.getGMTicketStatus()) data << uint32(1); else data << uint32(0); SendPacket(&data); } void WorldSession::HandleGMTicketToggleSystemStatusOpcode(WorldPacket& recv_data) { if (!HasGMPermissions()) return; sWorld.toggleGMTicketStatus(); } void WorldSession::HandleReportLag(WorldPacket& recv_data) { uint32 lagType; uint32 mapId; float position_x; float position_y; float position_z; recv_data >> lagType; recv_data >> mapId; recv_data >> position_x; recv_data >> position_y; recv_data >> position_z; if (GetPlayer() != nullptr) { CharacterDatabase.Execute("INSERT INTO lag_reports (player, account, lag_type, map_id, position_x, position_y, position_z) VALUES(%u, %u, %u, %u, %f, %f, %f)", GetPlayer()->GetLowGUID(), _accountId, lagType, mapId, position_x, position_y, position_z); } Log.Debug("HandleReportLag", "Player %s has reported a lagreport with Type: %u on Map: %u", GetPlayer()->GetName(), lagType, mapId); }
Rename enum LagReportType members LAP -> LAG
Rename enum LagReportType members LAP -> LAG
C++
agpl-3.0
Appled/AscEmu,master312/AscEmu,master312/AscEmu,master312/AscEmu,Appled/AscEmu,AscEmu/AscEmu,Appled/AscEmu,master312/AscEmu,master312/AscEmu,master312/AscEmu,AscEmu/AscEmu,AscEmu/AscEmu
8b48ca0b23b6274d5af2c455c897065e6438f09d
examples_tests/06.MeshLoaders/main.cpp
examples_tests/06.MeshLoaders/main.cpp
#define _IRR_STATIC_LIB_ #include <irrlicht.h> #include "../ext/ScreenShot/ScreenShot.h" #include "../common/QToQuitEventReceiver.h" // TODO: remove dependency #include "../src/irr/asset/CBAWMeshWriter.h" using namespace irr; using namespace core; class SimpleCallBack : public video::IShaderConstantSetCallBack { int32_t mvpUniformLocation; int32_t cameraDirUniformLocation; int32_t texUniformLocation[4]; video::E_SHADER_CONSTANT_TYPE mvpUniformType; video::E_SHADER_CONSTANT_TYPE cameraDirUniformType; video::E_SHADER_CONSTANT_TYPE texUniformType[4]; public: SimpleCallBack() : cameraDirUniformLocation(-1), cameraDirUniformType(video::ESCT_FLOAT_VEC3) {} virtual void PostLink(video::IMaterialRendererServices* services, const video::E_MATERIAL_TYPE& materialType, const core::vector<video::SConstantLocationNamePair>& constants) { for (size_t i=0; i<constants.size(); i++) { if (constants[i].name=="MVP") { mvpUniformLocation = constants[i].location; mvpUniformType = constants[i].type; } else if (constants[i].name=="cameraPos") { cameraDirUniformLocation = constants[i].location; cameraDirUniformType = constants[i].type; } } } virtual void OnSetConstants(video::IMaterialRendererServices* services, int32_t userData) { core::vectorSIMDf modelSpaceCamPos; modelSpaceCamPos.set(services->getVideoDriver()->getTransform(video::E4X3TS_WORLD_VIEW_INVERSE).getTranslation()); services->setShaderConstant(&modelSpaceCamPos,cameraDirUniformLocation,cameraDirUniformType,1); services->setShaderConstant(services->getVideoDriver()->getTransform(video::EPTS_PROJ_VIEW_WORLD).pointer(),mvpUniformLocation,mvpUniformType,1); } virtual void OnUnsetMaterial() {} }; int main() { srand(time(0)); // create device with full flexibility over creation parameters // you can add more parameters if desired, check irr::SIrrlichtCreationParameters irr::SIrrlichtCreationParameters params; params.Bits = 24; //may have to set to 32bit for some platforms params.ZBufferBits = 24; //we'd like 32bit here params.DriverType = video::EDT_OPENGL; //! Only Well functioning driver, software renderer left for sake of 2D image drawing params.WindowSize = dimension2d<uint32_t>(1280, 720); params.Fullscreen = false; params.Vsync = true; //! If supported by target platform params.Doublebuffer = true; params.Stencilbuffer = false; //! This will not even be a choice soon IrrlichtDevice* device = createDeviceEx(params); if (device == 0) return 1; // could not create selected driver. device->getCursorControl()->setVisible(false); QToQuitEventReceiver receiver; device->setEventReceiver(&receiver); video::IVideoDriver* driver = device->getVideoDriver(); SimpleCallBack* cb = new SimpleCallBack(); video::E_MATERIAL_TYPE newMaterialType = (video::E_MATERIAL_TYPE)driver->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles("../mesh.vert", "","","", //! No Geometry or Tessellation Shaders "../mesh.frag", 3,video::EMT_SOLID, //! 3 vertices per primitive (this is tessellation shader relevant only cb, //! Our Shader Callback 0); //! No custom user data cb->drop(); scene::ISceneManager* smgr = device->getSceneManager(); driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true); scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS(0,100.0f,0.01f); camera->setPosition(core::vector3df(-4,0,0)); camera->setTarget(core::vector3df(0,0,0)); camera->setNearValue(0.01f); camera->setFarValue(100.0f); smgr->setActiveCamera(camera); io::IFileSystem* fs = device->getFileSystem(); // from Criss: // here i'm testing baw mesh writer and loader // (import from .stl/.obj, then export to .baw, then import from .baw :D) // Seems to work for those two simple meshes, but need more testing! auto am = device->getAssetManager(); //! Test Loading of Obj asset::IAssetLoader::SAssetLoadParams lparams; auto cpumesh = core::smart_refctd_ptr_static_cast<asset::ICPUMesh>(*am->getAsset("../../media/extrusionLogo_TEST_fixed.stl", lparams).getContents().first); // export mesh asset::CBAWMeshWriter::WriteProperties bawprops; asset::IAssetWriter::SAssetWriteParams wparams(cpumesh.get(), asset::EWF_COMPRESSED, 0.f, 0, nullptr, &bawprops); am->writeAsset("extrusionLogo_TEST_fixed.baw", wparams); // end export // import .baw mesh (test) cpumesh = core::smart_refctd_ptr_static_cast<asset::ICPUMesh>(*am->getAsset("extrusionLogo_TEST_fixed.baw", lparams).getContents().first); // end import if (cpumesh) smgr->addMeshSceneNode(std::move(driver->getGPUObjectsFromAssets(&cpumesh.get(), (&cpumesh.get())+1)[0]))->setMaterialType(newMaterialType); cpumesh = core::smart_refctd_ptr_static_cast<asset::ICPUMesh>(*am->getAsset("../../media/cow.obj", lparams).getContents().first); // export mesh wparams.rootAsset = cpumesh.get(); am->writeAsset("cow.baw", wparams); // end export // import .baw mesh (test) cpumesh = core::smart_refctd_ptr_static_cast<asset::ICPUMesh>(*am->getAsset("cow.baw", lparams).getContents().first); // end import if (cpumesh) smgr->addMeshSceneNode(std::move(driver->getGPUObjectsFromAssets(&cpumesh.get(), (&cpumesh.get())+1)[0]),0,-1,core::vector3df(3.f,1.f,0.f))->setMaterialType(newMaterialType); uint64_t lastFPSTime = 0; while(device->run() && receiver.keepOpen() ) //if (device->isWindowActive()) { driver->beginScene(true, true, video::SColor(255,0,0,255) ); //! This animates (moves) the camera and sets the transforms //! Also draws the meshbuffer smgr->drawAll(); driver->endScene(); // display frames per second in window title uint64_t time = device->getTimer()->getRealTime(); if (time-lastFPSTime > 1000) { std::wostringstream sstr; sstr << L"Builtin Nodes Demo - Irrlicht Engine FPS:" << driver->getFPS() << " PrimitvesDrawn:" << driver->getPrimitiveCountDrawn(); device->setWindowCaption(sstr.str().c_str()); lastFPSTime = time; } } //create a screenshot { core::rect<uint32_t> sourceRect(0, 0, params.WindowSize.Width, params.WindowSize.Height); ext::ScreenShot::dirtyCPUStallingScreenshot(device, "screenshot.png", sourceRect, asset::EF_R8G8B8_SRGB); } device->drop(); return 0; }
#define _IRR_STATIC_LIB_ #include <irrlicht.h> #include "../ext/ScreenShot/ScreenShot.h" #include "../common/QToQuitEventReceiver.h" // TODO: remove dependency #include "../src/irr/asset/CBAWMeshWriter.h" using namespace irr; using namespace core; class SimpleCallBack : public video::IShaderConstantSetCallBack { int32_t mvpUniformLocation; int32_t cameraDirUniformLocation; int32_t texUniformLocation[4]; video::E_SHADER_CONSTANT_TYPE mvpUniformType; video::E_SHADER_CONSTANT_TYPE cameraDirUniformType; video::E_SHADER_CONSTANT_TYPE texUniformType[4]; public: SimpleCallBack() : cameraDirUniformLocation(-1), cameraDirUniformType(video::ESCT_FLOAT_VEC3) {} virtual void PostLink(video::IMaterialRendererServices* services, const video::E_MATERIAL_TYPE& materialType, const core::vector<video::SConstantLocationNamePair>& constants) { for (size_t i=0; i<constants.size(); i++) { if (constants[i].name=="MVP") { mvpUniformLocation = constants[i].location; mvpUniformType = constants[i].type; } else if (constants[i].name=="cameraPos") { cameraDirUniformLocation = constants[i].location; cameraDirUniformType = constants[i].type; } } } virtual void OnSetConstants(video::IMaterialRendererServices* services, int32_t userData) { core::vectorSIMDf modelSpaceCamPos; modelSpaceCamPos.set(services->getVideoDriver()->getTransform(video::E4X3TS_WORLD_VIEW_INVERSE).getTranslation()); services->setShaderConstant(&modelSpaceCamPos,cameraDirUniformLocation,cameraDirUniformType,1); services->setShaderConstant(services->getVideoDriver()->getTransform(video::EPTS_PROJ_VIEW_WORLD).pointer(),mvpUniformLocation,mvpUniformType,1); } virtual void OnUnsetMaterial() {} }; int main() { srand(time(0)); // create device with full flexibility over creation parameters // you can add more parameters if desired, check irr::SIrrlichtCreationParameters irr::SIrrlichtCreationParameters params; params.Bits = 24; //may have to set to 32bit for some platforms params.ZBufferBits = 24; //we'd like 32bit here params.DriverType = video::EDT_OPENGL; //! Only Well functioning driver, software renderer left for sake of 2D image drawing params.WindowSize = dimension2d<uint32_t>(1280, 720); params.Fullscreen = false; params.Vsync = true; //! If supported by target platform params.Doublebuffer = true; params.Stencilbuffer = false; //! This will not even be a choice soon IrrlichtDevice* device = createDeviceEx(params); if (device == 0) return 1; // could not create selected driver. device->getCursorControl()->setVisible(false); QToQuitEventReceiver receiver; device->setEventReceiver(&receiver); video::IVideoDriver* driver = device->getVideoDriver(); SimpleCallBack* cb = new SimpleCallBack(); video::E_MATERIAL_TYPE newMaterialType = (video::E_MATERIAL_TYPE)driver->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles("../mesh.vert", "","","", //! No Geometry or Tessellation Shaders "../mesh.frag", 3,video::EMT_SOLID, //! 3 vertices per primitive (this is tessellation shader relevant only cb, //! Our Shader Callback 0); //! No custom user data cb->drop(); scene::ISceneManager* smgr = device->getSceneManager(); driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true); scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS(0,100.0f,0.01f); camera->setPosition(core::vector3df(-4,0,0)); camera->setTarget(core::vector3df(0,0,0)); camera->setNearValue(0.01f); camera->setFarValue(100.0f); smgr->setActiveCamera(camera); io::IFileSystem* fs = device->getFileSystem(); // from Criss: // here i'm testing baw mesh writer and loader // (import from .stl/.obj, then export to .baw, then import from .baw :D) // Seems to work for those two simple meshes, but need more testing! auto am = device->getAssetManager(); //! Test Loading of Obj asset::IAssetLoader::SAssetLoadParams lparams; auto cpumesh = core::smart_refctd_ptr_static_cast<asset::ICPUMesh>(*am->getAsset("../../media/extrusionLogo_TEST_fixed.stl", lparams).getContents().first); // export mesh asset::CBAWMeshWriter::WriteProperties bawprops; asset::IAssetWriter::SAssetWriteParams wparams(cpumesh.get(), asset::EWF_COMPRESSED, 0.f, 0, nullptr, &bawprops); am->writeAsset("extrusionLogo_TEST_fixed.baw", wparams); // end export // import .baw mesh (test) cpumesh = core::smart_refctd_ptr_static_cast<asset::ICPUMesh>(*am->getAsset("extrusionLogo_TEST_fixed.baw", lparams).getContents().first); // end import if (cpumesh) smgr->addMeshSceneNode(std::move(driver->getGPUObjectsFromAssets(&cpumesh.get(), (&cpumesh.get())+1)->operator[](0)))->setMaterialType(newMaterialType); cpumesh = core::smart_refctd_ptr_static_cast<asset::ICPUMesh>(*am->getAsset("../../media/cow.obj", lparams).getContents().first); // export mesh wparams.rootAsset = cpumesh.get(); am->writeAsset("cow.baw", wparams); // end export // import .baw mesh (test) cpumesh = core::smart_refctd_ptr_static_cast<asset::ICPUMesh>(*am->getAsset("cow.baw", lparams).getContents().first); // end import if (cpumesh) smgr->addMeshSceneNode(std::move(driver->getGPUObjectsFromAssets(&cpumesh.get(), (&cpumesh.get())+1)->operator[](0)),0,-1,core::vector3df(3.f,1.f,0.f))->setMaterialType(newMaterialType); uint64_t lastFPSTime = 0; while(device->run() && receiver.keepOpen() ) //if (device->isWindowActive()) { driver->beginScene(true, true, video::SColor(255,0,0,255) ); //! This animates (moves) the camera and sets the transforms //! Also draws the meshbuffer smgr->drawAll(); driver->endScene(); // display frames per second in window title uint64_t time = device->getTimer()->getRealTime(); if (time-lastFPSTime > 1000) { std::wostringstream sstr; sstr << L"Builtin Nodes Demo - Irrlicht Engine FPS:" << driver->getFPS() << " PrimitvesDrawn:" << driver->getPrimitiveCountDrawn(); device->setWindowCaption(sstr.str().c_str()); lastFPSTime = time; } } //create a screenshot { core::rect<uint32_t> sourceRect(0, 0, params.WindowSize.Width, params.WindowSize.Height); ext::ScreenShot::dirtyCPUStallingScreenshot(device, "screenshot.png", sourceRect, asset::EF_R8G8B8_SRGB); } device->drop(); return 0; }
fix ex 6
fix ex 6
C++
apache-2.0
buildaworldnet/IrrlichtBAW,buildaworldnet/IrrlichtBAW,buildaworldnet/IrrlichtBAW
3dee04a4ea2cb0915f7b531c3601870ab2478b85
cpp/rewrite_ssoar.cc
cpp/rewrite_ssoar.cc
/** \brief A tool for rewriting information in ssoar data * \author Johannes Riedl * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <unordered_map> #include <unordered_set> #include <cstdio> #include <cstdlib> #include <cstring> #include "Compiler.h" #include "FileUtil.h" #include "MARC.h" #include "MiscUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "TextUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--input-format=(marc-21|marc-xml)] marc_input marc_output\n"; std::exit(EXIT_FAILURE); } void Assemble773Article(MARC::Subfields * const _773subfields, const std::string &title = "", const std::string &year = "", const std::string &pages = "", const std::string &volinfo = "", const std::string &edition = "") { if (not (title.empty() and volinfo.empty() and pages.empty() and year.empty() and edition.empty())) _773subfields->addSubfield('i', "In:"); if (not title.empty()) _773subfields->addSubfield('a', StringUtil::Trim(title)); if (not volinfo.empty()) _773subfields->addSubfield('g', "volume: " + volinfo); if (not pages.empty()) _773subfields->addSubfield('g', "pages: " + pages); if (not year.empty()) _773subfields->addSubfield('g', "year: " + year); if (not edition.empty()) _773subfields->addSubfield('g', "edition: " + edition); } void Assemble773Book(MARC::Subfields * const _773subfields, const std::string &title = "", const std::string &authors = "", const std::string &year = "", const std::string &pages = "", const std::string &isbn = "") { if (not (title.empty() and authors.empty() and year.empty() and pages.empty() and isbn.empty())) _773subfields->addSubfield('i', "In:"); if (not title.empty()) { if (not authors.empty()) _773subfields->addSubfield('t', StringUtil::Trim(title)); else _773subfields->addSubfield('a', StringUtil::Trim(title)); } if (not authors.empty()) _773subfields->addSubfield('a', authors); if (not year.empty()) _773subfields->addSubfield('d', year); if ( not pages.empty()) _773subfields->addSubfield('g', "pages:" + pages); if (not isbn.empty()) _773subfields->addSubfield('o', isbn); } void ParseSuperior(const std::string &_500aContent, MARC::Subfields * const _773subfields) { // Belegung nach BSZ-Konkordanz // 773 $a "Geistiger Schöpfer" // 773 08 $i "Beziehungskennzeichnung" (== Übergerordnetes Werk) // 773 $d Jahr // 773 $t Titel (wenn Autor nicht vorhanden, dann stattdessen $a) // 773 $g Bandzählung [und weitere Angaben] // 773 $o "Sonstige Identifier für die andere Ausgabe" (ISBN) // 500 Structure for books // Must be checked first since it is more explicit // Normally it is Author(s) : Title. Year. S. xxx. ISBN static const std::string book_regex("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\s*S\\.\\s*([\\d\\-]+)\\.\\s*ISBN\\s*([\\d\\-X]+))"); static RegexMatcher * const book_matcher(RegexMatcher::RegexMatcherFactoryOrDie(book_regex)); // Authors : Title. Year. Pages static const std::string book_regex_1("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\sS\\.\\s([\\d\\-]+))"); static RegexMatcher * const book_matcher_1(RegexMatcher::RegexMatcherFactoryOrDie(book_regex_1)); // Authors : Title. Year. ISBN static const std::string book_regex_2("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\s*ISBN\\s*([\\d\\-X]+))"); static RegexMatcher * const book_matcher_2(RegexMatcher::RegexMatcherFactoryOrDie(book_regex_2)); // 500 Structure fields for articles // Normally Journal ; Edition String ; Page (??) static const std::string article_regex("^([^;]*)\\s*;\\s*([^;]*)\\s*;\\s*([\\d\\-]*)\\s*"); static RegexMatcher * const article_matcher(RegexMatcher::RegexMatcherFactoryOrDie(article_regex)); // Journal; Pages static const std::string article_regex_1("^([^;]*)\\s*;\\s*([\\d\\-]*)\\s*"); static RegexMatcher * const article_matcher_1(RegexMatcher::RegexMatcherFactoryOrDie(article_regex_1)); // Journal (Year) static const std::string article_regex_2("^(.*)\\s*\\((\\d{4})\\)"); static RegexMatcher * const article_matcher_2(RegexMatcher::RegexMatcherFactoryOrDie(article_regex_2)); if (book_matcher->matched(_500aContent)) { const std::string authors((*book_matcher)[1]); const std::string title((*book_matcher)[2]); const std::string year((*book_matcher)[3]); const std::string pages((*book_matcher)[4]); const std::string isbn((*book_matcher)[5]); Assemble773Book(_773subfields, title, authors, year, pages, isbn); } else if (book_matcher_1->matched(_500aContent)) { const std::string authors((*book_matcher_1)[1]); const std::string title((*book_matcher_1)[2]); const std::string year((*book_matcher_1)[3]); Assemble773Book(_773subfields, title, authors, year); } else if (book_matcher_2->matched(_500aContent)) { const std::string authors((*book_matcher_2)[1]); const std::string title((*book_matcher_2)[2]); const std::string year((*book_matcher_2)[3]); const std::string isbn((*book_matcher_2)[4]); Assemble773Book(_773subfields, title, authors, year, "", isbn); } else if (article_matcher->matched(_500aContent)) { const std::string title((*article_matcher)[1]); const std::string volinfo((*article_matcher)[2]); const std::string page((*article_matcher)[3]); Assemble773Article(_773subfields, title, "", page, volinfo, ""); } else if (article_matcher_1->matched(_500aContent)) { // See whether we can extract further information const std::string title_and_spec((*article_matcher_1)[1]); const std::string pages((*article_matcher_1)[2]); static const std::string title_and_spec_regex("^([^(]*)\\s*\\((\\d{4})\\)\\s*(\\d+)\\s*"); static RegexMatcher * const title_and_spec_matcher(RegexMatcher::RegexMatcherFactoryOrDie(title_and_spec_regex)); if (title_and_spec_matcher->matched(title_and_spec)) { const std::string title((*title_and_spec_matcher)[1]); const std::string year((*title_and_spec_matcher)[2]); const std::string edition((*title_and_spec_matcher)[3]); Assemble773Article(_773subfields, title, year, pages, "", edition); } else Assemble773Article(_773subfields, title_and_spec, "", pages); } else if (article_matcher_2->matched(_500aContent)) { const std::string title((*article_matcher_2)[1]); const std::string year((*article_matcher_2)[2]); Assemble773Article(_773subfields, title, year); } else { LOG_WARNING("No matching regex for " + _500aContent); } } void InsertSigelTo003(MARC::Record * const record, bool * const modified_record) { record->insertField("003", "INSERT_VALID_SIGEL_HERE"); *modified_record=true; } // Rewrite to 041$h or get date from 008 void InsertLanguageTo041(MARC::Record * const record, bool * const modified_record) { for (auto &field : record->getTagRange("041")) { if (not field.getFirstSubfieldWithCode('h').empty()) return; // Possibly the information is already in the $a field static const std::string valid_language_regex("([a-zA-Z]{3})$"); static RegexMatcher * const valid_language_matcher(RegexMatcher::RegexMatcherFactoryOrDie(valid_language_regex)); std::string language; if (valid_language_matcher->matched(field.getFirstSubfieldWithCode('a'))) { field.replaceSubfieldCode('a', 'h'); *modified_record=true; return; } else { const std::string _008Field(record->getFirstFieldContents("008")); if (not valid_language_matcher->matched(_008Field)) { LOG_WARNING("Invalid language code " + language); continue; } record->addSubfield("041", 'h', language); *modified_record=true; return; } } } void InsertYearTo264c(MARC::Record * const record, bool * const modified_record) { for (auto field : record->getTagRange("264")) { if (not field.getFirstSubfieldWithCode('c').empty()) return; // Extract year from 008 if available const std::string _008Field(record->getFirstFieldContents("008")); const std::string year(_008Field.substr(7,4)); record->addSubfield("264", 'c', year); *modified_record=true; return; } } void RewriteSuperiorReference(MARC::Record * const record, bool * const modified_record) { if (record->findTag("773") != record->end()) return; // Check if we have matching 500 field const std::string superior_string("^In:[\\s]*(.*)"); RegexMatcher * const superior_matcher(RegexMatcher::RegexMatcherFactory(superior_string)); for (auto &field : record->getTagRange("500")) { const auto subfields(field.getSubfields()); for (const auto &subfield : subfields) { if (subfield.code_ == 'a' && superior_matcher->matched(subfield.value_)) { MARC::Subfields new773Subfields; // Parse Field Contents ParseSuperior((*superior_matcher)[1], &new773Subfields); // Write 773 Field if (not new773Subfields.empty()) { record->insertField("773", new773Subfields, '0', '8'); *modified_record = true; } } } } } void ProcessRecords(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer) { unsigned record_count(0), modified_count(0); while (MARC::Record record = marc_reader->read()) { ++record_count; bool modified_record(false); InsertSigelTo003(&record, &modified_record); InsertLanguageTo041(&record, &modified_record); InsertYearTo264c(&record, &modified_record); RewriteSuperiorReference(&record, &modified_record); marc_writer->write(record); if (modified_record) ++modified_count; } LOG_INFO("Modified " + std::to_string(modified_count) + " of " + std::to_string(record_count) + " records"); } } // unnamed namespace int Main(int argc, char **argv) { ::progname = argv[0]; MARC::FileType reader_type(MARC::FileType::AUTO); if (argc == 4) { if (std::strcmp(argv[1], "--input-format=marc-21") == 0) reader_type = MARC::FileType::BINARY; else if (std::strcmp(argv[1], "--input-format=marc-xml") == 0) reader_type = MARC::FileType::XML; else Usage(); ++argv, --argc; } if (argc != 3) Usage(); const std::string marc_input_filename(argv[1]); const std::string marc_output_filename(argv[2]); if (unlikely(marc_input_filename == marc_output_filename)) LOG_ERROR("Title data input file name equals output file name!"); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename, reader_type)); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename)); ProcessRecords(marc_reader.get() , marc_writer.get()); return EXIT_SUCCESS; }
/** \brief A tool for rewriting information in ssoar data * \author Johannes Riedl * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <unordered_map> #include <unordered_set> #include <cstdio> #include <cstdlib> #include <cstring> #include "Compiler.h" #include "FileUtil.h" #include "MARC.h" #include "MiscUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "TextUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--input-format=(marc-21|marc-xml)] marc_input marc_output\n"; std::exit(EXIT_FAILURE); } void Assemble773Article(MARC::Subfields * const _773subfields, const std::string &title = "", const std::string &year = "", const std::string &pages = "", const std::string &volinfo = "", const std::string &edition = "") { if (not (title.empty() and volinfo.empty() and pages.empty() and year.empty() and edition.empty())) _773subfields->addSubfield('i', "In:"); if (not title.empty()) _773subfields->addSubfield('a', StringUtil::Trim(title)); if (not volinfo.empty()) _773subfields->addSubfield('g', "volume: " + volinfo); if (not pages.empty()) _773subfields->addSubfield('g', "pages: " + pages); if (not year.empty()) _773subfields->addSubfield('g', "year: " + year); if (not edition.empty()) _773subfields->addSubfield('g', "edition: " + edition); } void Assemble773Book(MARC::Subfields * const _773subfields, const std::string &title = "", const std::string &authors = "", const std::string &year = "", const std::string &pages = "", const std::string &isbn = "") { if (not (title.empty() and authors.empty() and year.empty() and pages.empty() and isbn.empty())) _773subfields->addSubfield('i', "In:"); if (not title.empty()) { if (not authors.empty()) _773subfields->addSubfield('t', StringUtil::Trim(title)); else _773subfields->addSubfield('a', StringUtil::Trim(title)); } if (not authors.empty()) _773subfields->addSubfield('a', authors); if (not year.empty()) _773subfields->addSubfield('d', year); if ( not pages.empty()) _773subfields->addSubfield('g', "pages:" + pages); if (not isbn.empty()) _773subfields->addSubfield('o', isbn); } void ParseSuperior(const std::string &_500aContent, MARC::Subfields * const _773subfields) { // Belegung nach BSZ-Konkordanz // 773 $a "Geistiger Schöpfer" // 773 08 $i "Beziehungskennzeichnung" (== Übergerordnetes Werk) // 773 $d Jahr // 773 $t Titel (wenn Autor nicht vorhanden, dann stattdessen $a) // 773 $g Bandzählung [und weitere Angaben] // 773 $o "Sonstige Identifier für die andere Ausgabe" (ISBN) // 500 Structure for books // Must be checked first since it is more explicit // Normally it is Author(s) : Title. Year. S. xxx. ISBN static const std::string book_regex("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\s*S\\.\\s*([\\d\\-]+)\\.\\s*ISBN\\s*([\\d\\-X]+))"); static RegexMatcher * const book_matcher(RegexMatcher::RegexMatcherFactoryOrDie(book_regex)); // Authors : Title. Year. Pages static const std::string book_regex_1("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\sS\\.\\s([\\d\\-]+))"); static RegexMatcher * const book_matcher_1(RegexMatcher::RegexMatcherFactoryOrDie(book_regex_1)); // Authors : Title. Year. ISBN static const std::string book_regex_2("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\s*ISBN\\s*([\\d\\-X]+))"); static RegexMatcher * const book_matcher_2(RegexMatcher::RegexMatcherFactoryOrDie(book_regex_2)); // 500 Structure fields for articles // Normally Journal ; Edition String ; Page (??) static const std::string article_regex("^([^;]*)\\s*;\\s*([^;]*)\\s*;\\s*([\\d\\-]*)\\s*"); static RegexMatcher * const article_matcher(RegexMatcher::RegexMatcherFactoryOrDie(article_regex)); // Journal; Pages static const std::string article_regex_1("^([^;]*)\\s*;\\s*([\\d\\-]*)\\s*"); static RegexMatcher * const article_matcher_1(RegexMatcher::RegexMatcherFactoryOrDie(article_regex_1)); // Journal (Year) static const std::string article_regex_2("^(.*)\\s*\\((\\d{4})\\)"); static RegexMatcher * const article_matcher_2(RegexMatcher::RegexMatcherFactoryOrDie(article_regex_2)); if (book_matcher->matched(_500aContent)) { const std::string authors((*book_matcher)[1]); const std::string title((*book_matcher)[2]); const std::string year((*book_matcher)[3]); const std::string pages((*book_matcher)[4]); const std::string isbn((*book_matcher)[5]); Assemble773Book(_773subfields, title, authors, year, pages, isbn); } else if (book_matcher_1->matched(_500aContent)) { const std::string authors((*book_matcher_1)[1]); const std::string title((*book_matcher_1)[2]); const std::string year((*book_matcher_1)[3]); Assemble773Book(_773subfields, title, authors, year); } else if (book_matcher_2->matched(_500aContent)) { const std::string authors((*book_matcher_2)[1]); const std::string title((*book_matcher_2)[2]); const std::string year((*book_matcher_2)[3]); const std::string isbn((*book_matcher_2)[4]); Assemble773Book(_773subfields, title, authors, year, "", isbn); } else if (article_matcher->matched(_500aContent)) { const std::string title((*article_matcher)[1]); const std::string volinfo((*article_matcher)[2]); const std::string page((*article_matcher)[3]); Assemble773Article(_773subfields, title, "", page, volinfo, ""); } else if (article_matcher_1->matched(_500aContent)) { // See whether we can extract further information const std::string title_and_spec((*article_matcher_1)[1]); const std::string pages((*article_matcher_1)[2]); static const std::string title_and_spec_regex("^([^(]*)\\s*\\((\\d{4})\\)\\s*(\\d+)\\s*"); static RegexMatcher * const title_and_spec_matcher(RegexMatcher::RegexMatcherFactoryOrDie(title_and_spec_regex)); if (title_and_spec_matcher->matched(title_and_spec)) { const std::string title((*title_and_spec_matcher)[1]); const std::string year((*title_and_spec_matcher)[2]); const std::string edition((*title_and_spec_matcher)[3]); Assemble773Article(_773subfields, title, year, pages, "", edition); } else Assemble773Article(_773subfields, title_and_spec, "", pages); } else if (article_matcher_2->matched(_500aContent)) { const std::string title((*article_matcher_2)[1]); const std::string year((*article_matcher_2)[2]); Assemble773Article(_773subfields, title, year); } else { LOG_WARNING("No matching regex for " + _500aContent); } } void InsertSigelTo003(MARC::Record * const record, bool * const modified_record) { record->insertField("003", "INSERT_VALID_SIGEL_HERE"); *modified_record=true; } // Rewrite to 041$h or get date from 008 void InsertLanguageInto041(MARC::Record * const record, bool * const modified_record) { for (auto &field : record->getTagRange("041")) { if (not field.getFirstSubfieldWithCode('h').empty()) return; // Possibly the information is already in the $a field static const std::string valid_language_regex("([a-zA-Z]{3})$"); static RegexMatcher * const valid_language_matcher(RegexMatcher::RegexMatcherFactoryOrDie(valid_language_regex)); std::string language; if (valid_language_matcher->matched(field.getFirstSubfieldWithCode('a'))) { field.replaceSubfieldCode('a', 'h'); *modified_record=true; return; } else { const std::string _008Field(record->getFirstFieldContents("008")); if (not valid_language_matcher->matched(_008Field)) { LOG_WARNING("Invalid language code " + language); continue; } record->addSubfield("041", 'h', language); *modified_record=true; return; } } } void InsertYearTo264c(MARC::Record * const record, bool * const modified_record) { for (auto field : record->getTagRange("264")) { if (not field.getFirstSubfieldWithCode('c').empty()) return; // Extract year from 008 if available const std::string _008Field(record->getFirstFieldContents("008")); const std::string year(_008Field.substr(7,4)); record->addSubfield("264", 'c', year); *modified_record=true; return; } } void RewriteSuperiorReference(MARC::Record * const record, bool * const modified_record) { if (record->findTag("773") != record->end()) return; // Check if we have matching 500 field const std::string superior_string("^In:[\\s]*(.*)"); RegexMatcher * const superior_matcher(RegexMatcher::RegexMatcherFactory(superior_string)); for (auto &field : record->getTagRange("500")) { const auto subfields(field.getSubfields()); for (const auto &subfield : subfields) { if (subfield.code_ == 'a' && superior_matcher->matched(subfield.value_)) { MARC::Subfields new773Subfields; // Parse Field Contents ParseSuperior((*superior_matcher)[1], &new773Subfields); // Write 773 Field if (not new773Subfields.empty()) { record->insertField("773", new773Subfields, '0', '8'); *modified_record = true; } } } } } void ProcessRecords(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer) { unsigned record_count(0), modified_count(0); while (MARC::Record record = marc_reader->read()) { ++record_count; bool modified_record(false); InsertSigelTo003(&record, &modified_record); InsertLanguageInto041(&record, &modified_record); InsertYearTo264c(&record, &modified_record); RewriteSuperiorReference(&record, &modified_record); marc_writer->write(record); if (modified_record) ++modified_count; } LOG_INFO("Modified " + std::to_string(modified_count) + " of " + std::to_string(record_count) + " records"); } } // unnamed namespace int Main(int argc, char **argv) { ::progname = argv[0]; MARC::FileType reader_type(MARC::FileType::AUTO); if (argc == 4) { if (std::strcmp(argv[1], "--input-format=marc-21") == 0) reader_type = MARC::FileType::BINARY; else if (std::strcmp(argv[1], "--input-format=marc-xml") == 0) reader_type = MARC::FileType::XML; else Usage(); ++argv, --argc; } if (argc != 3) Usage(); const std::string marc_input_filename(argv[1]); const std::string marc_output_filename(argv[2]); if (unlikely(marc_input_filename == marc_output_filename)) LOG_ERROR("Title data input file name equals output file name!"); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename, reader_type)); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename)); ProcessRecords(marc_reader.get() , marc_writer.get()); return EXIT_SUCCESS; }
Change naming
Change naming
C++
agpl-3.0
ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools,ubtue/ub_tools
73c52482558c01412fa557335a46f4e7a84e4bb1
cppad/index_sort.hpp
cppad/index_sort.hpp
/* $Id$ */ # ifndef CPPAD_INDEX_SORT_INCLUDED # define CPPAD_INDEX_SORT_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Eclipse Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin index_sort$$ $spell cppad.hpp ind const $$ $section Returns Indices that Sort a Vector$$ $index index_sort$$ $index sort, index$$ $head Syntax$$ $codei%# include <cppad/near_equal.hpp> index_sort(%keys%, %ind%)%$$ $head keys$$ The argument $icode keys$$ has prototype $codei% const %VectorKey%& %keys% %$$ where $icode VectorKey$$ is a $cref SimpleVector$$ class with elements that support the $code <$$ operation. $head ind$$ The argument $icode ind$$ has prototype $codei% const %VectorSize%& %ind% %$$ where $icode VectorSize$$ is a $cref SimpleVector$$ class with elements of type $code size_t$$. The routine $cref CheckSimpleVector$$ will generate an error message if this is not the case. The size of $icode ind$$ must be the same as the size of $icode keys$$ and the value of its input elements does not matter. $pre $$ Upon return, $icode ind$$ is a permutation of the set of indices that yields increasing order for $icode keys$$. In other words, for all $icode%i% != %j%$$, $codei% %ind%[%i%] != %ind%[%j%] %$$ and for $icode%i% = 0 , %...% , %size%-2%$$, $codei% ( %keys%[ %ind%[%i%+1] ] < %keys%[ %ind[%i%] ] ) == false %$$ $head Example$$ $children% example/index_sort.cpp %$$ The file $cref index_sort.cpp$$ contains an example and test of this routine. It return true if it succeeds and false otherwise. $end */ # include <algorithm> # include <cppad/thread_alloc.hpp> # include <cppad/check_simple_vector.hpp> # include <cppad/local/define.hpp> CPPAD_BEGIN_NAMESPACE /*! \defgroup index_sort_hpp index_sort.hpp \{ \file index_sort.hpp File used to implement the CppAD index sort utility */ /*! Helper class used by index_sort */ template <class Compare> class index_sort_element { private: /// key used to determine position of this element Compare key_; /// index vlaue corresponding to this key size_t index_; public: /// operator requried by std::sort bool operator<(const index_sort_element& other) const { return key_ < other.key_; } /// set the key for this element void set_key(const Compare& value) { key_ = value; } /// set the index for this element void set_index(const size_t& index) { index_ = index; } /// get the key for this element Compare get_key(void) const { return key_; } /// get the index for this element size_t get_index(void) const { return index_; } }; /*! Compute the indices that sort a vector of keys \tparam VectorKey Simple vector type that deterimene the sorting order by \c < operator on its elements. \tparam VectorSize Simple vector type with elements of \c size_t that is used to return index values. \param keys [in] values that determine the sorting order. \param ind [out] must have the same size as \c keys. The input value of its elements does not matter. The output value of its elements satisfy \code ( keys[ ind[i] ] < keys[ ind[i+1] ] ) == false \endcode */ template <class VectorKey, class VectorSize> void index_sort(const VectorKey& keys, VectorSize& ind) { typedef typename VectorKey::value_type Compare; CheckSimpleVector<size_t, VectorSize>(); typedef index_sort_element<Compare> element; CPPAD_ASSERT_KNOWN( size_t(keys.size()) == size_t(ind.size()), "index_sort: vector sizes do not match" ); size_t size_work = size_t(keys.size()); size_t size_out; element* work = thread_alloc::create_array<element>(size_work, size_out); // copy initial order into work size_t i; for(i = 0; i < size_work; i++) { work[i].set_key( keys[i] ); work[i].set_index( i ); } // sort the work array std::sort(work, work+size_work); // copy the indices to the output vector for(i = 0; i < size_work; i++) ind[i] = work[i].get_index(); // we are done with this work array thread_alloc::delete_array(work); return; } /*! \} */ CPPAD_END_NAMESPACE # endif
/* $Id$ */ # ifndef CPPAD_INDEX_SORT_INCLUDED # define CPPAD_INDEX_SORT_INCLUDED /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-13 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Eclipse Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin index_sort$$ $spell cppad.hpp ind const $$ $section Returns Indices that Sort a Vector$$ $index index_sort$$ $index sort, index$$ $head Syntax$$ $codei%# include <cppad/near_equal.hpp> index_sort(%keys%, %ind%)%$$ $head keys$$ The argument $icode keys$$ has prototype $codei% const %VectorKey%& %keys% %$$ where $icode VectorKey$$ is a $cref SimpleVector$$ class with elements that support the $code <$$ operation. $head ind$$ The argument $icode ind$$ has prototype $codei% const %VectorSize%& %ind% %$$ where $icode VectorSize$$ is a $cref SimpleVector$$ class with elements of type $code size_t$$. The routine $cref CheckSimpleVector$$ will generate an error message if this is not the case. The size of $icode ind$$ must be the same as the size of $icode keys$$ and the value of its input elements does not matter. $pre $$ Upon return, $icode ind$$ is a permutation of the set of indices that yields increasing order for $icode keys$$. In other words, for all $icode%i% != %j%$$, $codei% %ind%[%i%] != %ind%[%j%] %$$ and for $icode%i% = 0 , %...% , %size%-2%$$, $codei% ( %keys%[ %ind%[%i%+1] ] < %keys%[ %ind%[%i%] ] ) == false %$$ $head Example$$ $children% example/index_sort.cpp %$$ The file $cref index_sort.cpp$$ contains an example and test of this routine. It return true if it succeeds and false otherwise. $end */ # include <algorithm> # include <cppad/thread_alloc.hpp> # include <cppad/check_simple_vector.hpp> # include <cppad/local/define.hpp> CPPAD_BEGIN_NAMESPACE /*! \defgroup index_sort_hpp index_sort.hpp \{ \file index_sort.hpp File used to implement the CppAD index sort utility */ /*! Helper class used by index_sort */ template <class Compare> class index_sort_element { private: /// key used to determine position of this element Compare key_; /// index vlaue corresponding to this key size_t index_; public: /// operator requried by std::sort bool operator<(const index_sort_element& other) const { return key_ < other.key_; } /// set the key for this element void set_key(const Compare& value) { key_ = value; } /// set the index for this element void set_index(const size_t& index) { index_ = index; } /// get the key for this element Compare get_key(void) const { return key_; } /// get the index for this element size_t get_index(void) const { return index_; } }; /*! Compute the indices that sort a vector of keys \tparam VectorKey Simple vector type that deterimene the sorting order by \c < operator on its elements. \tparam VectorSize Simple vector type with elements of \c size_t that is used to return index values. \param keys [in] values that determine the sorting order. \param ind [out] must have the same size as \c keys. The input value of its elements does not matter. The output value of its elements satisfy \code ( keys[ ind[i] ] < keys[ ind[i+1] ] ) == false \endcode */ template <class VectorKey, class VectorSize> void index_sort(const VectorKey& keys, VectorSize& ind) { typedef typename VectorKey::value_type Compare; CheckSimpleVector<size_t, VectorSize>(); typedef index_sort_element<Compare> element; CPPAD_ASSERT_KNOWN( size_t(keys.size()) == size_t(ind.size()), "index_sort: vector sizes do not match" ); size_t size_work = size_t(keys.size()); size_t size_out; element* work = thread_alloc::create_array<element>(size_work, size_out); // copy initial order into work size_t i; for(i = 0; i < size_work; i++) { work[i].set_key( keys[i] ); work[i].set_index( i ); } // sort the work array std::sort(work, work+size_work); // copy the indices to the output vector for(i = 0; i < size_work; i++) ind[i] = work[i].get_index(); // we are done with this work array thread_alloc::delete_array(work); return; } /*! \} */ CPPAD_END_NAMESPACE # endif
fix font in documentation of ind.
index_sort.hpp: fix font in documentation of ind. git-svn-id: 3f5418f4deb1796ec361794c2e3ca0aec3c9c1fd@2774 0e562018-b8fb-0310-a933-ecf073c7c197
C++
epl-1.0
wegamekinglc/CppAD,utke1/cppad,wegamekinglc/CppAD,wegamekinglc/CppAD,kaskr/CppAD,utke1/cppad,kaskr/CppAD,wegamekinglc/CppAD,utke1/cppad,kaskr/CppAD,wegamekinglc/CppAD,kaskr/CppAD,utke1/cppad,kaskr/CppAD
2ca0d97cfdb5fb80ba2b6e724b7ef5068dd59d0d
support/parsers/net.cc
support/parsers/net.cc
#include <algorithm> // search #include <array> #include <cassert> #include <deque> #include <iostream> #include <limits> #include <regex> #include <sstream> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <boost/algorithm/string/join.hpp> #include <boost/optional.hpp> #include "support/parsers/parse_error.hh" #include "support/parsers/net.hh" #include "support/parsers/token.hh" namespace pnmc { namespace parsers { namespace { /*------------------------------------------------------------------------------------------------*/ // @brief Used to start keywords in token_t at indexes higher than other regular tokens matched by // the regular expression. static constexpr auto keywords_gap = 1000u; // @brief Start at 1 because the relative position in the enum is used to compute the type of the // token and because submatches of regular expressions start at 1 (0 is the whole match). enum class tk { skip = 1u, newline, number, qname, name, colon, comma , lbracket, rbracket, arrow, lparen, rparen, question, exclamation, minus, mult , lt, gt , net = keywords_gap, transition, place, prio, module}; /*------------------------------------------------------------------------------------------------*/ using namespace std::string_literals; using token = token_holder<tk>; using parse_cxt = parse_context<tk>; /*------------------------------------------------------------------------------------------------*/ /// @brief Returns the tokens of a Tina model. template <typename InputIterator> auto tokens(InputIterator&& begin, InputIterator&& end) { static constexpr std::array<const char*, 5> keywords = {{"net", "tr", "pl", "pr", "md"}}; // Order must match enum token_t static const std::regex regex { "([ \\t]+)|" // skip spaces and tabs "(\\n)|" // newline (to keep track of line numbers) "(\\d+[KM]?)|" // numbers can have a suffix "(\\{)|" // only search for opening brace for qualified names "([a-zA-Z'_][a-zA-Z0-9'_]*)|" // don't begin by a number, we add it if necessary in the parser "(:)|" // colon "(,)|" // comma "(\\[)|" // left bracket "(\\])|" // right bracket "(->)|" // arrow "(\\()|" // left parenthesis "(\\))|" // right parenthesis "(\\?)|" // question mark "(!)|" // exclamation mark "(-)|" // minus "(\\*)|" // multiplication "(<)|" // less than "(>)" // upper than }; // To report error location, if any. auto line = 1ul; auto column = 1ul; std::smatch match; std::deque<token> tokens; while (true) { if (begin == end) {break;} std::regex_search(begin, end, match, regex); if (match.position() != 0) { throw parse_error( "Unexpected '" + match.prefix().str() + "' at " + std::to_string(line) + ':' + std::to_string(column - match.prefix().str().size())); } column += match.length(); begin += match.length(); if (match[pos(tk::skip)].matched) {continue;} if (match[pos(tk::newline)].matched) {column = 1; ++line; continue;} // Get the type of token by looking for the first successful submatch. const auto ty = [&match] { auto t = pos(tk::number); for (; t < match.size(); ++t) { if (match[t].matched) {break;} } return t; }(); assert(ty < match.size()); // Check if name is a keyword. if (ty == pos(tk::name)) { const auto search = std::find(keywords.cbegin(), keywords.cend(), match[ty].str()); if (search != keywords.cend()) { const auto kw_ty = std::distance(keywords.cbegin(), search) + keywords_gap; tokens.emplace_back(token {tk(kw_ty), "", line, column}); continue; } } // Process qualified names manually (to handle despecialization). else if (ty == pos(tk::qname)) { std::string qname; qname.reserve(32); bool despecialization = false; while (true) { if (despecialization) { qname.push_back(*begin); despecialization = false; } else { if (*begin == '}') {++begin; ++column; break;} else if (*begin == '\\') {despecialization = true;} else {qname.push_back(*begin);} } ++begin; ++column; } tokens.emplace_back(token {tk::qname, qname, line, column}); continue; } // All other tokens. tokens.emplace_back(token {tk(ty), match[ty].str(), line, column}); } return tokens; } /*------------------------------------------------------------------------------------------------*/ boost::optional<std::string> accept_name(parse_cxt& cxt) { if (accept(cxt, tk::number)) // identifiers may start with a number { const auto name = cxt.val(); accept(cxt, tk::name); return name + cxt.val(); } else if (accept(cxt, tk::name)) { return cxt.val(); } return {}; } /*------------------------------------------------------------------------------------------------*/ std::string id(parse_cxt& cxt) { if (const auto maybe_name = accept_name(cxt)) { return *maybe_name; } else { expect(cxt, tk::qname); return cxt.val(); } } /*------------------------------------------------------------------------------------------------*/ boost::optional<std::string> accept_id(parse_cxt& cxt) { if (const auto n = accept_name(cxt)) {return *n;} else if (accept(cxt, tk::qname)) {return cxt.val();} else {return {};} } /*------------------------------------------------------------------------------------------------*/ unsigned int number(parse_cxt& cxt) { expect(cxt, tk::number); const auto res = std::stoi(cxt.val()); switch (cxt.val().back()) { case 'K': return res * 1'000; case 'M': return res * 1'000'000; default : return res; } } /*------------------------------------------------------------------------------------------------*/ template <typename Fun> void input_arcs(parse_cxt& cxt, Fun&& add_arc) { while (true) { const auto maybe_target = accept_id(cxt); if (not maybe_target) {break;} // no more arcs auto arc_ty = pn::arc::type::normal; auto valuation = 1u; if (accept(cxt, tk::mult)) { if (accept(cxt, tk::mult)) { arc_ty = pn::arc::type::reset; } else { valuation = number(cxt); } } else if (accept(cxt, tk::question)) { if (accept(cxt, tk::minus)) {arc_ty = pn::arc::type::inhibitor;} else {arc_ty = pn::arc::type::read;} valuation = number(cxt); } else if (accept(cxt, tk::exclamation)) { throw parse_error("Unsupported stopwatch inhibitor arc"); } add_arc(*maybe_target, valuation, arc_ty); } } /*------------------------------------------------------------------------------------------------*/ template <typename Fun> void output_arcs(parse_cxt& cxt, Fun&& add_arc) { while (true) { const auto maybe_target = accept_id(cxt); if (not maybe_target) { break; // no more arcs } auto valuation = 1u; if (accept(cxt, tk::mult)) { valuation = number(cxt); } add_arc(*maybe_target, valuation, pn::arc::type::normal); } } /*------------------------------------------------------------------------------------------------*/ void transition(parse_cxt& cxt, pn::net& n) { const auto tid = id(cxt); n.add_transition(tid); if (accept(cxt, tk::colon)) // label { id(cxt); } if (accept(cxt, tk::lbracket) or accept(cxt, tk::rbracket)) // time interval { static constexpr auto inf = std::numeric_limits<unsigned int>::max(); // To report error location. const auto line = cxt.previous().line; const auto column = cxt.previous().column - 1; const bool open_lower_endpoint = cxt.val() == "]"; bool open_upper_endpoint = false; auto low = number(cxt); expect(cxt, tk::comma); auto high = 0u; if (accept(cxt, tk::name)) { if (cxt.val() != "w") {error(cxt);} high = inf; } else { high = number(cxt); } if (not accept(cxt, tk::rbracket)) { expect(cxt, tk::lbracket); open_upper_endpoint = cxt.val() == "["; } if (open_lower_endpoint) {low += 1;} if (open_upper_endpoint and high != inf) {high -= 1;} if (high < low) { throw parse_error( "Time interval at " + std::to_string(line) + ":" + std::to_string(column)); } n.add_time_interval(tid, low, high); } input_arcs(cxt, [&](const auto& pre, unsigned int weight, pn::arc::type ty) { n.add_pre_place(tid, pre, weight, ty); }); if (accept(cxt, tk::arrow)) { output_arcs(cxt, [&](const auto& post, unsigned int weight, pn::arc::type ty) { n.add_post_place(tid, post, weight, ty); }); } } /*------------------------------------------------------------------------------------------------*/ void place(parse_cxt& cxt, pn::net& n) { const auto name = id(cxt); auto marking = 0u; if (accept(cxt, tk::colon)) // label { id(cxt); } if (accept(cxt, tk::lparen)) // initial marking { marking = number(cxt); expect(cxt, tk::rparen); } n.add_place(name, marking); } /*------------------------------------------------------------------------------------------------*/ void priority(parse_cxt& cxt, pn::net&) { id(cxt); while (accept_id(cxt)) {} if (not accept(cxt, tk::lt)) { expect(cxt, tk::gt); } id(cxt); while (accept_id(cxt)) {} } /*------------------------------------------------------------------------------------------------*/ void module(parse_cxt& cxt, std::unordered_map<std::string, std::vector<std::string>>& modules_id) { const auto insertion = modules_id.emplace(id(cxt), std::vector<std::string>{}); while (const auto pl = accept_id(cxt)) { insertion.first->second.emplace_back(*pl); } } /*------------------------------------------------------------------------------------------------*/ /// @brief Remove commented lines and uncomment '#!' pragmas. std::string preprocess(std::istream& in) { std::stringstream ss; std::for_each( std::istreambuf_iterator<char>{in}, std::istreambuf_iterator<char>{} , [&](char c) { static bool comment = false; if (comment and c == '!') {comment = false; ss << ' ';} else if (comment and c == '\n') {comment = false; ss << c;} else if (not comment and c == '#') {comment = true; ss << ' ';} else if (not comment) {ss << c;} }); return ss.str(); } /*------------------------------------------------------------------------------------------------*/ pn::module make_module( const std::string& id, std::unordered_map<std::string, std::vector<std::string>>& graph , pn::net& net, const std::string& container, std::unordered_set<std::string>& places) { const auto place_search = net.places().find(id); if (place_search != end(net.places())) { places.insert(place_search->id); return pn::make_module(*place_search); } else { pn::module_node m{id}; const auto submodule_search = graph.find(id); if (submodule_search == end(graph)) { throw parse_error("Undefined module or place " + id + " in module " + container); } for (const auto& sub : submodule_search->second) { m.add_submodule(make_module(sub, graph, net, id, places)); } const auto insertion = net.modules.emplace(id, pn::make_module(m)); if (not insertion.second) { throw parse_error("Module or place " + id + " is present in another module"); } return insertion.first->second; } } /*------------------------------------------------------------------------------------------------*/ } // namespace anonymous /*------------------------------------------------------------------------------------------------*/ std::shared_ptr<pn::net> net(std::istream& in) { auto net_ptr = std::make_shared<pn::net>(); const auto text = preprocess(in); const auto tks = tokens(begin(text), end(text)); parse_cxt cxt{tks.cbegin(), tks.cend()}; std::unordered_map<std::string, std::vector<std::string>> modules_id; while (not cxt.eof()) { if (accept(cxt, tk::net)) {net_ptr->name = id(cxt);} else if (accept(cxt, tk::transition)) {transition(cxt, *net_ptr);} else if (accept(cxt, tk::place)) {place(cxt, *net_ptr);} else if (accept(cxt, tk::prio)) {priority(cxt, *net_ptr);} else if (accept(cxt, tk::module)) {module(cxt, modules_id);} else {error(cxt);} }; if (modules_id.size() > 0) { const auto& net_name = net_ptr->name; const auto& root_search = modules_id.find(net_name); std::unordered_set<std::string> places_encountered; if (root_search == end(modules_id)) { throw parse_error("No root module(s)."); } for (const auto& submodule : root_search->second) { net_ptr->root_modules.emplace_back(make_module( submodule, modules_id, *net_ptr, net_name , places_encountered)); } std::vector<std::string> invalid; std::for_each( begin(net_ptr->places()), end(net_ptr->places()) , [&](const auto& p) { if (not places_encountered.count(p.id)) {invalid.push_back(p.id);} }); std::for_each( begin(modules_id), end(modules_id) , [&](const auto& kv) { if (kv.first != net_ptr->name and not net_ptr->modules.count(kv.first)) { invalid.push_back(kv.first); } }); if (not invalid.empty()) { const auto msg = boost::algorithm::join(invalid, ", "); throw parse_error("The following modules or places do not belong to any module: " + msg); } } net_ptr->format = conf::pn_format::net; return net_ptr; } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::parsers
#include <algorithm> // search #include <array> #include <cassert> #include <deque> #include <iostream> #include <limits> #include <regex> #include <sstream> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <boost/algorithm/string/join.hpp> #include <boost/optional.hpp> #include "support/parsers/parse_error.hh" #include "support/parsers/net.hh" #include "support/parsers/token.hh" namespace pnmc { namespace parsers { namespace { /*------------------------------------------------------------------------------------------------*/ // @brief Used to start keywords in token_t at indexes higher than other regular tokens matched by // the regular expression. static constexpr auto keywords_gap = 1000u; // @brief Start at 1 because the relative position in the enum is used to compute the type of the // token and because submatches of regular expressions start at 1 (0 is the whole match). enum class tk { skip = 1u, newline, number, qname, name, colon, comma , lbracket, rbracket, arrow, lparen, rparen, question, exclamation, minus, mult , lt, gt , net = keywords_gap, transition, place, prio, module}; /*------------------------------------------------------------------------------------------------*/ using token = token_holder<tk>; using parse_cxt = parse_context<tk>; /*------------------------------------------------------------------------------------------------*/ /// @brief Returns the tokens of a Tina model. template <typename InputIterator> auto tokens(InputIterator&& begin, InputIterator&& end) { static constexpr std::array<const char*, 5> keywords = {{"net", "tr", "pl", "pr", "md"}}; // Order must match enum token_t static const std::regex regex { "([ \\t]+)|" // skip spaces and tabs "(\\n)|" // newline (to keep track of line numbers) "(\\d+[KM]?)|" // numbers can have a suffix "(\\{)|" // only search for opening brace for qualified names "([a-zA-Z'_][a-zA-Z0-9'_]*)|" // don't begin by a number, we add it if necessary in the parser "(:)|" // colon "(,)|" // comma "(\\[)|" // left bracket "(\\])|" // right bracket "(->)|" // arrow "(\\()|" // left parenthesis "(\\))|" // right parenthesis "(\\?)|" // question mark "(!)|" // exclamation mark "(-)|" // minus "(\\*)|" // multiplication "(<)|" // less than "(>)" // upper than }; // To report error location, if any. auto line = 1ul; auto column = 1ul; std::smatch match; std::deque<token> tokens; while (true) { if (begin == end) {break;} std::regex_search(begin, end, match, regex); if (match.position() != 0) { throw parse_error( "Unexpected '" + match.prefix().str() + "' at " + std::to_string(line) + ':' + std::to_string(column - match.prefix().str().size())); } column += match.length(); begin += match.length(); if (match[pos(tk::skip)].matched) {continue;} if (match[pos(tk::newline)].matched) {column = 1; ++line; continue;} // Get the type of token by looking for the first successful submatch. const auto ty = [&match] { auto t = pos(tk::number); for (; t < match.size(); ++t) { if (match[t].matched) {break;} } return t; }(); assert(ty < match.size()); // Check if name is a keyword. if (ty == pos(tk::name)) { const auto search = std::find(keywords.cbegin(), keywords.cend(), match[ty].str()); if (search != keywords.cend()) { const auto kw_ty = std::distance(keywords.cbegin(), search) + keywords_gap; tokens.emplace_back(token {tk(kw_ty), "", line, column}); continue; } } // Process qualified names manually (to handle despecialization). else if (ty == pos(tk::qname)) { std::string qname; qname.reserve(32); bool despecialization = false; while (true) { if (despecialization) { qname.push_back(*begin); despecialization = false; } else { if (*begin == '}') {++begin; ++column; break;} else if (*begin == '\\') {despecialization = true;} else {qname.push_back(*begin);} } ++begin; ++column; } tokens.emplace_back(token {tk::qname, qname, line, column}); continue; } // All other tokens. tokens.emplace_back(token {tk(ty), match[ty].str(), line, column}); } return tokens; } /*------------------------------------------------------------------------------------------------*/ boost::optional<std::string> accept_name(parse_cxt& cxt) { if (accept(cxt, tk::number)) // identifiers may start with a number { const auto name = cxt.val(); accept(cxt, tk::name); return name + cxt.val(); } else if (accept(cxt, tk::name)) { return cxt.val(); } return {}; } /*------------------------------------------------------------------------------------------------*/ std::string id(parse_cxt& cxt) { if (const auto maybe_name = accept_name(cxt)) { return *maybe_name; } else { expect(cxt, tk::qname); return cxt.val(); } } /*------------------------------------------------------------------------------------------------*/ boost::optional<std::string> accept_id(parse_cxt& cxt) { if (const auto n = accept_name(cxt)) {return *n;} else if (accept(cxt, tk::qname)) {return cxt.val();} else {return {};} } /*------------------------------------------------------------------------------------------------*/ unsigned int number(parse_cxt& cxt) { expect(cxt, tk::number); const auto res = std::stoi(cxt.val()); switch (cxt.val().back()) { case 'K': return res * 1'000; case 'M': return res * 1'000'000; default : return res; } } /*------------------------------------------------------------------------------------------------*/ template <typename Fun> void input_arcs(parse_cxt& cxt, Fun&& add_arc) { while (true) { const auto maybe_target = accept_id(cxt); if (not maybe_target) {break;} // no more arcs auto arc_ty = pn::arc::type::normal; auto valuation = 1u; if (accept(cxt, tk::mult)) { if (accept(cxt, tk::mult)) { arc_ty = pn::arc::type::reset; } else { valuation = number(cxt); } } else if (accept(cxt, tk::question)) { if (accept(cxt, tk::minus)) {arc_ty = pn::arc::type::inhibitor;} else {arc_ty = pn::arc::type::read;} valuation = number(cxt); } else if (accept(cxt, tk::exclamation)) { throw parse_error("Unsupported stopwatch inhibitor arc"); } add_arc(*maybe_target, valuation, arc_ty); } } /*------------------------------------------------------------------------------------------------*/ template <typename Fun> void output_arcs(parse_cxt& cxt, Fun&& add_arc) { while (true) { const auto maybe_target = accept_id(cxt); if (not maybe_target) { break; // no more arcs } auto valuation = 1u; if (accept(cxt, tk::mult)) { valuation = number(cxt); } add_arc(*maybe_target, valuation, pn::arc::type::normal); } } /*------------------------------------------------------------------------------------------------*/ void transition(parse_cxt& cxt, pn::net& n) { const auto tid = id(cxt); n.add_transition(tid); if (accept(cxt, tk::colon)) // label { id(cxt); } if (accept(cxt, tk::lbracket) or accept(cxt, tk::rbracket)) // time interval { static constexpr auto inf = std::numeric_limits<unsigned int>::max(); // To report error location. const auto line = cxt.previous().line; const auto column = cxt.previous().column - 1; const bool open_lower_endpoint = cxt.val() == "]"; bool open_upper_endpoint = false; auto low = number(cxt); expect(cxt, tk::comma); auto high = 0u; if (accept(cxt, tk::name)) { if (cxt.val() != "w") {error(cxt);} high = inf; } else { high = number(cxt); } if (not accept(cxt, tk::rbracket)) { expect(cxt, tk::lbracket); open_upper_endpoint = cxt.val() == "["; } if (open_lower_endpoint) {low += 1;} if (open_upper_endpoint and high != inf) {high -= 1;} if (high < low) { throw parse_error( "Time interval at " + std::to_string(line) + ":" + std::to_string(column)); } n.add_time_interval(tid, low, high); } input_arcs(cxt, [&](const auto& pre, unsigned int weight, pn::arc::type ty) { n.add_pre_place(tid, pre, weight, ty); }); if (accept(cxt, tk::arrow)) { output_arcs(cxt, [&](const auto& post, unsigned int weight, pn::arc::type ty) { n.add_post_place(tid, post, weight, ty); }); } } /*------------------------------------------------------------------------------------------------*/ void place(parse_cxt& cxt, pn::net& n) { const auto name = id(cxt); auto marking = 0u; if (accept(cxt, tk::colon)) // label { id(cxt); } if (accept(cxt, tk::lparen)) // initial marking { marking = number(cxt); expect(cxt, tk::rparen); } n.add_place(name, marking); } /*------------------------------------------------------------------------------------------------*/ void priority(parse_cxt& cxt, pn::net&) { id(cxt); while (accept_id(cxt)) {} if (not accept(cxt, tk::lt)) { expect(cxt, tk::gt); } id(cxt); while (accept_id(cxt)) {} } /*------------------------------------------------------------------------------------------------*/ void module(parse_cxt& cxt, std::unordered_map<std::string, std::vector<std::string>>& modules_id) { const auto insertion = modules_id.emplace(id(cxt), std::vector<std::string>{}); while (const auto pl = accept_id(cxt)) { insertion.first->second.emplace_back(*pl); } } /*------------------------------------------------------------------------------------------------*/ /// @brief Remove commented lines and uncomment '#!' pragmas. std::string preprocess(std::istream& in) { std::stringstream ss; std::for_each( std::istreambuf_iterator<char>{in}, std::istreambuf_iterator<char>{} , [&](char c) { static bool comment = false; if (comment and c == '!') {comment = false; ss << ' ';} else if (comment and c == '\n') {comment = false; ss << c;} else if (not comment and c == '#') {comment = true; ss << ' ';} else if (not comment) {ss << c;} }); return ss.str(); } /*------------------------------------------------------------------------------------------------*/ pn::module make_module( const std::string& id, std::unordered_map<std::string, std::vector<std::string>>& graph , pn::net& net, const std::string& container, std::unordered_set<std::string>& places) { const auto place_search = net.places().find(id); if (place_search != end(net.places())) { places.insert(place_search->id); return pn::make_module(*place_search); } else { pn::module_node m{id}; const auto submodule_search = graph.find(id); if (submodule_search == end(graph)) { throw parse_error("Undefined module or place " + id + " in module " + container); } for (const auto& sub : submodule_search->second) { m.add_submodule(make_module(sub, graph, net, id, places)); } const auto insertion = net.modules.emplace(id, pn::make_module(m)); if (not insertion.second) { throw parse_error("Module or place " + id + " is present in another module"); } return insertion.first->second; } } /*------------------------------------------------------------------------------------------------*/ } // namespace anonymous /*------------------------------------------------------------------------------------------------*/ std::shared_ptr<pn::net> net(std::istream& in) { auto net_ptr = std::make_shared<pn::net>(); const auto text = preprocess(in); const auto tks = tokens(begin(text), end(text)); parse_cxt cxt{tks.cbegin(), tks.cend()}; std::unordered_map<std::string, std::vector<std::string>> modules_id; while (not cxt.eof()) { if (accept(cxt, tk::net)) {net_ptr->name = id(cxt);} else if (accept(cxt, tk::transition)) {transition(cxt, *net_ptr);} else if (accept(cxt, tk::place)) {place(cxt, *net_ptr);} else if (accept(cxt, tk::prio)) {priority(cxt, *net_ptr);} else if (accept(cxt, tk::module)) {module(cxt, modules_id);} else {error(cxt);} }; if (modules_id.size() > 0) { const auto& net_name = net_ptr->name; const auto& root_search = modules_id.find(net_name); std::unordered_set<std::string> places_encountered; if (root_search == end(modules_id)) { throw parse_error("No root module(s)."); } for (const auto& submodule : root_search->second) { net_ptr->root_modules.emplace_back(make_module( submodule, modules_id, *net_ptr, net_name , places_encountered)); } std::vector<std::string> invalid; std::for_each( begin(net_ptr->places()), end(net_ptr->places()) , [&](const auto& p) { if (not places_encountered.count(p.id)) {invalid.push_back(p.id);} }); std::for_each( begin(modules_id), end(modules_id) , [&](const auto& kv) { if (kv.first != net_ptr->name and not net_ptr->modules.count(kv.first)) { invalid.push_back(kv.first); } }); if (not invalid.empty()) { const auto msg = boost::algorithm::join(invalid, ", "); throw parse_error("The following modules or places do not belong to any module: " + msg); } } net_ptr->format = conf::pn_format::net; return net_ptr; } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::parsers
Remove unused 'using namespace'
Remove unused 'using namespace'
C++
bsd-2-clause
ahamez/pnmc,ahamez/pnmc
40e47a16df0384f894ad8e0ec918d4a8d3535d1f
tools/ouzel/xcode/PBXFileReference.hpp
tools/ouzel/xcode/PBXFileReference.hpp
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_XCODE_PBXFILEREFERENCE_HPP #define OUZEL_XCODE_PBXFILEREFERENCE_HPP #include "PBXFileElement.hpp" #include "PBXFileType.hpp" namespace ouzel::xcode { class PBXFileReference: public PBXFileElement { public: PBXFileReference() = default; std::string getIsa() const override { return "PBXFileReference"; } plist::Value encode() const override { auto result = PBXFileElement::encode(); result["explicitFileType"] = toString(fileType); result["includeInIndex"] = 0; return result; } PBXFileType fileType; }; } #endif // OUZEL_XCODE_PBXFILEREFERENCE_HPP
// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_XCODE_PBXFILEREFERENCE_HPP #define OUZEL_XCODE_PBXFILEREFERENCE_HPP #include "PBXFileElement.hpp" #include "PBXFileType.hpp" namespace ouzel::xcode { class PBXFileReference: public PBXFileElement { public: PBXFileReference() = default; std::string getIsa() const override { return "PBXFileReference"; } plist::Value encode() const override { auto result = PBXFileElement::encode(); result["explicitFileType"] = toString(fileType); result["includeInIndex"] = 0; return result; } PBXFileType fileType = PBXFileType::text; }; } #endif // OUZEL_XCODE_PBXFILEREFERENCE_HPP
Initialize fileType to avoid warnings
Initialize fileType to avoid warnings
C++
unlicense
elnormous/ouzel,elnormous/ouzel,elnormous/ouzel