text
stringlengths
54
60.6k
<commit_before>// Copyright 2020 The SwiftShader 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 "Coroutine.hpp" #include "Reactor.hpp" #include "benchmark/benchmark.h" BENCHMARK_MAIN(); class Coroutines : public benchmark::Fixture { public: void SetUp(const ::benchmark::State &state) {} void TearDown(const ::benchmark::State &state) {} }; BENCHMARK_F(Coroutines, Fibonacci) (benchmark::State &state) { using namespace rr; if(!Caps.CoroutinesSupported) { state.SkipWithError("Coroutines are not supported"); return; } Coroutine<int()> function; { Yield(Int(0)); Yield(Int(1)); Int current = 1; Int next = 1; While(true) { Yield(next); auto tmp = current + next; current = next; next = tmp; } } auto coroutine = function(); int out = 0; for(auto _ : state) { coroutine->await(out); } } <commit_msg>ReactorBenchmarks: Sweep coroutine perf.<commit_after>// Copyright 2020 The SwiftShader 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 "Coroutine.hpp" #include "Reactor.hpp" #include "benchmark/benchmark.h" BENCHMARK_MAIN(); class Coroutines : public benchmark::Fixture { public: void SetUp(const ::benchmark::State &state) {} void TearDown(const ::benchmark::State &state) {} }; BENCHMARK_DEFINE_F(Coroutines, Fibonacci) (benchmark::State &state) { using namespace rr; if(!Caps.CoroutinesSupported) { state.SkipWithError("Coroutines are not supported"); return; } Coroutine<int()> function; { Yield(Int(0)); Yield(Int(1)); Int current = 1; Int next = 1; While(true) { Yield(next); auto tmp = current + next; current = next; next = tmp; } } auto coroutine = function(); const auto iterations = state.range(0); int out = 0; for(auto _ : state) { for(int64_t i = 0; i < iterations; i++) { coroutine->await(out); } } } BENCHMARK_REGISTER_F(Coroutines, Fibonacci)->RangeMultiplier(8)->Range(1, 0x1000000)->ArgName("iterations"); <|endoftext|>
<commit_before>#include "wrapper.h" #include "wx/dialup.h" extern "C" { EWXWEXPORT(void*,wxDialUpManager_Create)() { return (void*) wxDialUpManager::Create(); } EWXWEXPORT(void,wxDialUpManager_Delete)(void* _obj) { delete (wxDialUpManager*)_obj; } EWXWEXPORT(int,wxDialUpManager_IsOk)(void* _obj) { return (int)((wxDialUpManager*)_obj)->IsOk(); } EWXWEXPORT(int,wxDialUpManager_GetISPNames)(void* _obj, void* _lst) { wxArrayString arr; ((wxDialUpManager*)_obj)->GetISPNames(arr); if (_lst) { for (unsigned int i = 0; i < arr.GetCount(); i++) #ifdef wxUSE_UNICODE ((wxChar**)_lst)[i] = wcsdup(arr.Item(i).c_str()); #else ((wxChar**)_lst)[i] = strdup(arr.Item(i).c_str()); #endif } return arr.GetCount(); } EWXWEXPORT(int,wxDialUpManager_Dial)(void* _obj, void* nameOfISP, void* username, void* password, int async) { return (int)((wxDialUpManager*)_obj)->Dial((const wxChar*)nameOfISP, (const wxChar*)username, (const wxChar*)password, async != 0); } EWXWEXPORT(int,wxDialUpManager_IsDialing)(void* _obj) { return (int)((wxDialUpManager*)_obj)->IsDialing(); } EWXWEXPORT(int,wxDialUpManager_CancelDialing)(void* _obj) { return (int)((wxDialUpManager*)_obj)->CancelDialing(); } EWXWEXPORT(int,wxDialUpManager_HangUp)(void* _obj) { return (int)((wxDialUpManager*)_obj)->HangUp(); } EWXWEXPORT(int,wxDialUpManager_IsAlwaysOnline)(void* _obj) { return (int)((wxDialUpManager*)_obj)->IsAlwaysOnline(); } EWXWEXPORT(int,wxDialUpManager_IsOnline)(void* _obj) { return (int)((wxDialUpManager*)_obj)->IsOnline(); } EWXWEXPORT(void,wxDialUpManager_SetOnlineStatus)(void* _obj, int isOnline) { ((wxDialUpManager*)_obj)->SetOnlineStatus(isOnline != 0); } EWXWEXPORT(int,wxDialUpManager_EnableAutoCheckOnlineStatus)(void* _obj, int nSeconds) { return (int)((wxDialUpManager*)_obj)->EnableAutoCheckOnlineStatus((size_t)nSeconds); } EWXWEXPORT(void,wxDialUpManager_DisableAutoCheckOnlineStatus)(void* _obj) { ((wxDialUpManager*)_obj)->DisableAutoCheckOnlineStatus(); } EWXWEXPORT(void,wxDialUpManager_SetWellKnownHost)(void* _obj, void* hostname, int portno) { ((wxDialUpManager*)_obj)->SetWellKnownHost((const wxChar*)hostname, portno); } EWXWEXPORT(void,wxDialUpManager_SetConnectCommand)(void* _obj, void* commandDial, void* commandHangup) { ((wxDialUpManager*)_obj)->SetConnectCommand((const wxChar*)commandDial, (const wxChar*)commandHangup); } EWXWEXPORT(int,wxDialUpEvent_IsConnectedEvent)(void* _obj) { return (int)((wxDialUpEvent*)_obj)->IsConnectedEvent(); } EWXWEXPORT(int,wxDialUpEvent_IsOwnEvent)(void* _obj) { return (int)((wxDialUpEvent*)_obj)->IsOwnEvent(); } } <commit_msg>Shelarcy patch (eljdialup.cpp)<commit_after>#include "wrapper.h" #include "wx/dialup.h" #if defined (wxUSE_UNICODE) && (wxUSE_UNICODE==0) # undef wxUSE_UNICODE #endif extern "C" { EWXWEXPORT(void*,wxDialUpManager_Create)() { return (void*) wxDialUpManager::Create(); } EWXWEXPORT(void,wxDialUpManager_Delete)(void* _obj) { delete (wxDialUpManager*)_obj; } EWXWEXPORT(int,wxDialUpManager_IsOk)(void* _obj) { return (int)((wxDialUpManager*)_obj)->IsOk(); } EWXWEXPORT(int,wxDialUpManager_GetISPNames)(void* _obj, void* _lst) { wxArrayString arr; ((wxDialUpManager*)_obj)->GetISPNames(arr); if (_lst) { for (unsigned int i = 0; i < arr.GetCount(); i++) #ifdef wxUSE_UNICODE ((wxChar**)_lst)[i] = wcsdup(arr.Item(i).c_str()); #else ((wxChar**)_lst)[i] = strdup(arr.Item(i).c_str()); #endif } return arr.GetCount(); } EWXWEXPORT(int,wxDialUpManager_Dial)(void* _obj, void* nameOfISP, void* username, void* password, int async) { return (int)((wxDialUpManager*)_obj)->Dial((const wxChar*)nameOfISP, (const wxChar*)username, (const wxChar*)password, async != 0); } EWXWEXPORT(int,wxDialUpManager_IsDialing)(void* _obj) { return (int)((wxDialUpManager*)_obj)->IsDialing(); } EWXWEXPORT(int,wxDialUpManager_CancelDialing)(void* _obj) { return (int)((wxDialUpManager*)_obj)->CancelDialing(); } EWXWEXPORT(int,wxDialUpManager_HangUp)(void* _obj) { return (int)((wxDialUpManager*)_obj)->HangUp(); } EWXWEXPORT(int,wxDialUpManager_IsAlwaysOnline)(void* _obj) { return (int)((wxDialUpManager*)_obj)->IsAlwaysOnline(); } EWXWEXPORT(int,wxDialUpManager_IsOnline)(void* _obj) { return (int)((wxDialUpManager*)_obj)->IsOnline(); } EWXWEXPORT(void,wxDialUpManager_SetOnlineStatus)(void* _obj, int isOnline) { ((wxDialUpManager*)_obj)->SetOnlineStatus(isOnline != 0); } EWXWEXPORT(int,wxDialUpManager_EnableAutoCheckOnlineStatus)(void* _obj, int nSeconds) { return (int)((wxDialUpManager*)_obj)->EnableAutoCheckOnlineStatus((size_t)nSeconds); } EWXWEXPORT(void,wxDialUpManager_DisableAutoCheckOnlineStatus)(void* _obj) { ((wxDialUpManager*)_obj)->DisableAutoCheckOnlineStatus(); } EWXWEXPORT(void,wxDialUpManager_SetWellKnownHost)(void* _obj, void* hostname, int portno) { ((wxDialUpManager*)_obj)->SetWellKnownHost((const wxChar*)hostname, portno); } EWXWEXPORT(void,wxDialUpManager_SetConnectCommand)(void* _obj, void* commandDial, void* commandHangup) { ((wxDialUpManager*)_obj)->SetConnectCommand((const wxChar*)commandDial, (const wxChar*)commandHangup); } EWXWEXPORT(int,wxDialUpEvent_IsConnectedEvent)(void* _obj) { return (int)((wxDialUpEvent*)_obj)->IsConnectedEvent(); } EWXWEXPORT(int,wxDialUpEvent_IsOwnEvent)(void* _obj) { return (int)((wxDialUpEvent*)_obj)->IsOwnEvent(); } } <|endoftext|>
<commit_before>/** ****************************************************************************** * Elemental Forms : a lightweight user interface framework * ****************************************************************************** * ©2015 Ben Vanik. All rights reserved. Released under the BSD license. * * Portions ©2011-2015 Emil Segerås: https://github.com/fruxo/turbobadger * ****************************************************************************** */ #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include "el/util/object.h" #include "el/util/string.h" #include "el/value.h" namespace el { // FIX: ## Floating point string conversions might be locale dependant. Force // "." as decimal! // Returns true if the given string contains space that is not at the end of the // string. bool contains_non_trailing_space(const char* str) { if (const char* p = strstr(str, " ")) { while (*p == ' ') p++; return *p != '\0'; } return false; } // Return true if the string can be represented as a number. // It ignores trailing white space. // Ex: 100, -.2 will return true. // Ex: 1.0E-8, 5px will return false. bool is_number_only(const char* s) { if (!s || *s == 0 || *s == ' ') return 0; char* p; strtod(s, &p); while (*p == ' ') p++; return *p == '\0'; } // Return true if the given number string is a float number. // Should only be called when you've verified it's a number with is_number(). bool is_number_float(const char* str) { while (*str) if (*str++ == '.') return true; return false; } char* next_token(char*& str, const char* delim) { str += strspn(str, delim); if (!*str) return nullptr; char* token = str; str += strcspn(str, delim); if (*str) *str++ = '\0'; return token; } ValueArray::ValueArray() = default; ValueArray::~ValueArray() = default; ValueArray* ValueArray::Clone(ValueArray* source) { ValueArray* new_arr = new ValueArray(); for (auto& it : source->list_) { Value* new_val = new_arr->AddValue(); new_val->Copy(*it.get()); } return new_arr; } Value* ValueArray::AddValue() { list_.push_back(std::make_unique<Value>()); return list_.back().get(); } Value* ValueArray::AddInteger(int32_t value) { auto v = AddValue(); v->set_integer(value); return v; } Value* ValueArray::at(size_t i) const { if (i >= 0 && i < list_.size()) { return list_[i].get(); } return nullptr; } Value::Value() = default; Value::Value(const Value& value) { Copy(value); } Value::Value(Type type) { switch (type) { case Type::kNull: set_null(); break; case Type::kString: set_string("", Set::kAsStatic); break; case Type::kFloat: set_float(0); break; case Type::kInt: set_integer(0); break; case Type::kObject: set_object(nullptr); break; case Type::kArray: set_array(new ValueArray(), Set::kTakeOwnership); break; default: assert(!"Not implemented!"); break; }; } Value::Value(int value) { set_integer(value); } Value::Value(float value) { set_float(value); } Value::Value(const char* value, Set set) { set_string(value, set); } Value::Value(util::TypedObject* object) { set_object(object); } Value::~Value() { set_null(); } void Value::TakeOver(Value& source_value) { if (Type(source_value.packed_.type) == Type::kString) { set_string(source_value.value_.string, source_value.packed_.allocated ? Set::kTakeOwnership : Set::kNewCopy); } else if (source_value.type() == Type::kArray) { set_array(source_value.value_.value_array, source_value.packed_.allocated ? Set::kTakeOwnership : Set::kNewCopy); } else { *this = source_value; } source_value.set_type(Type::kNull); } void Value::Copy(const Value& source_value) { if (source_value.type() == Type::kString) { set_string(source_value.value_.string, Set::kNewCopy); } else if (source_value.type() == Type::kArray) { set_array(source_value.value_.value_array, Set::kNewCopy); } else if (source_value.type() == Type::kObject) { assert(!"We can't copy objects! The value will be nulled!"); set_object(nullptr); } else { set_null(); std::memcpy(this, &source_value, sizeof(Value)); } } void Value::set_null() { if (packed_.allocated) { if (type() == Type::kString) { free(value_.string); value_.string = nullptr; } else if (type() == Type::kObject) { delete value_.object; value_.object = nullptr; } else if (type() == Type::kArray) { delete value_.value_array; value_.value_array = nullptr; } } set_type(Type::kNull); } void Value::set_integer(int val) { set_null(); set_type(Type::kInt); value_.integer_number = val; } void Value::set_float(float val) { set_null(); set_type(Type::kFloat); value_.float_number = val; } void Value::set_string(const char* val, Set set) { set_null(); packed_.allocated = set == Set::kNewCopy || set == Set::kTakeOwnership; if (set != Set::kNewCopy) { value_.string = const_cast<char*>(val); set_type(Type::kString); } else if ((value_.string = strdup(val))) { set_type(Type::kString); } } void Value::set_object(util::TypedObject* object) { set_null(); set_type(Type::kObject); packed_.allocated = true; value_.object = object; } void Value::set_array(ValueArray* arr, Set set) { set_null(); packed_.allocated = set == Set::kNewCopy || set == Set::kTakeOwnership; if (set != Set::kNewCopy) { value_.value_array = arr; set_type(Type::kArray); } else if ((value_.value_array = ValueArray::Clone(arr))) { set_type(Type::kArray); } } void Value::parse_string(const char* str, Set set) { if (!str) { set_null(); } else if (is_number_only(str)) { if (is_number_float(str)) { set_float((float)atof(str)); } else { set_integer(atoi(str)); } } else if (util::is_start_of_number(str) && contains_non_trailing_space(str)) { // If the number has nontrailing space, we'll assume a list of numbers. // (example: "10 -4 3.5") set_null(); ValueArray* arr = new ValueArray(); std::string tmpstr = str; char* str_next = (char*)tmpstr.data(); while (char* token = next_token(str_next, ", ")) { Value* new_val = arr->AddValue(); new_val->parse_string(token, Set::kNewCopy); } set_array(arr, Set::kTakeOwnership); } else if (*str == '[') { set_null(); ValueArray* arr = new ValueArray(); assert(!"not implemented! Split out the tokenizer code above!"); set_array(arr, Set::kTakeOwnership); } else { set_string(str, set); return; } // We didn't set as string, so we might need to deal with the passed in string // data. if (set == Set::kTakeOwnership) { // Delete the passed in data. Value tmp; tmp.set_string(str, Set::kTakeOwnership); } } int Value::as_integer() const { if (type() == Type::kString) { return atoi(value_.string); } else if (type() == Type::kFloat) { return (int)value_.float_number; } return type() == Type::kInt ? value_.integer_number : 0; } float Value::as_float() const { if (type() == Type::kString) { return (float)atof(value_.string); } else if (type() == Type::kInt) { return (float)value_.integer_number; } return type() == Type::kFloat ? value_.float_number : 0; } const char* Value::as_string() { if (type() == Type::kInt) { char tmp[32]; sprintf(tmp, "%d", value_.integer_number); set_string(tmp, Set::kNewCopy); } else if (type() == Type::kFloat) { char tmp[32]; sprintf(tmp, "%f", value_.float_number); set_string(tmp, Set::kNewCopy); } else if (type() == Type::kObject) { return value_.object ? value_.object->GetTypeName() : ""; } return type() == Type::kString ? value_.string : ""; } std::string Value::to_string() const { switch (type()) { case Type::kNull: return ""; case Type::kString: return value_.string; case Type::kFloat: return std::to_string(value_.float_number); case Type::kInt: return std::to_string(value_.integer_number); case Type::kObject: return value_.object ? value_.object->GetTypeName() : ""; case Type::kArray: { std::string result; for (size_t i = 0; i < value_.value_array->size(); ++i) { auto value = value_.value_array->at(i); if (i) { result += " " + value->to_string(); } else { result += value->to_string(); } } return result; } default: return ""; } } } // namespace el <commit_msg>Remove check if size_t >= 0<commit_after>/** ****************************************************************************** * Elemental Forms : a lightweight user interface framework * ****************************************************************************** * ©2015 Ben Vanik. All rights reserved. Released under the BSD license. * * Portions ©2011-2015 Emil Segerås: https://github.com/fruxo/turbobadger * ****************************************************************************** */ #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include "el/util/object.h" #include "el/util/string.h" #include "el/value.h" namespace el { // FIX: ## Floating point string conversions might be locale dependant. Force // "." as decimal! // Returns true if the given string contains space that is not at the end of the // string. bool contains_non_trailing_space(const char* str) { if (const char* p = strstr(str, " ")) { while (*p == ' ') p++; return *p != '\0'; } return false; } // Return true if the string can be represented as a number. // It ignores trailing white space. // Ex: 100, -.2 will return true. // Ex: 1.0E-8, 5px will return false. bool is_number_only(const char* s) { if (!s || *s == 0 || *s == ' ') return 0; char* p; strtod(s, &p); while (*p == ' ') p++; return *p == '\0'; } // Return true if the given number string is a float number. // Should only be called when you've verified it's a number with is_number(). bool is_number_float(const char* str) { while (*str) if (*str++ == '.') return true; return false; } char* next_token(char*& str, const char* delim) { str += strspn(str, delim); if (!*str) return nullptr; char* token = str; str += strcspn(str, delim); if (*str) *str++ = '\0'; return token; } ValueArray::ValueArray() = default; ValueArray::~ValueArray() = default; ValueArray* ValueArray::Clone(ValueArray* source) { ValueArray* new_arr = new ValueArray(); for (auto& it : source->list_) { Value* new_val = new_arr->AddValue(); new_val->Copy(*it.get()); } return new_arr; } Value* ValueArray::AddValue() { list_.push_back(std::make_unique<Value>()); return list_.back().get(); } Value* ValueArray::AddInteger(int32_t value) { auto v = AddValue(); v->set_integer(value); return v; } Value* ValueArray::at(size_t i) const { if (i < list_.size()) { return list_[i].get(); } return nullptr; } Value::Value() = default; Value::Value(const Value& value) { Copy(value); } Value::Value(Type type) { switch (type) { case Type::kNull: set_null(); break; case Type::kString: set_string("", Set::kAsStatic); break; case Type::kFloat: set_float(0); break; case Type::kInt: set_integer(0); break; case Type::kObject: set_object(nullptr); break; case Type::kArray: set_array(new ValueArray(), Set::kTakeOwnership); break; default: assert(!"Not implemented!"); break; }; } Value::Value(int value) { set_integer(value); } Value::Value(float value) { set_float(value); } Value::Value(const char* value, Set set) { set_string(value, set); } Value::Value(util::TypedObject* object) { set_object(object); } Value::~Value() { set_null(); } void Value::TakeOver(Value& source_value) { if (Type(source_value.packed_.type) == Type::kString) { set_string(source_value.value_.string, source_value.packed_.allocated ? Set::kTakeOwnership : Set::kNewCopy); } else if (source_value.type() == Type::kArray) { set_array(source_value.value_.value_array, source_value.packed_.allocated ? Set::kTakeOwnership : Set::kNewCopy); } else { *this = source_value; } source_value.set_type(Type::kNull); } void Value::Copy(const Value& source_value) { if (source_value.type() == Type::kString) { set_string(source_value.value_.string, Set::kNewCopy); } else if (source_value.type() == Type::kArray) { set_array(source_value.value_.value_array, Set::kNewCopy); } else if (source_value.type() == Type::kObject) { assert(!"We can't copy objects! The value will be nulled!"); set_object(nullptr); } else { set_null(); std::memcpy(this, &source_value, sizeof(Value)); } } void Value::set_null() { if (packed_.allocated) { if (type() == Type::kString) { free(value_.string); value_.string = nullptr; } else if (type() == Type::kObject) { delete value_.object; value_.object = nullptr; } else if (type() == Type::kArray) { delete value_.value_array; value_.value_array = nullptr; } } set_type(Type::kNull); } void Value::set_integer(int val) { set_null(); set_type(Type::kInt); value_.integer_number = val; } void Value::set_float(float val) { set_null(); set_type(Type::kFloat); value_.float_number = val; } void Value::set_string(const char* val, Set set) { set_null(); packed_.allocated = set == Set::kNewCopy || set == Set::kTakeOwnership; if (set != Set::kNewCopy) { value_.string = const_cast<char*>(val); set_type(Type::kString); } else if ((value_.string = strdup(val))) { set_type(Type::kString); } } void Value::set_object(util::TypedObject* object) { set_null(); set_type(Type::kObject); packed_.allocated = true; value_.object = object; } void Value::set_array(ValueArray* arr, Set set) { set_null(); packed_.allocated = set == Set::kNewCopy || set == Set::kTakeOwnership; if (set != Set::kNewCopy) { value_.value_array = arr; set_type(Type::kArray); } else if ((value_.value_array = ValueArray::Clone(arr))) { set_type(Type::kArray); } } void Value::parse_string(const char* str, Set set) { if (!str) { set_null(); } else if (is_number_only(str)) { if (is_number_float(str)) { set_float((float)atof(str)); } else { set_integer(atoi(str)); } } else if (util::is_start_of_number(str) && contains_non_trailing_space(str)) { // If the number has nontrailing space, we'll assume a list of numbers. // (example: "10 -4 3.5") set_null(); ValueArray* arr = new ValueArray(); std::string tmpstr = str; char* str_next = (char*)tmpstr.data(); while (char* token = next_token(str_next, ", ")) { Value* new_val = arr->AddValue(); new_val->parse_string(token, Set::kNewCopy); } set_array(arr, Set::kTakeOwnership); } else if (*str == '[') { set_null(); ValueArray* arr = new ValueArray(); assert(!"not implemented! Split out the tokenizer code above!"); set_array(arr, Set::kTakeOwnership); } else { set_string(str, set); return; } // We didn't set as string, so we might need to deal with the passed in string // data. if (set == Set::kTakeOwnership) { // Delete the passed in data. Value tmp; tmp.set_string(str, Set::kTakeOwnership); } } int Value::as_integer() const { if (type() == Type::kString) { return atoi(value_.string); } else if (type() == Type::kFloat) { return (int)value_.float_number; } return type() == Type::kInt ? value_.integer_number : 0; } float Value::as_float() const { if (type() == Type::kString) { return (float)atof(value_.string); } else if (type() == Type::kInt) { return (float)value_.integer_number; } return type() == Type::kFloat ? value_.float_number : 0; } const char* Value::as_string() { if (type() == Type::kInt) { char tmp[32]; sprintf(tmp, "%d", value_.integer_number); set_string(tmp, Set::kNewCopy); } else if (type() == Type::kFloat) { char tmp[32]; sprintf(tmp, "%f", value_.float_number); set_string(tmp, Set::kNewCopy); } else if (type() == Type::kObject) { return value_.object ? value_.object->GetTypeName() : ""; } return type() == Type::kString ? value_.string : ""; } std::string Value::to_string() const { switch (type()) { case Type::kNull: return ""; case Type::kString: return value_.string; case Type::kFloat: return std::to_string(value_.float_number); case Type::kInt: return std::to_string(value_.integer_number); case Type::kObject: return value_.object ? value_.object->GetTypeName() : ""; case Type::kArray: { std::string result; for (size_t i = 0; i < value_.value_array->size(); ++i) { auto value = value_.value_array->at(i); if (i) { result += " " + value->to_string(); } else { result += value->to_string(); } } return result; } default: return ""; } } } // namespace el <|endoftext|>
<commit_before>#include <common/buffer.h> #include <common/endian.h> #include <event/event_callback.h> #include <io/pipe/pipe.h> #include <io/pipe/pipe_pair.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_cache.h> #include <xcodec/xcodec_decoder.h> #include <xcodec/xcodec_encoder.h> #include <xcodec/xcodec_hash.h> #include <xcodec/xcodec_pipe_pair.h> /* * And now for something completely different, a note on how end-of-stream * indication works with the XCodec. * * When things are going along smoothly, the XCodec is a nice one-way stream * compressor. All you need is state that you already have or state from * earlier in the stream. However, it doesn't take much for things to go less * smoothly. When you have two connections, a symbol may be defined in the * first and referenced in the second, and the reference in the second stream * may be decoded before the definition in the first one. In this case, we * have <ASK> and <LEARN> in the <OOB> stream to communicate bidirectionally * to get the reference. If we're actually going to get the definition soon, * that's a bit wasteful, and there are a lot of optimizations we can make, * but the basic principle needs to be robust in case, say, the first * connection goes down. * * Because of this, we can't just pass through end-of-stream indicators * freely. When the encoder receives EOS from a StreamChannel, we could then * send EOS out to the StreamChannel that connects us to the decoder on the * other side of the network. But what if that decoder needs to <ASK> us * about a symbol we sent a reference to just before EOS? * * So we send <EOS> rather than EOS, a message saying that the encoded stream * has ended. * * When the decoder receives <EOS> it can send EOS on to the StreamChannel it * is writing to, assuming it has processed all outstanding frame data. And * when it has finished processing all outstanding frame data, it will send * <EOS_ACK> on the encoder's output StreamChannel, to the remote decoder. * When both sides have sent <EOS_ACK>, the encoder's StreamChannels may be * shut down and no more communication will occur. */ /* * Usage: * <OP_HELLO> length[uint8_t] data[uint8_t x length] * * Effects: * Must appear at the start of and only at the start of an encoded stream. * * Sife-effects: * Possibly many. */ #define XCODEC_PIPE_OP_HELLO ((uint8_t)0xff) /* * Usage: * <OP_LEARN> data[uint8_t x XCODEC_PIPE_SEGMENT_LENGTH] * * Effects: * The `data' is hashed, the hash is associated with the data if possible. * * Side-effects: * None. */ #define XCODEC_PIPE_OP_LEARN ((uint8_t)0xfe) /* * Usage: * <OP_ASK> hash[uint64_t] * * Effects: * An OP_LEARN will be sent in response with the data corresponding to the * hash. * * If the hash is unknown, error will be indicated. * * Side-effects: * None. */ #define XCODEC_PIPE_OP_ASK ((uint8_t)0xfd) /* * Usage: * <OP_EOS> * * Effects: * Alert the other party that we have no intention of sending more data. * * Side-effects: * The other party will send <OP_EOS_ACK> when it has processed all of * the data we have sent. */ #define XCODEC_PIPE_OP_EOS ((uint8_t)0xfc) /* * Usage: * <OP_EOS_ACK> * * Effects: * Alert the other party that we have no intention of reading more data. * * Side-effects: * The connection will be torn down. */ #define XCODEC_PIPE_OP_EOS_ACK ((uint8_t)0xfb) /* * Usage: * <FRAME> length[uint16_t] data[uint8_t x length] * * Effects: * Frames an encoded chunk. As distinct to OP_OOB below. * * Side-effects: * None. */ #define XCODEC_PIPE_OP_FRAME ((uint8_t)0x00) #define XCODEC_PIPE_MAX_FRAME (32768) static void encode_frame(Buffer *, Buffer *); void XCodecPipePair::decoder_consume(Buffer *buf) { if (buf->empty()) { if (!decoder_buffer_.empty()) ERROR(log_) << "Remote encoder closed connection with data outstanding."; if (!decoder_frame_buffer_.empty()) ERROR(log_) << "Remote encoder closed connection with frame data outstanding."; if (!decoder_sent_eos_) { decoder_sent_eos_ = true; decoder_produce(buf); } return; } decoder_buffer_.append(buf); buf->clear(); while (!decoder_buffer_.empty()) { if (decoder_buffer_.length() < sizeof (uint8_t) + sizeof (uint8_t) + sizeof (uint16_t)) break; uint8_t op = decoder_buffer_.peek(); switch (op) { case XCODEC_PIPE_OP_HELLO: if (decoder_cache_ != NULL) { ERROR(log_) << "Got <HELLO> twice."; decoder_error(); return; } else { uint8_t len; if (decoder_buffer_.length() < sizeof op + sizeof len) return; decoder_buffer_.copyout(&len, sizeof op, sizeof len); if (decoder_buffer_.length() < sizeof op + sizeof len + len) return; if (len != UUID_SIZE) { ERROR(log_) << "Unsupported <HELLO> length: " << (unsigned)len; decoder_error(); return; } Buffer uubuf; decoder_buffer_.moveout(&uubuf, sizeof op + sizeof len, UUID_SIZE); UUID uuid; if (!uuid.decode(&uubuf)) { ERROR(log_) << "Invalid UUID in <HELLO>."; decoder_error(); return; } decoder_cache_ = XCodecCache::lookup(uuid); ASSERT(decoder_cache_ != NULL); ASSERT(decoder_ == NULL); decoder_ = new XCodecDecoder(decoder_cache_); DEBUG(log_) << "Peer connected with UUID: " << uuid.string_; } break; case XCODEC_PIPE_OP_ASK: if (encoder_ == NULL) { ERROR(log_) << "Got <ASK> before sending <HELLO>."; decoder_error(); return; } else { uint64_t hash; if (decoder_buffer_.length() < sizeof op + sizeof hash) return; decoder_buffer_.extract(&hash, sizeof op); hash = BigEndian::decode(hash); BufferSegment *oseg = codec_->cache()->lookup(hash); if (oseg == NULL) { ERROR(log_) << "Unknown hash in <ASK>: " << hash; decoder_error(); return; } DEBUG(log_) << "Responding to <ASK> with <LEARN>."; Buffer learn; learn.append(XCODEC_PIPE_OP_LEARN); learn.append(oseg); oseg->unref(); encoder_produce(&learn); } break; case XCODEC_PIPE_OP_LEARN: if (decoder_cache_ == NULL) { ERROR(log_) << "Got <LEARN> before <HELLO>."; decoder_error(); return; } else { if (decoder_buffer_.length() < sizeof op + XCODEC_SEGMENT_LENGTH) return; decoder_buffer_.skip(sizeof op); BufferSegment *seg; decoder_buffer_.copyout(&seg, XCODEC_SEGMENT_LENGTH); decoder_buffer_.skip(XCODEC_SEGMENT_LENGTH); uint64_t hash = XCodecHash<XCODEC_SEGMENT_LENGTH>::hash(seg->data()); if (decoder_unknown_hashes_.find(hash) == decoder_unknown_hashes_.end()) { INFO(log_) << "Gratuitous <LEARN> without <ASK>."; } else { decoder_unknown_hashes_.erase(hash); } BufferSegment *oseg = decoder_cache_->lookup(hash); if (oseg != NULL) { if (!oseg->equal(seg)) { oseg->unref(); ERROR(log_) << "Collision in <LEARN>."; seg->unref(); decoder_error(); return; } oseg->unref(); DEBUG(log_) << "Redundant <LEARN>."; } else { DEBUG(log_) << "Successful <LEARN>."; decoder_cache_->enter(hash, seg); } seg->unref(); } break; case XCODEC_PIPE_OP_EOS: if (decoder_received_eos_) { ERROR(log_) << "Duplicate <EOS>."; decoder_error(); return; } decoder_received_eos_ = true; break; case XCODEC_PIPE_OP_EOS_ACK: if (!encoder_sent_eos_) { ERROR(log_) << "Got <EOS_ACK> before sending <EOS>."; decoder_error(); return; } if (decoder_received_eos_ack_) { ERROR(log_) << "Duplicate <EOS_ACK>."; decoder_error(); return; } decoder_received_eos_ack_ = true; break; case XCODEC_PIPE_OP_FRAME: if (decoder_ == NULL) { ERROR(log_) << "Got frame data before decoder initialized."; decoder_error(); return; } else { uint16_t len; decoder_buffer_.extract(&len, sizeof op); len = BigEndian::decode(len); if (len == 0 || len > XCODEC_PIPE_MAX_FRAME) { ERROR(log_) << "Invalid framed data length."; decoder_error(); return; } if (decoder_buffer_.length() < sizeof op + sizeof len + len) return; decoder_buffer_.moveout(&decoder_frame_buffer_, sizeof op + sizeof len, len); } break; default: ERROR(log_) << "Unsupported operation in pipe stream."; decoder_error(); return; } if (decoder_frame_buffer_.empty()) { if (decoder_received_eos_ && !encoder_sent_eos_ack_) { DEBUG(log_) << "Decoder finished, got <EOS>, sending <EOS_ACK>."; Buffer eos_ack; eos_ack.append(XCODEC_PIPE_OP_EOS_ACK); encoder_produce(&eos_ack); encoder_sent_eos_ack_ = true; } continue; } if (!decoder_unknown_hashes_.empty()) { DEBUG(log_) << "Waiting for unknown hashes to continue processing data."; continue; } Buffer output; if (!decoder_->decode(&output, &decoder_frame_buffer_, decoder_unknown_hashes_)) { ERROR(log_) << "Decoder exiting with error."; decoder_error(); return; } if (!output.empty()) { decoder_produce(&output); } else { /* * We should only get no output from the decoder if * we're waiting on the next frame. It would be nice * to make the encoder framing aware so that it would * not end up with encoded data that straddles a frame * boundary. (Fixing that would also allow us to * simplify length checking within the decoder * considerably.) */ ASSERT(!decoder_frame_buffer_.empty()); } } if (decoder_received_eos_ && !decoder_sent_eos_) { DEBUG(log_) << "Decoder finished, got <EOS>, shutting down decoder output channel."; Buffer eos; decoder_produce(&eos); decoder_sent_eos_ = true; } if (encoder_sent_eos_ack_ && decoder_received_eos_ack_) { ASSERT(decoder_buffer_.empty()); ASSERT(decoder_frame_buffer_.empty()); DEBUG(log_) << "Decoder finished, got <EOS_ACK>, shutting down encoder output channel."; Buffer eos; encoder_produce(&eos); } } void XCodecPipePair::encoder_consume(Buffer *buf) { ASSERT(!encoder_sent_eos_); Buffer output; if (encoder_ == NULL) { Buffer extra; if (!codec_->cache()->uuid_encode(&extra)) { ERROR(log_) << "Could not encode UUID for <HELLO>."; encoder_error(); return; } uint8_t len = extra.length(); ASSERT(len == UUID_SIZE); output.append(XCODEC_PIPE_OP_HELLO); output.append(len); output.append(extra); ASSERT(output.length() == 2 + UUID_SIZE); encoder_ = new XCodecEncoder(codec_->cache()); } if (!buf->empty()) { Buffer encoded; encoder_->encode(&encoded, buf); ASSERT(!encoded.empty()); encode_frame(&output, &encoded); ASSERT(!output.empty()); } else { output.append(XCODEC_PIPE_OP_EOS); encoder_sent_eos_ = true; } encoder_produce(&output); } static void encode_frame(Buffer *out, Buffer *in) { while (!in->empty()) { uint16_t framelen; if (in->length() <= XCODEC_PIPE_MAX_FRAME) framelen = in->length(); else framelen = XCODEC_PIPE_MAX_FRAME; Buffer frame; in->moveout(&frame, framelen); framelen = BigEndian::encode(framelen); out->append(XCODEC_PIPE_OP_FRAME); out->append(&framelen); out->append(frame); } } <commit_msg>Attempt to handle ASKs properly.<commit_after>#include <common/buffer.h> #include <common/endian.h> #include <event/event_callback.h> #include <io/pipe/pipe.h> #include <io/pipe/pipe_pair.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_cache.h> #include <xcodec/xcodec_decoder.h> #include <xcodec/xcodec_encoder.h> #include <xcodec/xcodec_hash.h> #include <xcodec/xcodec_pipe_pair.h> /* * And now for something completely different, a note on how end-of-stream * indication works with the XCodec. * * When things are going along smoothly, the XCodec is a nice one-way stream * compressor. All you need is state that you already have or state from * earlier in the stream. However, it doesn't take much for things to go less * smoothly. When you have two connections, a symbol may be defined in the * first and referenced in the second, and the reference in the second stream * may be decoded before the definition in the first one. In this case, we * have <ASK> and <LEARN> in the <OOB> stream to communicate bidirectionally * to get the reference. If we're actually going to get the definition soon, * that's a bit wasteful, and there are a lot of optimizations we can make, * but the basic principle needs to be robust in case, say, the first * connection goes down. * * Because of this, we can't just pass through end-of-stream indicators * freely. When the encoder receives EOS from a StreamChannel, we could then * send EOS out to the StreamChannel that connects us to the decoder on the * other side of the network. But what if that decoder needs to <ASK> us * about a symbol we sent a reference to just before EOS? * * So we send <EOS> rather than EOS, a message saying that the encoded stream * has ended. * * When the decoder receives <EOS> it can send EOS on to the StreamChannel it * is writing to, assuming it has processed all outstanding frame data. And * when it has finished processing all outstanding frame data, it will send * <EOS_ACK> on the encoder's output StreamChannel, to the remote decoder. * When both sides have sent <EOS_ACK>, the encoder's StreamChannels may be * shut down and no more communication will occur. */ /* * Usage: * <OP_HELLO> length[uint8_t] data[uint8_t x length] * * Effects: * Must appear at the start of and only at the start of an encoded stream. * * Sife-effects: * Possibly many. */ #define XCODEC_PIPE_OP_HELLO ((uint8_t)0xff) /* * Usage: * <OP_LEARN> data[uint8_t x XCODEC_PIPE_SEGMENT_LENGTH] * * Effects: * The `data' is hashed, the hash is associated with the data if possible. * * Side-effects: * None. */ #define XCODEC_PIPE_OP_LEARN ((uint8_t)0xfe) /* * Usage: * <OP_ASK> hash[uint64_t] * * Effects: * An OP_LEARN will be sent in response with the data corresponding to the * hash. * * If the hash is unknown, error will be indicated. * * Side-effects: * None. */ #define XCODEC_PIPE_OP_ASK ((uint8_t)0xfd) /* * Usage: * <OP_EOS> * * Effects: * Alert the other party that we have no intention of sending more data. * * Side-effects: * The other party will send <OP_EOS_ACK> when it has processed all of * the data we have sent. */ #define XCODEC_PIPE_OP_EOS ((uint8_t)0xfc) /* * Usage: * <OP_EOS_ACK> * * Effects: * Alert the other party that we have no intention of reading more data. * * Side-effects: * The connection will be torn down. */ #define XCODEC_PIPE_OP_EOS_ACK ((uint8_t)0xfb) /* * Usage: * <FRAME> length[uint16_t] data[uint8_t x length] * * Effects: * Frames an encoded chunk. As distinct to OP_OOB below. * * Side-effects: * None. */ #define XCODEC_PIPE_OP_FRAME ((uint8_t)0x00) #define XCODEC_PIPE_MAX_FRAME (32768) static void encode_frame(Buffer *, Buffer *); void XCodecPipePair::decoder_consume(Buffer *buf) { if (buf->empty()) { if (!decoder_buffer_.empty()) ERROR(log_) << "Remote encoder closed connection with data outstanding."; if (!decoder_frame_buffer_.empty()) ERROR(log_) << "Remote encoder closed connection with frame data outstanding."; if (!decoder_sent_eos_) { decoder_sent_eos_ = true; decoder_produce(buf); } return; } decoder_buffer_.append(buf); buf->clear(); while (!decoder_buffer_.empty()) { uint8_t op = decoder_buffer_.peek(); switch (op) { case XCODEC_PIPE_OP_HELLO: if (decoder_cache_ != NULL) { ERROR(log_) << "Got <HELLO> twice."; decoder_error(); return; } else { uint8_t len; if (decoder_buffer_.length() < sizeof op + sizeof len) return; decoder_buffer_.copyout(&len, sizeof op, sizeof len); if (decoder_buffer_.length() < sizeof op + sizeof len + len) return; if (len != UUID_SIZE) { ERROR(log_) << "Unsupported <HELLO> length: " << (unsigned)len; decoder_error(); return; } Buffer uubuf; decoder_buffer_.moveout(&uubuf, sizeof op + sizeof len, UUID_SIZE); UUID uuid; if (!uuid.decode(&uubuf)) { ERROR(log_) << "Invalid UUID in <HELLO>."; decoder_error(); return; } decoder_cache_ = XCodecCache::lookup(uuid); ASSERT(decoder_cache_ != NULL); ASSERT(decoder_ == NULL); decoder_ = new XCodecDecoder(decoder_cache_); DEBUG(log_) << "Peer connected with UUID: " << uuid.string_; } break; case XCODEC_PIPE_OP_ASK: if (encoder_ == NULL) { ERROR(log_) << "Got <ASK> before sending <HELLO>."; decoder_error(); return; } else { uint64_t hash; if (decoder_buffer_.length() < sizeof op + sizeof hash) return; decoder_buffer_.extract(&hash, sizeof op); hash = BigEndian::decode(hash); BufferSegment *oseg = codec_->cache()->lookup(hash); if (oseg == NULL) { ERROR(log_) << "Unknown hash in <ASK>: " << hash; decoder_error(); return; } DEBUG(log_) << "Responding to <ASK> with <LEARN>."; Buffer learn; learn.append(XCODEC_PIPE_OP_LEARN); learn.append(oseg); oseg->unref(); encoder_produce(&learn); } break; case XCODEC_PIPE_OP_LEARN: if (decoder_cache_ == NULL) { ERROR(log_) << "Got <LEARN> before <HELLO>."; decoder_error(); return; } else { if (decoder_buffer_.length() < sizeof op + XCODEC_SEGMENT_LENGTH) return; decoder_buffer_.skip(sizeof op); BufferSegment *seg; decoder_buffer_.copyout(&seg, XCODEC_SEGMENT_LENGTH); decoder_buffer_.skip(XCODEC_SEGMENT_LENGTH); uint64_t hash = XCodecHash<XCODEC_SEGMENT_LENGTH>::hash(seg->data()); if (decoder_unknown_hashes_.find(hash) == decoder_unknown_hashes_.end()) { INFO(log_) << "Gratuitous <LEARN> without <ASK>."; } else { decoder_unknown_hashes_.erase(hash); } BufferSegment *oseg = decoder_cache_->lookup(hash); if (oseg != NULL) { if (!oseg->equal(seg)) { oseg->unref(); ERROR(log_) << "Collision in <LEARN>."; seg->unref(); decoder_error(); return; } oseg->unref(); DEBUG(log_) << "Redundant <LEARN>."; } else { DEBUG(log_) << "Successful <LEARN>."; decoder_cache_->enter(hash, seg); } seg->unref(); } break; case XCODEC_PIPE_OP_EOS: if (decoder_received_eos_) { ERROR(log_) << "Duplicate <EOS>."; decoder_error(); return; } decoder_received_eos_ = true; break; case XCODEC_PIPE_OP_EOS_ACK: if (!encoder_sent_eos_) { ERROR(log_) << "Got <EOS_ACK> before sending <EOS>."; decoder_error(); return; } if (decoder_received_eos_ack_) { ERROR(log_) << "Duplicate <EOS_ACK>."; decoder_error(); return; } decoder_received_eos_ack_ = true; break; case XCODEC_PIPE_OP_FRAME: if (decoder_ == NULL) { ERROR(log_) << "Got frame data before decoder initialized."; decoder_error(); return; } else { uint16_t len; decoder_buffer_.extract(&len, sizeof op); len = BigEndian::decode(len); if (len == 0 || len > XCODEC_PIPE_MAX_FRAME) { ERROR(log_) << "Invalid framed data length."; decoder_error(); return; } if (decoder_buffer_.length() < sizeof op + sizeof len + len) return; decoder_buffer_.moveout(&decoder_frame_buffer_, sizeof op + sizeof len, len); } break; default: ERROR(log_) << "Unsupported operation in pipe stream."; decoder_error(); return; } if (decoder_frame_buffer_.empty()) { if (decoder_received_eos_ && !encoder_sent_eos_ack_) { DEBUG(log_) << "Decoder finished, got <EOS>, sending <EOS_ACK>."; Buffer eos_ack; eos_ack.append(XCODEC_PIPE_OP_EOS_ACK); encoder_produce(&eos_ack); encoder_sent_eos_ack_ = true; } continue; } if (!decoder_unknown_hashes_.empty()) { DEBUG(log_) << "Waiting for unknown hashes to continue processing data."; continue; } Buffer output; if (!decoder_->decode(&output, &decoder_frame_buffer_, decoder_unknown_hashes_)) { ERROR(log_) << "Decoder exiting with error."; decoder_error(); return; } if (!output.empty()) { decoder_produce(&output); } else { /* * We should only get no output from the decoder if * we're waiting on the next frame. It would be nice * to make the encoder framing aware so that it would * not end up with encoded data that straddles a frame * boundary. (Fixing that would also allow us to * simplify length checking within the decoder * considerably.) */ ASSERT(!decoder_frame_buffer_.empty()); } Buffer ask; std::set<uint64_t>::const_iterator it; for (it = decoder_unknown_hashes_.begin(); it != decoder_unknown_hashes_.end(); ++it) { uint64_t hash = *it; hash = BigEndian::encode(hash); ask.append(XCODEC_PIPE_OP_ASK); ask.append(&hash); } if (!ask.empty()) { DEBUG(log_) << "Sending <ASK>s."; encoder_produce(&ask); } } if (decoder_received_eos_ && !decoder_sent_eos_) { DEBUG(log_) << "Decoder finished, got <EOS>, shutting down decoder output channel."; Buffer eos; decoder_produce(&eos); decoder_sent_eos_ = true; } if (encoder_sent_eos_ack_ && decoder_received_eos_ack_) { ASSERT(decoder_buffer_.empty()); ASSERT(decoder_frame_buffer_.empty()); DEBUG(log_) << "Decoder finished, got <EOS_ACK>, shutting down encoder output channel."; Buffer eos; encoder_produce(&eos); } } void XCodecPipePair::encoder_consume(Buffer *buf) { ASSERT(!encoder_sent_eos_); Buffer output; if (encoder_ == NULL) { Buffer extra; if (!codec_->cache()->uuid_encode(&extra)) { ERROR(log_) << "Could not encode UUID for <HELLO>."; encoder_error(); return; } uint8_t len = extra.length(); ASSERT(len == UUID_SIZE); output.append(XCODEC_PIPE_OP_HELLO); output.append(len); output.append(extra); ASSERT(output.length() == 2 + UUID_SIZE); encoder_ = new XCodecEncoder(codec_->cache()); } if (!buf->empty()) { Buffer encoded; encoder_->encode(&encoded, buf); ASSERT(!encoded.empty()); encode_frame(&output, &encoded); ASSERT(!output.empty()); } else { output.append(XCODEC_PIPE_OP_EOS); encoder_sent_eos_ = true; } encoder_produce(&output); } static void encode_frame(Buffer *out, Buffer *in) { while (!in->empty()) { uint16_t framelen; if (in->length() <= XCODEC_PIPE_MAX_FRAME) framelen = in->length(); else framelen = XCODEC_PIPE_MAX_FRAME; Buffer frame; in->moveout(&frame, framelen); framelen = BigEndian::encode(framelen); out->append(XCODEC_PIPE_OP_FRAME); out->append(&framelen); out->append(frame); } } <|endoftext|>
<commit_before>/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2014, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ /*----------------------------------------------------------------------------- APPLICATION: MEX-grabber FILE: mexgrabber.cpp AUTHORS: Jesus Briales Garcia <[email protected]> Jose Luis Blanco Claraco <[email protected]> For instructions and details, see: http://www.mrpt.org/Application:MEX-grabber -----------------------------------------------------------------------------*/ #include <mrpt/hwdrivers/CGenericSensor.h> #include <mrpt/utils/CConfigFile.h> #include <mrpt/utils/CFileGZOutputStream.h> #include <mrpt/utils/CImage.h> #include <mrpt/utils/round.h> #include <mrpt/slam/CActionCollection.h> #include <mrpt/slam/CSensoryFrame.h> #include <mrpt/slam/CObservationOdometry.h> #include <mrpt/slam/CObservationGPS.h> #include <mrpt/slam/CObservationIMU.h> #include <mrpt/slam/CActionRobotMovement2D.h> #include <mrpt/system/os.h> #include <mrpt/system/filesystem.h> // Matlab MEX interface headers #include <mexplus.h> // Force here using mexPrintf instead of printf #define printf mexPrintf using namespace mrpt; using namespace mrpt::system; using namespace mrpt::hwdrivers; using namespace mrpt::utils; using namespace mrpt::slam; using namespace std; using namespace mexplus; const std::string GLOBAL_SECTION_NAME = "global"; // Forward declarations: struct TThreadParams { CConfigFile *cfgFile; string sensor_label; }; void SensorThread(TThreadParams params); CGenericSensor::TListObservations global_list_obs; synch::CCriticalSection cs_global_list_obs; bool allThreadsMustExit = false; // Thread handlers vector stored as global (persistent MEX variables) vector<TThreadHandle> lstThreads; // State variables bool mex_is_running = false; // Configuration variables MRPT_TODO("Set as variable controlled from Matlab") size_t max_num_obs = 50; /* Important: * All global variables will be stored between MEX calls, * and can be used by running threads backstage. */ namespace { // Defines MEX API for new. MEX_DEFINE(new) (int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { printf(" mex-grabber - Part of the MRPT\n"); printf(" MRPT C++ Library: %s - BUILD DATE %s\n", MRPT_getVersion().c_str(), MRPT_getCompilationDate().c_str()); printf("-------------------------------------------------------------------\n"); mexplus::InputArguments input(nrhs, prhs, 1); // mexplus::OutputArguments output(nlhs, plhs, 1); // if (mex_is_running) // { // printf("[mex-grabber::new] Application is already running\n"); // return; // } // Initialize global (persistent) variables mex_is_running = true; allThreadsMustExit = false; string INI_FILENAME( input.get<string>(0) ); ASSERT_FILE_EXISTS_(INI_FILENAME) CConfigFile iniFile( INI_FILENAME ); // ------------------------------------------ // Load config from file: // ------------------------------------------ int time_between_launches = 300; double SF_max_time_span = 0.25; // Seconds bool use_sensoryframes = false; int GRABBER_PERIOD_MS = 1000; MRPT_LOAD_CONFIG_VAR( time_between_launches, int, iniFile, GLOBAL_SECTION_NAME ); MRPT_LOAD_CONFIG_VAR( SF_max_time_span, float, iniFile, GLOBAL_SECTION_NAME ); MRPT_LOAD_CONFIG_VAR( use_sensoryframes, bool, iniFile, GLOBAL_SECTION_NAME ); MRPT_LOAD_CONFIG_VAR( GRABBER_PERIOD_MS, int, iniFile, GLOBAL_SECTION_NAME ); // ---------------------------------------------- // Launch threads: // ---------------------------------------------- vector_string sections; iniFile.getAllSections( sections ); for (vector_string::iterator it=sections.begin();it!=sections.end();++it) { if (*it==GLOBAL_SECTION_NAME || it->empty() || iniFile.read_bool(*it,"rawlog-grabber-ignore",false,false) ) continue; // This is not a sensor: //cout << "Launching thread for sensor '" << *it << "'" << endl; TThreadParams threParms; threParms.cfgFile = &iniFile; threParms.sensor_label = *it; TThreadHandle thre = createThread(SensorThread, threParms); lstThreads.push_back(thre); sleep(time_between_launches); } printf("[mex-grabber::new] All threads launched\n"); } // End of "new" method // Defines MEX API for read (acquire observations in Matlab form) MEX_DEFINE(read) (int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { // ---------------------------------------------- // Run: // ---------------------------------------------- // mexplus::InputArguments input(nrhs, prhs, 1); mexplus::OutputArguments output(nlhs, plhs, 1); CGenericSensor::TListObservations copy_of_global_list_obs; // See if we have observations and process them: { synch::CCriticalSectionLocker lock (&cs_global_list_obs); copy_of_global_list_obs.clear(); if (!global_list_obs.empty()) { CGenericSensor::TListObservations::iterator itEnd = global_list_obs.begin(); std::advance( itEnd, global_list_obs.size() / 2 ); copy_of_global_list_obs.insert(global_list_obs.begin(),itEnd ); global_list_obs.erase(global_list_obs.begin(), itEnd); } } // End of cs lock // Read from list of observations to mxArray cell array (store any kind of objects) MxArray cell_obs( MxArray::Cell(1, copy_of_global_list_obs.size()) ); size_t index = 0; for (CGenericSensor::TListObservations::iterator it=copy_of_global_list_obs.begin(); it!=copy_of_global_list_obs.end();++it) { MxArray struct_obs( it->second->writeToMatlab() ); struct_obs.set("ts", it->first); // Store timestamp too cell_obs.set( index, struct_obs.release() ); index++; } // Returns created struct output.set(0, cell_obs.release()); // No need to sleep, since this function only applies when user requested from Matlab } // End of "read" method // Defines MEX API for delete. MEX_DEFINE(delete) (int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { // mexplus::InputArguments input(nrhs, prhs, 1); // mexplus::OutputArguments output(nlhs, plhs, 0); if (allThreadsMustExit) { printf("[main thread] Ended due to other thread signal to exit application.\n"); } // Wait all threads: // ---------------------------- allThreadsMustExit = true; mrpt::system::sleep(300); printf("\nWaiting for all threads to close...\n"); for (vector<TThreadHandle>::iterator th=lstThreads.begin();th!=lstThreads.end();++th) joinThread( *th ); cout << endl << "[mex-grabber::delete] mex-grabber application finished" << endl; mex_is_running = false; } // End of "delete" method } // End of namespace MEX_DISPATCH // Don't forget to add this if MEX_DEFINE() is used. // ------------------------------------------------------ // SensorThread // ------------------------------------------------------ void SensorThread(TThreadParams params) { try { string driver_name = params.cfgFile->read_string(params.sensor_label,"driver","",true); CGenericSensorPtr sensor = CGenericSensor::createSensorPtr(driver_name ); if (!sensor) { cerr << endl << "***ERROR***: Class name not recognized: " << driver_name << endl; allThreadsMustExit = true; } // Load common & sensor specific parameters: sensor->loadConfig( *params.cfgFile, params.sensor_label ); cout << format("[thread_%s] Starting...",params.sensor_label.c_str()) << " at " << sensor->getProcessRate() << " Hz" << endl; ASSERTMSG_(sensor->getProcessRate()>0,"process_rate must be set to a valid value (>0 Hz)."); int process_period_ms = round( 1000.0 / sensor->getProcessRate() ); // Init device: sensor->initialize(); while (! allThreadsMustExit ) { TTimeStamp t0= now(); // Process sensor->doProcess(); // Get new observations CGenericSensor::TListObservations lstObjs; sensor->getObservations( lstObjs ); { synch::CCriticalSectionLocker lock (&cs_global_list_obs); // Control maximum number of stored observations to prevent excesive growth of list between calls if ( global_list_obs.size() < 2 * max_num_obs ) // .size() is returning 2 countings for each pair global_list_obs.insert( lstObjs.begin(), lstObjs.end() ); } lstObjs.clear(); // wait until the process period: TTimeStamp t1= now(); double At = timeDifference(t0,t1); int At_rem_ms = process_period_ms - At*1000; if (At_rem_ms>0) sleep(At_rem_ms); } sensor.clear(); cout << format("[thread_%s] Closing...",params.sensor_label.c_str()) << endl; } catch (std::exception &e) { cerr << e.what() << endl; allThreadsMustExit = true; } catch (...) { cerr << "Untyped exception!!" << endl; allThreadsMustExit = true; } } // ------------------------------------------------------ // MAIN THREAD // // For testing outside Matlab // ------------------------------------------------------ int main(int argc, const char* argv[] ) { try { printf(" MEX-grabber - Part of the MRPT\n"); printf(" MRPT C++ Library: %s - BUILD DATE %s\n", MRPT_getVersion().c_str(), MRPT_getCompilationDate().c_str()); printf("-------------------------------------------------------------------\n"); printf(" This is a test for Matlab MEX functionalities\n"); printf("-------------------------------------------------------------------\n"); // Launch threads with "new" const mxArray* mxIn[2]; mxIn[0] = mexplus::MxArray::from( "new" ); mxIn[1] = mexplus::MxArray::from( argv[1] ); // Read config file path, first argv is function name mxArray* mxOut[1]; mexFunction( 1, mxOut, 2, mxIn ); // Read frames with "read" mxIn[0] = mexplus::MxArray::from( "read" ); mexFunction( 1, mxOut, 1, mxIn ); // Finish applicatin with "delete" mxIn[0] = mexplus::MxArray::from( "delete" ); mexFunction( 1, mxOut, 1, mxIn ); // Repete whole process // Launch threads with "new" mxIn[0] = mexplus::MxArray::from( "new" ); mxIn[1] = mexplus::MxArray::from( argv[1] ); // Read config file path, first argv is function name mexFunction( 1, mxOut, 2, mxIn ); // Read frames with "read" mxIn[0] = mexplus::MxArray::from( "read" ); mexFunction( 1, mxOut, 1, mxIn ); // Finish applicatin with "delete" mxIn[0] = mexplus::MxArray::from( "delete" ); mexFunction( 1, mxOut, 1, mxIn ); return 0; } catch (std::exception &e) { std::cerr << e.what() << std::endl << "Program finished for an exception!!" << std::endl; mrpt::system::pause(); return -1; } catch (...) { std::cerr << "Untyped exception!!" << std::endl; mrpt::system::pause(); return -1; } } <commit_msg>mexgrabber: remove unneeded #includes<commit_after>/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2014, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ /*----------------------------------------------------------------------------- APPLICATION: MEX-grabber FILE: mexgrabber.cpp AUTHORS: Jesus Briales Garcia <[email protected]> Jose Luis Blanco Claraco <[email protected]> For instructions and details, see: http://www.mrpt.org/Application:MEX-grabber -----------------------------------------------------------------------------*/ #include <mrpt/hwdrivers/CGenericSensor.h> #include <mrpt/utils/CConfigFile.h> #include <mrpt/utils/CFileGZOutputStream.h> #include <mrpt/utils/CImage.h> #include <mrpt/utils/round.h> #include <mrpt/system/os.h> #include <mrpt/system/filesystem.h> // Matlab MEX interface headers #include <mexplus.h> // Force here using mexPrintf instead of printf #define printf mexPrintf using namespace mrpt; using namespace mrpt::system; using namespace mrpt::hwdrivers; using namespace mrpt::utils; //using namespace mrpt::obs; using namespace std; using namespace mexplus; const std::string GLOBAL_SECTION_NAME = "global"; // Forward declarations: struct TThreadParams { CConfigFile *cfgFile; string sensor_label; }; void SensorThread(TThreadParams params); CGenericSensor::TListObservations global_list_obs; synch::CCriticalSection cs_global_list_obs; bool allThreadsMustExit = false; // Thread handlers vector stored as global (persistent MEX variables) vector<TThreadHandle> lstThreads; // State variables bool mex_is_running = false; // Configuration variables MRPT_TODO("Set as variable controlled from Matlab") size_t max_num_obs = 50; /* Important: * All global variables will be stored between MEX calls, * and can be used by running threads backstage. */ namespace { // Defines MEX API for new. MEX_DEFINE(new) (int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { printf(" mex-grabber - Part of the MRPT\n"); printf(" MRPT C++ Library: %s - BUILD DATE %s\n", MRPT_getVersion().c_str(), MRPT_getCompilationDate().c_str()); printf("-------------------------------------------------------------------\n"); mexplus::InputArguments input(nrhs, prhs, 1); // mexplus::OutputArguments output(nlhs, plhs, 1); // if (mex_is_running) // { // printf("[mex-grabber::new] Application is already running\n"); // return; // } // Initialize global (persistent) variables mex_is_running = true; allThreadsMustExit = false; string INI_FILENAME( input.get<string>(0) ); ASSERT_FILE_EXISTS_(INI_FILENAME) CConfigFile iniFile( INI_FILENAME ); // ------------------------------------------ // Load config from file: // ------------------------------------------ int time_between_launches = 300; double SF_max_time_span = 0.25; // Seconds bool use_sensoryframes = false; int GRABBER_PERIOD_MS = 1000; MRPT_LOAD_CONFIG_VAR( time_between_launches, int, iniFile, GLOBAL_SECTION_NAME ); MRPT_LOAD_CONFIG_VAR( SF_max_time_span, float, iniFile, GLOBAL_SECTION_NAME ); MRPT_LOAD_CONFIG_VAR( use_sensoryframes, bool, iniFile, GLOBAL_SECTION_NAME ); MRPT_LOAD_CONFIG_VAR( GRABBER_PERIOD_MS, int, iniFile, GLOBAL_SECTION_NAME ); // ---------------------------------------------- // Launch threads: // ---------------------------------------------- vector_string sections; iniFile.getAllSections( sections ); for (vector_string::iterator it=sections.begin();it!=sections.end();++it) { if (*it==GLOBAL_SECTION_NAME || it->empty() || iniFile.read_bool(*it,"rawlog-grabber-ignore",false,false) ) continue; // This is not a sensor: //cout << "Launching thread for sensor '" << *it << "'" << endl; TThreadParams threParms; threParms.cfgFile = &iniFile; threParms.sensor_label = *it; TThreadHandle thre = createThread(SensorThread, threParms); lstThreads.push_back(thre); sleep(time_between_launches); } printf("[mex-grabber::new] All threads launched\n"); } // End of "new" method // Defines MEX API for read (acquire observations in Matlab form) MEX_DEFINE(read) (int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { // ---------------------------------------------- // Run: // ---------------------------------------------- // mexplus::InputArguments input(nrhs, prhs, 1); mexplus::OutputArguments output(nlhs, plhs, 1); CGenericSensor::TListObservations copy_of_global_list_obs; // See if we have observations and process them: { synch::CCriticalSectionLocker lock (&cs_global_list_obs); copy_of_global_list_obs.clear(); if (!global_list_obs.empty()) { CGenericSensor::TListObservations::iterator itEnd = global_list_obs.begin(); std::advance( itEnd, global_list_obs.size() / 2 ); copy_of_global_list_obs.insert(global_list_obs.begin(),itEnd ); global_list_obs.erase(global_list_obs.begin(), itEnd); } } // End of cs lock // Read from list of observations to mxArray cell array (store any kind of objects) MxArray cell_obs( MxArray::Cell(1, copy_of_global_list_obs.size()) ); size_t index = 0; for (CGenericSensor::TListObservations::iterator it=copy_of_global_list_obs.begin(); it!=copy_of_global_list_obs.end();++it) { MxArray struct_obs( it->second->writeToMatlab() ); struct_obs.set("ts", it->first); // Store timestamp too cell_obs.set( index, struct_obs.release() ); index++; } // Returns created struct output.set(0, cell_obs.release()); // No need to sleep, since this function only applies when user requested from Matlab } // End of "read" method // Defines MEX API for delete. MEX_DEFINE(delete) (int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { // mexplus::InputArguments input(nrhs, prhs, 1); // mexplus::OutputArguments output(nlhs, plhs, 0); if (allThreadsMustExit) { printf("[main thread] Ended due to other thread signal to exit application.\n"); } // Wait all threads: // ---------------------------- allThreadsMustExit = true; mrpt::system::sleep(300); printf("\nWaiting for all threads to close...\n"); for (vector<TThreadHandle>::iterator th=lstThreads.begin();th!=lstThreads.end();++th) joinThread( *th ); cout << endl << "[mex-grabber::delete] mex-grabber application finished" << endl; mex_is_running = false; } // End of "delete" method } // End of namespace MEX_DISPATCH // Don't forget to add this if MEX_DEFINE() is used. // ------------------------------------------------------ // SensorThread // ------------------------------------------------------ void SensorThread(TThreadParams params) { try { string driver_name = params.cfgFile->read_string(params.sensor_label,"driver","",true); CGenericSensorPtr sensor = CGenericSensor::createSensorPtr(driver_name ); if (!sensor) { cerr << endl << "***ERROR***: Class name not recognized: " << driver_name << endl; allThreadsMustExit = true; } // Load common & sensor specific parameters: sensor->loadConfig( *params.cfgFile, params.sensor_label ); cout << format("[thread_%s] Starting...",params.sensor_label.c_str()) << " at " << sensor->getProcessRate() << " Hz" << endl; ASSERTMSG_(sensor->getProcessRate()>0,"process_rate must be set to a valid value (>0 Hz)."); int process_period_ms = round( 1000.0 / sensor->getProcessRate() ); // Init device: sensor->initialize(); while (! allThreadsMustExit ) { TTimeStamp t0= now(); // Process sensor->doProcess(); // Get new observations CGenericSensor::TListObservations lstObjs; sensor->getObservations( lstObjs ); { synch::CCriticalSectionLocker lock (&cs_global_list_obs); // Control maximum number of stored observations to prevent excesive growth of list between calls if ( global_list_obs.size() < 2 * max_num_obs ) // .size() is returning 2 countings for each pair global_list_obs.insert( lstObjs.begin(), lstObjs.end() ); } lstObjs.clear(); // wait until the process period: TTimeStamp t1= now(); double At = timeDifference(t0,t1); int At_rem_ms = process_period_ms - At*1000; if (At_rem_ms>0) sleep(At_rem_ms); } sensor.clear(); cout << format("[thread_%s] Closing...",params.sensor_label.c_str()) << endl; } catch (std::exception &e) { cerr << e.what() << endl; allThreadsMustExit = true; } catch (...) { cerr << "Untyped exception!!" << endl; allThreadsMustExit = true; } } // ------------------------------------------------------ // MAIN THREAD // // For testing outside Matlab // ------------------------------------------------------ int main(int argc, const char* argv[] ) { try { printf(" MEX-grabber - Part of the MRPT\n"); printf(" MRPT C++ Library: %s - BUILD DATE %s\n", MRPT_getVersion().c_str(), MRPT_getCompilationDate().c_str()); printf("-------------------------------------------------------------------\n"); printf(" This is a test for Matlab MEX functionalities\n"); printf("-------------------------------------------------------------------\n"); // Launch threads with "new" const mxArray* mxIn[2]; mxIn[0] = mexplus::MxArray::from( "new" ); mxIn[1] = mexplus::MxArray::from( argv[1] ); // Read config file path, first argv is function name mxArray* mxOut[1]; mexFunction( 1, mxOut, 2, mxIn ); // Read frames with "read" mxIn[0] = mexplus::MxArray::from( "read" ); mexFunction( 1, mxOut, 1, mxIn ); // Finish applicatin with "delete" mxIn[0] = mexplus::MxArray::from( "delete" ); mexFunction( 1, mxOut, 1, mxIn ); // Repete whole process // Launch threads with "new" mxIn[0] = mexplus::MxArray::from( "new" ); mxIn[1] = mexplus::MxArray::from( argv[1] ); // Read config file path, first argv is function name mexFunction( 1, mxOut, 2, mxIn ); // Read frames with "read" mxIn[0] = mexplus::MxArray::from( "read" ); mexFunction( 1, mxOut, 1, mxIn ); // Finish applicatin with "delete" mxIn[0] = mexplus::MxArray::from( "delete" ); mexFunction( 1, mxOut, 1, mxIn ); return 0; } catch (std::exception &e) { std::cerr << e.what() << std::endl << "Program finished for an exception!!" << std::endl; mrpt::system::pause(); return -1; } catch (...) { std::cerr << "Untyped exception!!" << std::endl; mrpt::system::pause(); return -1; } } <|endoftext|>
<commit_before>#include <fstream> #include <boost/lexical_cast.hpp> #include "Crypto.h" #include "Timestamp.h" #include "I2NPProtocol.h" #include "NetDb.h" #include "util.h" #include "version.h" #include "Log.h" #include "RouterContext.h" namespace i2p { RouterContext context; RouterContext::RouterContext (): m_LastUpdateTime (0), m_AcceptsTunnels (true), m_IsFloodfill (false), m_StartupTime (0), m_Status (eRouterStatusOK ) { } void RouterContext::Init () { srand (i2p::util::GetMillisecondsSinceEpoch () % 1000); m_StartupTime = i2p::util::GetSecondsSinceEpoch (); if (!Load ()) CreateNewRouter (); UpdateRouterInfo (); } void RouterContext::CreateNewRouter () { #if defined(__x86_64__) || defined(__i386__) || defined(_MSC_VER) m_Keys = i2p::data::PrivateKeys::CreateRandomKeys (i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519); #else m_Keys = i2p::data::PrivateKeys::CreateRandomKeys (i2p::data::SIGNING_KEY_TYPE_DSA_SHA1); #endif SaveKeys (); NewRouterInfo (); } void RouterContext::NewRouterInfo () { i2p::data::RouterInfo routerInfo; routerInfo.SetRouterIdentity (GetIdentity ()); int port = i2p::util::config::GetArg("-port", 0); if (!port) port = rand () % (30777 - 9111) + 9111; // I2P network ports range routerInfo.AddSSUAddress (i2p::util::config::GetCharArg("-host", "127.0.0.1"), port, routerInfo.GetIdentHash ()); routerInfo.AddNTCPAddress (i2p::util::config::GetCharArg("-host", "127.0.0.1"), port); routerInfo.SetCaps (i2p::data::RouterInfo::eReachable | i2p::data::RouterInfo::eSSUTesting | i2p::data::RouterInfo::eSSUIntroducer); // LR, BC routerInfo.SetProperty ("coreVersion", I2P_VERSION); routerInfo.SetProperty ("netId", "2"); routerInfo.SetProperty ("router.version", I2P_VERSION); routerInfo.SetProperty ("stat_uptime", "90m"); routerInfo.CreateBuffer (m_Keys); m_RouterInfo.SetRouterIdentity (GetIdentity ()); m_RouterInfo.Update (routerInfo.GetBuffer (), routerInfo.GetBufferLen ()); } void RouterContext::UpdateRouterInfo () { m_RouterInfo.CreateBuffer (m_Keys); m_RouterInfo.SaveToFile (i2p::util::filesystem::GetFullPath (ROUTER_INFO)); m_LastUpdateTime = i2p::util::GetSecondsSinceEpoch (); } void RouterContext::SetStatus (RouterStatus status) { if (status != m_Status) { m_Status = status; switch (m_Status) { case eRouterStatusOK: SetReachable (); break; case eRouterStatusFirewalled: SetUnreachable (); break; default: ; } } } void RouterContext::UpdatePort (int port) { bool updated = false; for (auto& address : m_RouterInfo.GetAddresses ()) { if (address.port != port) { address.port = port; updated = true; } } if (updated) UpdateRouterInfo (); } void RouterContext::UpdateAddress (const boost::asio::ip::address& host) { bool updated = false; for (auto& address : m_RouterInfo.GetAddresses ()) { if (address.host != host && address.IsCompatible (host)) { address.host = host; updated = true; } } auto ts = i2p::util::GetSecondsSinceEpoch (); if (updated || ts > m_LastUpdateTime + ROUTER_INFO_UPDATE_INTERVAL) UpdateRouterInfo (); } bool RouterContext::AddIntroducer (const i2p::data::RouterInfo::Introducer& introducer) { bool ret = m_RouterInfo.AddIntroducer (introducer); if (ret) UpdateRouterInfo (); return ret; } void RouterContext::RemoveIntroducer (const boost::asio::ip::udp::endpoint& e) { if (m_RouterInfo.RemoveIntroducer (e)) UpdateRouterInfo (); } void RouterContext::SetFloodfill (bool floodfill) { m_IsFloodfill = floodfill; if (floodfill) m_RouterInfo.SetCaps (m_RouterInfo.GetCaps () | i2p::data::RouterInfo::eFloodfill); else { m_RouterInfo.SetCaps (m_RouterInfo.GetCaps () & ~i2p::data::RouterInfo::eFloodfill); // we don't publish number of routers and leaseset for non-floodfill m_RouterInfo.DeleteProperty (ROUTER_INFO_PROPERTY_LEASESETS); m_RouterInfo.DeleteProperty (ROUTER_INFO_PROPERTY_ROUTERS); } UpdateRouterInfo (); } void RouterContext::SetHighBandwidth () { if (!m_RouterInfo.IsHighBandwidth ()) { m_RouterInfo.SetCaps (m_RouterInfo.GetCaps () | i2p::data::RouterInfo::eHighBandwidth); UpdateRouterInfo (); } } void RouterContext::SetLowBandwidth () { if (m_RouterInfo.IsHighBandwidth ()) { m_RouterInfo.SetCaps (m_RouterInfo.GetCaps () & ~i2p::data::RouterInfo::eHighBandwidth); UpdateRouterInfo (); } } bool RouterContext::IsUnreachable () const { return m_RouterInfo.GetCaps () & i2p::data::RouterInfo::eUnreachable; } void RouterContext::SetUnreachable () { // set caps m_RouterInfo.SetCaps (i2p::data::RouterInfo::eUnreachable | i2p::data::RouterInfo::eSSUTesting); // LU, B // remove NTCP address auto& addresses = m_RouterInfo.GetAddresses (); for (size_t i = 0; i < addresses.size (); i++) { if (addresses[i].transportStyle == i2p::data::RouterInfo::eTransportNTCP) { addresses.erase (addresses.begin () + i); break; } } // delete previous introducers for (auto& addr : addresses) addr.introducers.clear (); // update UpdateRouterInfo (); } void RouterContext::SetReachable () { // update caps uint8_t caps = m_RouterInfo.GetCaps (); caps &= ~i2p::data::RouterInfo::eUnreachable; caps |= i2p::data::RouterInfo::eReachable; caps |= i2p::data::RouterInfo::eSSUIntroducer; if (m_IsFloodfill) caps |= i2p::data::RouterInfo::eFloodfill; m_RouterInfo.SetCaps (caps); // insert NTCP back auto& addresses = m_RouterInfo.GetAddresses (); for (size_t i = 0; i < addresses.size (); i++) { if (addresses[i].transportStyle == i2p::data::RouterInfo::eTransportSSU) { // insert NTCP address with host/port from SSU m_RouterInfo.AddNTCPAddress (addresses[i].host.to_string ().c_str (), addresses[i].port); break; } } // delete previous introducers for (auto& addr : addresses) addr.introducers.clear (); // update UpdateRouterInfo (); } void RouterContext::SetSupportsV6 (bool supportsV6) { if (supportsV6) m_RouterInfo.EnableV6 (); else m_RouterInfo.DisableV6 (); UpdateRouterInfo (); } void RouterContext::UpdateNTCPV6Address (const boost::asio::ip::address& host) { bool updated = false, found = false; int port = 0; auto& addresses = m_RouterInfo.GetAddresses (); for (auto& addr : addresses) { if (addr.host.is_v6 () && addr.transportStyle == i2p::data::RouterInfo::eTransportNTCP) { if (addr.host != host) { addr.host = host; updated = true; } found = true; } else port = addr.port; } if (!found) { // create new address m_RouterInfo.AddNTCPAddress (host.to_string ().c_str (), port); auto mtu = i2p::util::net::GetMTU (host); if (mtu) { LogPrint ("Our v6 MTU=", mtu); if (mtu > 1472) mtu = 1472; } m_RouterInfo.AddSSUAddress (host.to_string ().c_str (), port, GetIdentHash (), mtu ? mtu : 1472); // TODO updated = true; } if (updated) UpdateRouterInfo (); } void RouterContext::UpdateStats () { if (m_IsFloodfill) { // update routers and leasesets m_RouterInfo.SetProperty (ROUTER_INFO_PROPERTY_LEASESETS, boost::lexical_cast<std::string>(i2p::data::netdb.GetNumLeaseSets ())); m_RouterInfo.SetProperty (ROUTER_INFO_PROPERTY_ROUTERS, boost::lexical_cast<std::string>(i2p::data::netdb.GetNumRouters ())); UpdateRouterInfo (); } } bool RouterContext::Load () { std::ifstream fk (i2p::util::filesystem::GetFullPath (ROUTER_KEYS).c_str (), std::ifstream::binary | std::ofstream::in); if (!fk.is_open ()) return false; fk.seekg (0, std::ios::end); size_t len = fk.tellg(); fk.seekg (0, std::ios::beg); if (len == sizeof (i2p::data::Keys)) // old keys file format { i2p::data::Keys keys; fk.read ((char *)&keys, sizeof (keys)); m_Keys = keys; } else // new keys file format { uint8_t * buf = new uint8_t[len]; fk.read ((char *)buf, len); m_Keys.FromBuffer (buf, len); delete[] buf; } i2p::data::RouterInfo routerInfo(i2p::util::filesystem::GetFullPath (ROUTER_INFO)); // TODO m_RouterInfo.SetRouterIdentity (GetIdentity ()); m_RouterInfo.Update (routerInfo.GetBuffer (), routerInfo.GetBufferLen ()); m_RouterInfo.SetProperty ("coreVersion", I2P_VERSION); m_RouterInfo.SetProperty ("router.version", I2P_VERSION); if (IsUnreachable ()) SetReachable (); // we assume reachable until we discover firewall through peer tests return true; } void RouterContext::SaveKeys () { // save in the same format as .dat files std::ofstream fk (i2p::util::filesystem::GetFullPath (ROUTER_KEYS).c_str (), std::ofstream::binary | std::ofstream::out); size_t len = m_Keys.GetFullLen (); uint8_t * buf = new uint8_t[len]; m_Keys.ToBuffer (buf, len); fk.write ((char *)buf, len); delete[] buf; } std::shared_ptr<i2p::tunnel::TunnelPool> RouterContext::GetTunnelPool () const { return i2p::tunnel::tunnels.GetExploratoryPool (); } void RouterContext::HandleI2NPMessage (const uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from) { i2p::HandleI2NPMessage (CreateI2NPMessage (buf, GetI2NPMessageLength (buf), from)); } void RouterContext::ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg) { std::unique_lock<std::mutex> l(m_GarlicMutex); i2p::garlic::GarlicDestination::ProcessGarlicMessage (msg); } void RouterContext::ProcessDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg) { std::unique_lock<std::mutex> l(m_GarlicMutex); i2p::garlic::GarlicDestination::ProcessDeliveryStatusMessage (msg); } uint32_t RouterContext::GetUptime () const { return i2p::util::GetSecondsSinceEpoch () - m_StartupTime; } } <commit_msg>* sane log messages: RouterContext.cpp<commit_after>#include <fstream> #include <boost/lexical_cast.hpp> #include "Crypto.h" #include "Timestamp.h" #include "I2NPProtocol.h" #include "NetDb.h" #include "util.h" #include "version.h" #include "Log.h" #include "RouterContext.h" namespace i2p { RouterContext context; RouterContext::RouterContext (): m_LastUpdateTime (0), m_AcceptsTunnels (true), m_IsFloodfill (false), m_StartupTime (0), m_Status (eRouterStatusOK ) { } void RouterContext::Init () { srand (i2p::util::GetMillisecondsSinceEpoch () % 1000); m_StartupTime = i2p::util::GetSecondsSinceEpoch (); if (!Load ()) CreateNewRouter (); UpdateRouterInfo (); } void RouterContext::CreateNewRouter () { #if defined(__x86_64__) || defined(__i386__) || defined(_MSC_VER) m_Keys = i2p::data::PrivateKeys::CreateRandomKeys (i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519); #else m_Keys = i2p::data::PrivateKeys::CreateRandomKeys (i2p::data::SIGNING_KEY_TYPE_DSA_SHA1); #endif SaveKeys (); NewRouterInfo (); } void RouterContext::NewRouterInfo () { i2p::data::RouterInfo routerInfo; routerInfo.SetRouterIdentity (GetIdentity ()); int port = i2p::util::config::GetArg("-port", 0); if (!port) port = rand () % (30777 - 9111) + 9111; // I2P network ports range routerInfo.AddSSUAddress (i2p::util::config::GetCharArg("-host", "127.0.0.1"), port, routerInfo.GetIdentHash ()); routerInfo.AddNTCPAddress (i2p::util::config::GetCharArg("-host", "127.0.0.1"), port); routerInfo.SetCaps (i2p::data::RouterInfo::eReachable | i2p::data::RouterInfo::eSSUTesting | i2p::data::RouterInfo::eSSUIntroducer); // LR, BC routerInfo.SetProperty ("coreVersion", I2P_VERSION); routerInfo.SetProperty ("netId", "2"); routerInfo.SetProperty ("router.version", I2P_VERSION); routerInfo.SetProperty ("stat_uptime", "90m"); routerInfo.CreateBuffer (m_Keys); m_RouterInfo.SetRouterIdentity (GetIdentity ()); m_RouterInfo.Update (routerInfo.GetBuffer (), routerInfo.GetBufferLen ()); } void RouterContext::UpdateRouterInfo () { m_RouterInfo.CreateBuffer (m_Keys); m_RouterInfo.SaveToFile (i2p::util::filesystem::GetFullPath (ROUTER_INFO)); m_LastUpdateTime = i2p::util::GetSecondsSinceEpoch (); } void RouterContext::SetStatus (RouterStatus status) { if (status != m_Status) { m_Status = status; switch (m_Status) { case eRouterStatusOK: SetReachable (); break; case eRouterStatusFirewalled: SetUnreachable (); break; default: ; } } } void RouterContext::UpdatePort (int port) { bool updated = false; for (auto& address : m_RouterInfo.GetAddresses ()) { if (address.port != port) { address.port = port; updated = true; } } if (updated) UpdateRouterInfo (); } void RouterContext::UpdateAddress (const boost::asio::ip::address& host) { bool updated = false; for (auto& address : m_RouterInfo.GetAddresses ()) { if (address.host != host && address.IsCompatible (host)) { address.host = host; updated = true; } } auto ts = i2p::util::GetSecondsSinceEpoch (); if (updated || ts > m_LastUpdateTime + ROUTER_INFO_UPDATE_INTERVAL) UpdateRouterInfo (); } bool RouterContext::AddIntroducer (const i2p::data::RouterInfo::Introducer& introducer) { bool ret = m_RouterInfo.AddIntroducer (introducer); if (ret) UpdateRouterInfo (); return ret; } void RouterContext::RemoveIntroducer (const boost::asio::ip::udp::endpoint& e) { if (m_RouterInfo.RemoveIntroducer (e)) UpdateRouterInfo (); } void RouterContext::SetFloodfill (bool floodfill) { m_IsFloodfill = floodfill; if (floodfill) m_RouterInfo.SetCaps (m_RouterInfo.GetCaps () | i2p::data::RouterInfo::eFloodfill); else { m_RouterInfo.SetCaps (m_RouterInfo.GetCaps () & ~i2p::data::RouterInfo::eFloodfill); // we don't publish number of routers and leaseset for non-floodfill m_RouterInfo.DeleteProperty (ROUTER_INFO_PROPERTY_LEASESETS); m_RouterInfo.DeleteProperty (ROUTER_INFO_PROPERTY_ROUTERS); } UpdateRouterInfo (); } void RouterContext::SetHighBandwidth () { if (!m_RouterInfo.IsHighBandwidth ()) { m_RouterInfo.SetCaps (m_RouterInfo.GetCaps () | i2p::data::RouterInfo::eHighBandwidth); UpdateRouterInfo (); } } void RouterContext::SetLowBandwidth () { if (m_RouterInfo.IsHighBandwidth ()) { m_RouterInfo.SetCaps (m_RouterInfo.GetCaps () & ~i2p::data::RouterInfo::eHighBandwidth); UpdateRouterInfo (); } } bool RouterContext::IsUnreachable () const { return m_RouterInfo.GetCaps () & i2p::data::RouterInfo::eUnreachable; } void RouterContext::SetUnreachable () { // set caps m_RouterInfo.SetCaps (i2p::data::RouterInfo::eUnreachable | i2p::data::RouterInfo::eSSUTesting); // LU, B // remove NTCP address auto& addresses = m_RouterInfo.GetAddresses (); for (size_t i = 0; i < addresses.size (); i++) { if (addresses[i].transportStyle == i2p::data::RouterInfo::eTransportNTCP) { addresses.erase (addresses.begin () + i); break; } } // delete previous introducers for (auto& addr : addresses) addr.introducers.clear (); // update UpdateRouterInfo (); } void RouterContext::SetReachable () { // update caps uint8_t caps = m_RouterInfo.GetCaps (); caps &= ~i2p::data::RouterInfo::eUnreachable; caps |= i2p::data::RouterInfo::eReachable; caps |= i2p::data::RouterInfo::eSSUIntroducer; if (m_IsFloodfill) caps |= i2p::data::RouterInfo::eFloodfill; m_RouterInfo.SetCaps (caps); // insert NTCP back auto& addresses = m_RouterInfo.GetAddresses (); for (size_t i = 0; i < addresses.size (); i++) { if (addresses[i].transportStyle == i2p::data::RouterInfo::eTransportSSU) { // insert NTCP address with host/port from SSU m_RouterInfo.AddNTCPAddress (addresses[i].host.to_string ().c_str (), addresses[i].port); break; } } // delete previous introducers for (auto& addr : addresses) addr.introducers.clear (); // update UpdateRouterInfo (); } void RouterContext::SetSupportsV6 (bool supportsV6) { if (supportsV6) m_RouterInfo.EnableV6 (); else m_RouterInfo.DisableV6 (); UpdateRouterInfo (); } void RouterContext::UpdateNTCPV6Address (const boost::asio::ip::address& host) { bool updated = false, found = false; int port = 0; auto& addresses = m_RouterInfo.GetAddresses (); for (auto& addr : addresses) { if (addr.host.is_v6 () && addr.transportStyle == i2p::data::RouterInfo::eTransportNTCP) { if (addr.host != host) { addr.host = host; updated = true; } found = true; } else port = addr.port; } if (!found) { // create new address m_RouterInfo.AddNTCPAddress (host.to_string ().c_str (), port); auto mtu = i2p::util::net::GetMTU (host); if (mtu) { LogPrint (eLogDebug, "Router: Our v6 MTU=", mtu); if (mtu > 1472) { // TODO: magic constant mtu = 1472; LogPrint(eLogWarning, "Router: MTU dropped to upper limit of 1472 bytes"); } } m_RouterInfo.AddSSUAddress (host.to_string ().c_str (), port, GetIdentHash (), mtu ? mtu : 1472); // TODO updated = true; } if (updated) UpdateRouterInfo (); } void RouterContext::UpdateStats () { if (m_IsFloodfill) { // update routers and leasesets m_RouterInfo.SetProperty (ROUTER_INFO_PROPERTY_LEASESETS, boost::lexical_cast<std::string>(i2p::data::netdb.GetNumLeaseSets ())); m_RouterInfo.SetProperty (ROUTER_INFO_PROPERTY_ROUTERS, boost::lexical_cast<std::string>(i2p::data::netdb.GetNumRouters ())); UpdateRouterInfo (); } } bool RouterContext::Load () { std::ifstream fk (i2p::util::filesystem::GetFullPath (ROUTER_KEYS).c_str (), std::ifstream::binary | std::ofstream::in); if (!fk.is_open ()) return false; fk.seekg (0, std::ios::end); size_t len = fk.tellg(); fk.seekg (0, std::ios::beg); if (len == sizeof (i2p::data::Keys)) // old keys file format { i2p::data::Keys keys; fk.read ((char *)&keys, sizeof (keys)); m_Keys = keys; } else // new keys file format { uint8_t * buf = new uint8_t[len]; fk.read ((char *)buf, len); m_Keys.FromBuffer (buf, len); delete[] buf; } i2p::data::RouterInfo routerInfo(i2p::util::filesystem::GetFullPath (ROUTER_INFO)); // TODO m_RouterInfo.SetRouterIdentity (GetIdentity ()); m_RouterInfo.Update (routerInfo.GetBuffer (), routerInfo.GetBufferLen ()); m_RouterInfo.SetProperty ("coreVersion", I2P_VERSION); m_RouterInfo.SetProperty ("router.version", I2P_VERSION); if (IsUnreachable ()) SetReachable (); // we assume reachable until we discover firewall through peer tests return true; } void RouterContext::SaveKeys () { // save in the same format as .dat files std::ofstream fk (i2p::util::filesystem::GetFullPath (ROUTER_KEYS).c_str (), std::ofstream::binary | std::ofstream::out); size_t len = m_Keys.GetFullLen (); uint8_t * buf = new uint8_t[len]; m_Keys.ToBuffer (buf, len); fk.write ((char *)buf, len); delete[] buf; } std::shared_ptr<i2p::tunnel::TunnelPool> RouterContext::GetTunnelPool () const { return i2p::tunnel::tunnels.GetExploratoryPool (); } void RouterContext::HandleI2NPMessage (const uint8_t * buf, size_t len, std::shared_ptr<i2p::tunnel::InboundTunnel> from) { i2p::HandleI2NPMessage (CreateI2NPMessage (buf, GetI2NPMessageLength (buf), from)); } void RouterContext::ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg) { std::unique_lock<std::mutex> l(m_GarlicMutex); i2p::garlic::GarlicDestination::ProcessGarlicMessage (msg); } void RouterContext::ProcessDeliveryStatusMessage (std::shared_ptr<I2NPMessage> msg) { std::unique_lock<std::mutex> l(m_GarlicMutex); i2p::garlic::GarlicDestination::ProcessDeliveryStatusMessage (msg); } uint32_t RouterContext::GetUptime () const { return i2p::util::GetSecondsSinceEpoch () - m_StartupTime; } } <|endoftext|>
<commit_before>#include "perf_precomp.hpp" #include "opencv2/ts/ocl_perf.hpp" #ifdef HAVE_OPENCL namespace cvtest { namespace ocl { CV_ENUM(MethodType, TM_SQDIFF, TM_SQDIFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_CCOEFF, TM_CCOEFF_NORMED) typedef std::tr1::tuple<Size, Size, MethodType> ImgSize_TmplSize_Method_t; typedef TestBaseWithParam<ImgSize_TmplSize_Method_t> ImgSize_TmplSize_Method; OCL_PERF_TEST_P(ImgSize_TmplSize_Method, matchTemplate, ::testing::Combine( testing::Values(szSmall128, cv::Size(320, 240), cv::Size(640, 480), cv::Size(800, 600), cv::Size(1024, 768), cv::Size(1280, 1024)), testing::Values(cv::Size(12, 12), cv::Size(28, 9), cv::Size(8, 30), cv::Size(16, 16)), MethodType::all() ) ) { Size imgSz = get<0>(GetParam()); Size tmplSz = get<1>(GetParam()); int method = get<2>(GetParam()); Mat img(imgSz, CV_8UC1); Mat tmpl(tmplSz, CV_8UC1); Mat result(imgSz - tmplSz + Size(1,1), CV_32F); declare .in(img, WARMUP_RNG) .in(tmpl, WARMUP_RNG) .out(result) .time(30); OCL_TEST_CYCLE() matchTemplate(img, tmpl, result, method); bool isNormed = method == TM_CCORR_NORMED || method == TM_SQDIFF_NORMED || method == TM_CCOEFF_NORMED; double eps = isNormed ? 1e-6 : 255 * 255 * tmpl.total() * 1e-6; SANITY_CHECK(result, eps); } } } #endif // HAVE_OPENCL<commit_msg>fixed pref test<commit_after>#include "perf_precomp.hpp" #include "opencv2/ts/ocl_perf.hpp" #ifdef HAVE_OPENCL namespace cvtest { namespace ocl { CV_ENUM(MethodType, TM_SQDIFF, TM_SQDIFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_CCOEFF, TM_CCOEFF_NORMED) typedef std::tr1::tuple<Size, Size, MethodType> ImgSize_TmplSize_Method_t; typedef TestBaseWithParam<ImgSize_TmplSize_Method_t> ImgSize_TmplSize_Method; OCL_PERF_TEST_P(ImgSize_TmplSize_Method, matchTemplate, ::testing::Combine( testing::Values(szSmall128, cv::Size(320, 240), cv::Size(640, 480), cv::Size(800, 600), cv::Size(1024, 768), cv::Size(1280, 1024)), testing::Values(cv::Size(12, 12), cv::Size(28, 9), cv::Size(8, 30), cv::Size(16, 16)), MethodType::all() ) ) { Size imgSz = get<0>(GetParam()); Size tmplSz = get<1>(GetParam()); int method = get<2>(GetParam()); UMat img(imgSz, CV_8UC1); UMat tmpl(tmplSz, CV_8UC1); UMat result(imgSz - tmplSz + Size(1,1), CV_32F); declare .in(img, WARMUP_RNG) .in(tmpl, WARMUP_RNG) .out(result) .time(30); OCL_TEST_CYCLE() matchTemplate(img, tmpl, result, method); bool isNormed = method == TM_CCORR_NORMED || method == TM_SQDIFF_NORMED || method == TM_CCOEFF_NORMED; double eps = isNormed ? 1e-6 : 255 * 255 * tmpl.total() * 1e-6; SANITY_CHECK(result, eps); } } } #endif // HAVE_OPENCL<|endoftext|>
<commit_before>#include "../includes/emulator.hh" Emulator::Emulator() { } Emulator::Emulator(char* file, int dbg) : state_(0) , ram_(new RAM(file)) , display_(ram_) , dbg_(&cpu_, ram_, dbg) { SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO); screen_ = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_ANYFORMAT); SDL_WM_SetCaption("Chip8 Emulator", NULL); display_.screen_set(screen_); } Emulator::~Emulator() { } void Emulator::fetch_decode_execute() { uint8_t instruction[2]; instruction[0] = ram_->ram_get(cpu_.pc_get()); instruction[1] = ram_->ram_get(cpu_.pc_get() + 1); cpu_.pc_set(cpu_.pc_get() + 2); if (instruction[0] == 0 && instruction[1] == 0) { state_ = 1; return; } uint16_t instr = (instruction[0] << 8) | instruction[1]; switch (instruction[0] >> 4) { case 0x0: if (instruction[1] == 0xE0) display_.clear(); else if (instruction[1] == 0xEE) cpu_.ret(); break; case 0x1: cpu_.pc_set(instr & 0x0FFF); break; case 0x2: cpu_.call(instr & 0x0FFF); break; case 0x3: if (cpu_.registers_get(instruction[0] & 0x0F) == instruction[1]) cpu_.pc_set(cpu_.pc_get() + 2); break; case 0x4: if (cpu_.registers_get(instruction[0] & 0x0F) != instruction[1]) cpu_.pc_set(cpu_.pc_get() + 2); break; case 0x5: if (cpu_.registers_get(instruction[0] & 0x0F) == cpu_.registers_get(instruction[1] >> 4)) cpu_.pc_set(cpu_.pc_get() + 2); break; case 0x6: cpu_.registers_set(instruction[0] & 0x0F, instruction[1]); break; case 0x7: cpu_.registers_set(instruction[0] & 0x0F, cpu_.registers_get(instruction[0] & 0x0F) + instruction[1]); break; case 0x8: if ((instruction[1] & 0x0F) == 0x0) cpu_.registers_set(instruction[0] & 0x0F, cpu_.registers_get(instruction[1] >> 4)); else if ((instruction[1] & 0x0F) == 0x1) cpu_.registers_set(instruction[0] & 0x0F, (instruction[0] & 0x0F) | ((instruction[1] >> 4) & 0x0F)); else if ((instruction[1] & 0x0F) == 0x2) cpu_.registers_set(instruction[0] & 0x0F, (instruction[0] & 0x0F) & ((instruction[1] >> 4) & 0x0F)); else if ((instruction[1] & 0x0F) == 0x3) cpu_.registers_set(instruction[0] & 0x0F, (instruction[0] & 0x0F) ^ ((instruction[1] >> 4) & 0x0F)); else if ((instruction[1] & 0x0F) == 0x4) cpu_.add(instr); else if ((instruction[1] & 0x0F) == 0x5) cpu_.sub(instr); else if ((instruction[1] & 0x0F) == 0x6) cpu_.shr(instr); else if ((instruction[1] & 0x0F) == 0x7) cpu_.subn(instr); else if ((instruction[1] & 0x0F) == 0xE) cpu_.shl(instr); break; case 0x9: if (cpu_.registers_get(instruction[0] & 0x0F) != cpu_.registers_get(instruction[1] >> 4)) cpu_.pc_set(cpu_.pc_get() + 2); break; case 0xA: cpu_.Ireg_set(instr & 0x0FFF); break; case 0xB: cpu_.pc_set((instr & 0x0FFF) + cpu_.registers_get(0)); break; case 0xC: cpu_.randomize(instr); break; case 0xD: display_.draw_sprite(cpu_.registers_get(instruction[0] & 0x0F), cpu_.registers_get(instruction[1] >> 4), cpu_.Ireg_get(), instruction[1] & 0x0F, &cpu_); break; case 0xE: if (instruction[1] == 0x9E) { if (kb_.is_key_pressed(cpu_.registers_get(instruction[0] & 0x0F))) cpu_.pc_set(cpu_.pc_get() + 2); } else if (instruction[1] == 0xA1) { if (!kb_.is_key_pressed(cpu_.registers_get(instruction[0] & 0x0F))) cpu_.pc_set(cpu_.pc_get() + 2); } break; case 0xF: if (instruction[1] == 0x07) cpu_.registers_set(instruction[0] & 0x0F, cpu_.timer_get()); else if (instruction[1] == 0x0A) cpu_.registers_set(instruction[0] & 0x0F, kb_.get_key_pressed()); else if (instruction[1] == 0x15) cpu_.timer_set(cpu_.registers_get(instruction[0] & 0x0F)); else if (instruction[1] == 0x18) cpu_.sound_set(cpu_.registers_get(instruction[0] & 0x0F)); else if (instruction[1] == 0x1E) cpu_.Ireg_set(cpu_.Ireg_get() + cpu_.registers_get(instruction[0] & 0x0F)); else if (instruction[1] == 0x29) cpu_.Ireg_set((instruction[0] & 0x0F) * 5); else if (instruction[1] == 0x33) cpu_.ldb(instr, ram_); else if (instruction[1] == 0x55) cpu_.ld55(instr, ram_); else if (instruction[1] == 0x65) cpu_.ld65(instr, ram_); break; default: break; } } int Emulator::run() { uint32_t last = SDL_GetTicks(); while (!state_) { if (kb_.is_key_pressed(SDLK_ESCAPE)) break; if (cpu_.timer_get() > 0) cpu_.timer_set(cpu_.timer_get() - 1); if (cpu_.sound_get() > 0) { std::cout << '\a' << std::endl; cpu_.sound_set(cpu_.sound_get() - 1); } dbg_.stop(); fetch_decode_execute(); dbg_.print_status(); SDL_Flip(screen_); while (SDL_GetTicks() - last < 16) continue; last = SDL_GetTicks(); } SDL_Quit(); return 0; } <commit_msg>debug still in progress, that's so much better<commit_after>#include "../includes/emulator.hh" Emulator::Emulator() { } Emulator::Emulator(char* file, int dbg) : state_(0) , ram_(new RAM(file)) , display_(ram_) , dbg_(&cpu_, ram_, dbg) { SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO); screen_ = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_ANYFORMAT); SDL_WM_SetCaption("Chip8 Emulator", NULL); display_.screen_set(screen_); } Emulator::~Emulator() { } void Emulator::fetch_decode_execute() { uint8_t instruction[2]; instruction[0] = ram_->ram_get(cpu_.pc_get()); instruction[1] = ram_->ram_get(cpu_.pc_get() + 1); cpu_.pc_set(cpu_.pc_get() + 2); if (instruction[0] == 0 && instruction[1] == 0) { state_ = 1; return; } uint16_t instr = (instruction[0] << 8) | instruction[1]; switch (instruction[0] >> 4) { case 0x0: if (instruction[1] == 0xE0) display_.clear(); else if (instruction[1] == 0xEE) cpu_.ret(); break; case 0x1: cpu_.pc_set(instr & 0x0FFF); break; case 0x2: cpu_.call(instr & 0x0FFF); break; case 0x3: if (cpu_.registers_get(instruction[0] & 0x0F) == instruction[1]) cpu_.pc_set(cpu_.pc_get() + 2); break; case 0x4: if (cpu_.registers_get(instruction[0] & 0x0F) != instruction[1]) cpu_.pc_set(cpu_.pc_get() + 2); break; case 0x5: if (cpu_.registers_get(instruction[0] & 0x0F) == cpu_.registers_get(instruction[1] >> 4)) cpu_.pc_set(cpu_.pc_get() + 2); break; case 0x6: cpu_.registers_set(instruction[0] & 0x0F, instruction[1]); break; case 0x7: cpu_.registers_set(instruction[0] & 0x0F, cpu_.registers_get(instruction[0] & 0x0F) + instruction[1]); break; case 0x8: if ((instruction[1] & 0x0F) == 0x0) cpu_.registers_set(instruction[0] & 0x0F, cpu_.registers_get(instruction[1] >> 4)); else if ((instruction[1] & 0x0F) == 0x1) cpu_.registers_set(instruction[0] & 0x0F, cpu_.registers_get(instruction[0] & 0x0F) | cpu_.registers_get((instruction[1] >> 4) & 0x0F)); else if ((instruction[1] & 0x0F) == 0x2) cpu_.registers_set(instruction[0] & 0x0F, cpu_.registers_get(instruction[0] & 0x0F) & cpu_.registers_get((instruction[1] >> 4) & 0x0F)); else if ((instruction[1] & 0x0F) == 0x3) cpu_.registers_set(instruction[0] & 0x0F, cpu_.registers_get(instruction[0] & 0x0F) ^ cpu_.registers_get((instruction[1] >> 4) & 0x0F)); else if ((instruction[1] & 0x0F) == 0x4) cpu_.add(instr); else if ((instruction[1] & 0x0F) == 0x5) cpu_.sub(instr); else if ((instruction[1] & 0x0F) == 0x6) cpu_.shr(instr); else if ((instruction[1] & 0x0F) == 0x7) cpu_.subn(instr); else if ((instruction[1] & 0x0F) == 0xE) cpu_.shl(instr); break; case 0x9: if (cpu_.registers_get(instruction[0] & 0x0F) != cpu_.registers_get(instruction[1] >> 4)) cpu_.pc_set(cpu_.pc_get() + 2); break; case 0xA: cpu_.Ireg_set(instr & 0x0FFF); break; case 0xB: cpu_.pc_set((instr & 0x0FFF) + cpu_.registers_get(0)); break; case 0xC: cpu_.randomize(instr); break; case 0xD: display_.draw_sprite(cpu_.registers_get(instruction[0] & 0x0F), cpu_.registers_get(instruction[1] >> 4), cpu_.Ireg_get(), instruction[1] & 0x0F, &cpu_); break; case 0xE: if (instruction[1] == 0x9E) { if (kb_.is_key_pressed(cpu_.registers_get(instruction[0] & 0x0F))) cpu_.pc_set(cpu_.pc_get() + 2); } else if (instruction[1] == 0xA1) { if (!kb_.is_key_pressed(cpu_.registers_get(instruction[0] & 0x0F))) cpu_.pc_set(cpu_.pc_get() + 2); } break; case 0xF: if (instruction[1] == 0x07) cpu_.registers_set(instruction[0] & 0x0F, cpu_.timer_get()); else if (instruction[1] == 0x0A) cpu_.registers_set(instruction[0] & 0x0F, kb_.get_key_pressed()); else if (instruction[1] == 0x15) cpu_.timer_set(cpu_.registers_get(instruction[0] & 0x0F)); else if (instruction[1] == 0x18) cpu_.sound_set(cpu_.registers_get(instruction[0] & 0x0F)); else if (instruction[1] == 0x1E) cpu_.Ireg_set(cpu_.Ireg_get() + cpu_.registers_get(instruction[0] & 0x0F)); else if (instruction[1] == 0x29) cpu_.Ireg_set(cpu_.registers_get(instruction[0] & 0x0F) * 5); else if (instruction[1] == 0x33) cpu_.ldb(instr, ram_); else if (instruction[1] == 0x55) cpu_.ld55(instr, ram_); else if (instruction[1] == 0x65) cpu_.ld65(instr, ram_); break; default: break; } } int Emulator::run() { uint32_t last = SDL_GetTicks(); while (!state_) { if (kb_.is_key_pressed(SDLK_ESCAPE)) break; if (cpu_.timer_get() > 0) cpu_.timer_set(cpu_.timer_get() - 1); if (cpu_.sound_get() > 0) { std::cout << '\a' << std::endl; cpu_.sound_set(cpu_.sound_get() - 1); } dbg_.stop(); fetch_decode_execute(); dbg_.print_status(); SDL_Flip(screen_); while (SDL_GetTicks() - last < 16) continue; last = SDL_GetTicks(); } SDL_Quit(); return 0; } <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // CellMLSupport plugin //============================================================================== #include "cellmlfilemanager.h" #include "cellmlsupportplugin.h" //============================================================================== #include <QFileInfo> #include <QXmlStreamReader> //============================================================================== namespace OpenCOR { namespace CellMLSupport { //============================================================================== PLUGININFO_FUNC CellMLSupportPluginInfo() { Descriptions descriptions; descriptions.insert("en", QString::fromUtf8("a plugin to support <a href=\"http://www.cellml.org/\">CellML</a>.")); descriptions.insert("fr", QString::fromUtf8("une extension pour supporter <a href=\"http://www.cellml.org/\">CellML</a>.")); return new PluginInfo(PluginInfo::InterfaceVersion001, PluginInfo::Miscellaneous, false, false, QStringList() << "Core" << "CellMLAPI" << "Compiler" << "CoreSolver", descriptions); } //============================================================================== // Core interface //============================================================================== void CellMLSupportPlugin::initialize() { // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::finalize() { // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::initialized(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // Make a call to the instance of the CellML file manager so that it gets // set up and can then do its job // Note: we do it rather than in initialize() since we need the Core plugin // to be initialised... CellmlFileManager::instance(); } //============================================================================== void CellMLSupportPlugin::loadSettings(QSettings *pSettings) { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::saveSettings(QSettings *pSettings) const { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::settingsLoaded(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::handleArguments(const QStringList &pArguments) { Q_UNUSED(pArguments); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::handleAction(const QUrl &pUrl) { Q_UNUSED(pUrl); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::runCliCommand(const QString &pCommand, const QStringList &pArguments, int *pRes) { Q_UNUSED(pCommand); Q_UNUSED(pArguments); // We don't handle this interface... *pRes = 0; } //============================================================================== // File interface //============================================================================== FileTypes CellMLSupportPlugin::fileTypes() const { // Return the CellML file type that the CellMLSupport plugin supports return FileTypes() << FileType(qobject_cast<FileInterface *>(this), CellmlMimeType, CellmlFileExtension); } //============================================================================== QString CellMLSupportPlugin::fileTypeDescription(const QString &pMimeType) const { // Return the description for the requested MIME type, that is as long as it // is for the CellML MIME type if (!pMimeType.compare(CellmlMimeType)) return tr("CellML File"); else // Not a MIME type that we can recognise, so... return QString(); } //============================================================================== // GUI interface //============================================================================== void CellMLSupportPlugin::retranslateUi() { // We don't handle this interface... } //============================================================================== // Plugin specific //============================================================================== bool isCellmlFile(const QString &pFileName) { // Return whether the file is a CellML file if (!QFileInfo(pFileName).suffix().compare(CellMLSupport::CellmlFileExtension)) // We are dealing with a file which file extension is that of a CellML // file, so... return true; // The file doesn't have the 'correct' file extension, so quickly check its // contents QFile file(pFileName); if (!file.open(QIODevice::ReadOnly)) // We can't open the file, so... return false; // Try to read the file as if it was an XML file QXmlStreamReader xml(&file); bool res = false; while (!xml.atEnd() && !xml.hasError()) { xml.readNext(); if (xml.isStartElement()) { // This is our root element, so for the file to be considered a // CellML file it should be a model element in either the CellML 1.0 // or 1.1 namespace if ( !xml.name().toString().compare("model") && ( (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.0#")) || (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.1#")))) // All the requirements are gathered for the file to be // considered a CellML file, so... res = true; break; } } file.close(); // We are done, so... return res; } //============================================================================== } // namespace CellMLSupport } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // CellMLSupport plugin //============================================================================== #include "cellmlfilemanager.h" #include "cellmlsupportplugin.h" //============================================================================== #include <QFileInfo> #include <QXmlStreamReader> //============================================================================== namespace OpenCOR { namespace CellMLSupport { //============================================================================== PLUGININFO_FUNC CellMLSupportPluginInfo() { Descriptions descriptions; descriptions.insert("en", QString::fromUtf8("a plugin to support <a href=\"http://www.cellml.org/\">CellML</a>.")); descriptions.insert("fr", QString::fromUtf8("une extension pour supporter <a href=\"http://www.cellml.org/\">CellML</a>.")); return new PluginInfo(PluginInfo::InterfaceVersion001, PluginInfo::Miscellaneous, false, false, QStringList() << "Core" << "CellMLAPI" << "Compiler" << "CoreSolver", descriptions); } //============================================================================== // Core interface //============================================================================== void CellMLSupportPlugin::initialize() { // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::finalize() { // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::initialized(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // Make a call to the instance of the CellML file manager so that it gets // properly set up before it actually gets used // Note: we do it here rather than in initialize() since we need the Core // plugin to be initialised... CellmlFileManager::instance(); } //============================================================================== void CellMLSupportPlugin::loadSettings(QSettings *pSettings) { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::saveSettings(QSettings *pSettings) const { Q_UNUSED(pSettings); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::settingsLoaded(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::handleArguments(const QStringList &pArguments) { Q_UNUSED(pArguments); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::handleAction(const QUrl &pUrl) { Q_UNUSED(pUrl); // We don't handle this interface... } //============================================================================== void CellMLSupportPlugin::runCliCommand(const QString &pCommand, const QStringList &pArguments, int *pRes) { Q_UNUSED(pCommand); Q_UNUSED(pArguments); // We don't handle this interface... *pRes = 0; } //============================================================================== // File interface //============================================================================== FileTypes CellMLSupportPlugin::fileTypes() const { // Return the CellML file type that the CellMLSupport plugin supports return FileTypes() << FileType(qobject_cast<FileInterface *>(this), CellmlMimeType, CellmlFileExtension); } //============================================================================== QString CellMLSupportPlugin::fileTypeDescription(const QString &pMimeType) const { // Return the description for the requested MIME type, that is as long as it // is for the CellML MIME type if (!pMimeType.compare(CellmlMimeType)) return tr("CellML File"); else // Not a MIME type that we can recognise, so... return QString(); } //============================================================================== // GUI interface //============================================================================== void CellMLSupportPlugin::retranslateUi() { // We don't handle this interface... } //============================================================================== // Plugin specific //============================================================================== bool isCellmlFile(const QString &pFileName) { // Return whether the file is a CellML file if (!QFileInfo(pFileName).suffix().compare(CellMLSupport::CellmlFileExtension)) // We are dealing with a file which file extension is that of a CellML // file, so... return true; // The file doesn't have the 'correct' file extension, so quickly check its // contents QFile file(pFileName); if (!file.open(QIODevice::ReadOnly)) // We can't open the file, so... return false; // Try to read the file as if it was an XML file QXmlStreamReader xml(&file); bool res = false; while (!xml.atEnd() && !xml.hasError()) { xml.readNext(); if (xml.isStartElement()) { // This is our root element, so for the file to be considered a // CellML file it should be a model element in either the CellML 1.0 // or 1.1 namespace if ( !xml.name().toString().compare("model") && ( (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.0#")) || (!xml.namespaceUri().toString().compare("http://www.cellml.org/cellml/1.1#")))) // All the requirements are gathered for the file to be // considered a CellML file, so... res = true; break; } } file.close(); // We are done, so... return res; } //============================================================================== } // namespace CellMLSupport } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>#include "TEXT_S.H" #include "GPU.H" #include "SPECIFIC.H" #include "TEXT.H" #include "TYPES.H" //char*, unsigned short*, unsigned short* #if 1 long GetStringLength(char* string, unsigned short* a1, unsigned short* a2)//8DEDC(<), 8FF20(<) { char c; long t0, t1, t2, t3, t5, v0; t5 = 0; t0 = 0; t2 = 0xFFFFFC00; c = *string++;//c = a3 t1 = 0x400; if (c != 0 || c != 10) { t3 = ScaleFlag; //t6 = &AccentTable[0][0]; //t4 = &CharDef[0]; //loc_8DF18 while (string[0] != 10 || string[0] != 0) { if (c == 32) { t0 += 8; if (t3 != 0) { t0 -= 2; } } else if (c == 9) { //loc_8DF30 t0 += 40; if (!(t1 < -11)) { t1 = -12; } if (t2 < 2) { t2 = 2; } } else if (c > 19) { //loc_8DF5C if (c < 0x20) { //v0 = (c << 3) - c; //v0 += 0x206; //a3 = v0 + t4 sizeof(struct CHARDEF); } else { //loc_8DF7C //v1 = c - 0x80; //v0 = v1 < 0x2E ? 1 : 0; //v0 = v1 << 1; if (c - 0x80 < 0x2E) { //v0 += t6; //a3 = v0[0]; t5 = 1; }//loc_8DF98 //v0 = a3 << 3; //v0 -= a3; //v0 -= 0xE7; //a3 = v0 + t4; } //loc_8DFA8 } } } //loc_8DFFC if (a1 != 0 && t5 == 0) { //loc_8E010 *a1 = t1; } else if (a1 != 0 && t1 != 0) { t1 -= 4; } //loc_8E014 if (a2 != 0) { *a2 = t2; } *a1 = t1; return t0; } #endif void GetStringDimensions(char* string, unsigned short* w, unsigned short* h)//8E028, ? { S_Warn("[GetStringDimensions] - Unimplemented!\n"); } void DrawChar(unsigned short a0, unsigned short a1, unsigned short a2, struct CHARDEF* a3)//8DDBC(<), 8FE00(<) (F) { struct CVECTOR* TopShade;//$v0 struct CVECTOR* BottomShade;//$at long v1; a2 &= 0xFFFF; if ((unsigned long) &db.polyptr[0] < (unsigned long) &db.polybuf_limit[0]) { TopShade = &FontShades[a2][a3->TopShade]; BottomShade = &FontShades[a2][a3->BottomShade]; *(long*) &db.polyptr[4] = *(long*) &TopShade->r; *(long*) &db.polyptr[28] = *(long*) &BottomShade->r; *(long*) &db.polyptr[16] = *(long*) &TopShade->r; *(long*) &db.polyptr[40] = *(long*) &BottomShade->r; ((char*) db.polyptr)[7] = 0x3C;//#define TAG_PGT4 0x3C *(short*) &db.polyptr[14] = 4197; *(short*) &db.polyptr[26] = 41; //sizeof(POLY_GT4); v1 = a3->w; a1 += a3->YOffset; if (ScaleFlag != 0) { v1 = (a3->w >> 2) - a3->w + 1; } //loc_8DE5C *(short*) &db.polyptr[8] = a0; *(short*) &db.polyptr[10] = a1; *(short*) &db.polyptr[20] = a0 + v1; *(short*) &db.polyptr[22] = a1; *(short*) &db.polyptr[32] = a0; *(short*) &db.polyptr[34] = a1 + a3->h; *(short*) &db.polyptr[44] = a0 + v1; *(short*) &db.polyptr[46] = a1 + a3->h; *(char*) &db.polyptr[12] = a3->w; *(char*) &db.polyptr[13] = a3->v; *(char*) &db.polyptr[24] = a3->u + a3->v; *(char*) &db.polyptr[25] = a3->v; *(char*) &db.polyptr[36] = a3->u; *(char*) &db.polyptr[37] = a3->v + a3->h; *(char*) &db.polyptr[48] = a3->u + a3->w; *(char*) &db.polyptr[49] = a3->v + a3->h; *(long*) &db.polyptr[0] = db.ot[0] | 0x0C000000; db.ot[0] = (unsigned long) db.polyptr; db.polyptr += sizeof(POLY_GT4); }//locret_8DED4 }<commit_msg>Add GetStringDimensions()<commit_after>#include "TEXT_S.H" #include "GPU.H" #include "SPECIFIC.H" #include "TEXT.H" #include "TYPES.H" //char*, unsigned short*, unsigned short* #if 1 long GetStringLength(char* string, unsigned short* a1, unsigned short* a2)//8DEDC(<), 8FF20(<) { char c; long t0, t1, t2, t3, t5, v0; t5 = 0; t0 = 0; t2 = 0xFFFFFC00; c = *string++;//c = a3 t1 = 0x400; if (c != 0 || c != 10) { t3 = ScaleFlag; //t6 = &AccentTable[0][0]; //t4 = &CharDef[0]; //loc_8DF18 while (string[0] != 10 || string[0] != 0) { if (c == 32) { t0 += 8; if (t3 != 0) { t0 -= 2; } } else if (c == 9) { //loc_8DF30 t0 += 40; if (!(t1 < -11)) { t1 = -12; } if (t2 < 2) { t2 = 2; } } else if (c > 19) { //loc_8DF5C if (c < 0x20) { //v0 = (c << 3) - c; //v0 += 0x206; //a3 = v0 + t4 sizeof(struct CHARDEF); } else { //loc_8DF7C //v1 = c - 0x80; //v0 = v1 < 0x2E ? 1 : 0; //v0 = v1 << 1; if (c - 0x80 < 0x2E) { //v0 += t6; //a3 = v0[0]; t5 = 1; }//loc_8DF98 //v0 = a3 << 3; //v0 -= a3; //v0 -= 0xE7; //a3 = v0 + t4; } //loc_8DFA8 } } } //loc_8DFFC if (a1 != 0 && t5 == 0) { //loc_8E010 *a1 = t1; } else if (a1 != 0 && t1 != 0) { t1 -= 4; } //loc_8E014 if (a2 != 0) { *a2 = t2; } *a1 = t1; return t0; } #endif void GetStringDimensions(char* string, unsigned short* w, unsigned short* h)//8E028(<), 9006C(<) (F) { unsigned short sw;//18 unsigned short sh;//16 long t9;//t9 long t7;//t7 char c;//a0 long v0; t9 = GetStringLength(string, &sw, &sh); c = *string++; while (c != 0) { t7 = (sh - sw) + 2; //loc_8E070 if (c == 0xA) { if (*string != 0xA) { //loc_8E094 if (*string != 0x0) { v0 = GetStringLength(string, &sw, &sh); t7 = (t7 + 2) + (sh - sw); if (t9 < v0 != 0) { t9 = v0; } } } else { t7 += 16; } } //loc_8E0CC c = *string++; } //loc_8E0DC *h = t7; *w = t9; } void DrawChar(unsigned short a0, unsigned short a1, unsigned short a2, struct CHARDEF* a3)//8DDBC(<), 8FE00(<) (F) { struct CVECTOR* TopShade;//$v0 struct CVECTOR* BottomShade;//$at long v1; a2 &= 0xFFFF; if ((unsigned long) &db.polyptr[0] < (unsigned long) &db.polybuf_limit[0]) { TopShade = &FontShades[a2][a3->TopShade]; BottomShade = &FontShades[a2][a3->BottomShade]; *(long*) &db.polyptr[4] = *(long*) &TopShade->r; *(long*) &db.polyptr[28] = *(long*) &BottomShade->r; *(long*) &db.polyptr[16] = *(long*) &TopShade->r; *(long*) &db.polyptr[40] = *(long*) &BottomShade->r; ((char*) db.polyptr)[7] = 0x3C;//#define TAG_PGT4 0x3C *(short*) &db.polyptr[14] = 4197; *(short*) &db.polyptr[26] = 41; //sizeof(POLY_GT4); v1 = a3->w; a1 += a3->YOffset; if (ScaleFlag != 0) { v1 = (a3->w >> 2) - a3->w + 1; } //loc_8DE5C *(short*) &db.polyptr[8] = a0; *(short*) &db.polyptr[10] = a1; *(short*) &db.polyptr[20] = a0 + v1; *(short*) &db.polyptr[22] = a1; *(short*) &db.polyptr[32] = a0; *(short*) &db.polyptr[34] = a1 + a3->h; *(short*) &db.polyptr[44] = a0 + v1; *(short*) &db.polyptr[46] = a1 + a3->h; *(char*) &db.polyptr[12] = a3->w; *(char*) &db.polyptr[13] = a3->v; *(char*) &db.polyptr[24] = a3->u + a3->v; *(char*) &db.polyptr[25] = a3->v; *(char*) &db.polyptr[36] = a3->u; *(char*) &db.polyptr[37] = a3->v + a3->h; *(char*) &db.polyptr[48] = a3->u + a3->w; *(char*) &db.polyptr[49] = a3->v + a3->h; *(long*) &db.polyptr[0] = db.ot[0] | 0x0C000000; db.ot[0] = (unsigned long) db.polyptr; db.polyptr += sizeof(POLY_GT4); }//locret_8DED4 }<|endoftext|>
<commit_before>// // Created by Miguel Rentes on 30/01/2017. // #include "STL.h" void printKMax(int arr[], int n, int k) { deque<int> mydeque; int greatest = 0; // for each group of k-elements: // push it to the deque // iterate over it and find the greatest value // on the next iterations, push only one more value // and iterate again over the first k-elements // on the deque } int main(void) { int t; cin >> t; while (t > 0) { int n, k; cin >> n >> k; int i; int arr[n]; for (i = 0; i < n; i++) cin >> arr[i]; printKMax(arr, n, k); t--; } return EXIT_SUCCESS; }<commit_msg>Starts solution for the Deque-STL challenge.<commit_after>// // Created by Miguel Rentes on 30/01/2017. // #include "STL.h" void printKMax(int arr[], int n, int k) { deque<int> mydeque; std::deque<int>::iterator it = mydeque.begin(); int greatest = 0; int value = 0; int index = k; // for each group of k-elements: // push it to the deque for (int i = 0; i < k; i++) { mydeque.push_front(arr[i]); value = mydeque.front(); if (value > greatest) greatest = value; } while (it != mydeque.end()) std::cout << *it++ << ' '; // iterate over it and find the greatest value // on the next iterations, push only one more value // and iterate again over the first k-elements // on the deque } int main(void) { int t; cin >> t; while (t > 0) { int n, k; cin >> n >> k; int i; int arr[n]; for (i = 0; i < n; i++) cin >> arr[i]; printKMax(arr, n, k); t--; } return EXIT_SUCCESS; }<|endoftext|>
<commit_before>#ifndef __MAPS_GRIDMAP_HPP_ #define __MAPS_GRIDMAP_HPP_ #pragma once #include <maps/LocalMap.hpp> #include <maps/grid/GridCell.hpp> /** std **/ #include <iostream> #include <type_traits> /** Boost **/ #include <boost/shared_ptr.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <boost/serialization/access.hpp> #include <boost/serialization/nvp.hpp> namespace maps { namespace grid { /**@brief GridMap class IEEE 1873 standard * This map is a Grid structure for a raster metric (Cartesian) map * This map offers a template class for all maps that are regular grids */ template <typename T, typename R = GridCell<T> > class GridMap: public LocalMap, public R { private: /** * @brief Resolution of the cell in local x-axis and y-axis * @details * Size of the cell in local x- und y-axis in some distance/length unit * (e.g. meter or inch) * The unit used in the resolution should be the same as the unit used for * the translation part of the local frame. (s. LocalMapData::offset) */ Vector2d resolution; public: typedef R GridCellType; typedef T CellType; GridMap() : LocalMap(maps::LocalMapType::GRID_MAP), R(), resolution(0,0) { } GridMap(const GridMap& other) : LocalMap(other), R(other), resolution(other.resolution) { } template<class T2, class R2> GridMap(const GridMap<T2, R2>& other, const R& storage) : LocalMap(other) , R(storage) , resolution(other.getResolution()) { } /** @brief Constructor of the abstract GridMap class * * Defines the extends and positioning of the grid. The grid is assumed * to be on the x-y plane of the reference frame. The number of grid * cells is given by the num_cells parameter. Each dimension (x and y) * also has an scaling and offset parameter, such that the origin of the * grid (grid_map) can be moved around and the grid scaled. * * The relation between the grid cell index and position is: * * @verbatim * * v_position = v_index * resolution + offset * * where: * v_position is a 2x1 vector [x, y] wrt the local coordinate frame * v_index is a 2x1 vector [x, y] defining the index in the grid * resolution is a 2x1 vector defining the resolution of each grid cell * offset as it is defined in LocalMap class * * @endverbatim * * @param resolution - resolution of the x and y axis * @param num_cell - number of cells in x and y direction * @param default_value - default value */ GridMap(const Vector2ui &num_cells, const Vector2d &resolution, const T& default_value) : LocalMap(maps::LocalMapType::GRID_MAP), R(num_cells, default_value), resolution(resolution) { } GridMap(const Vector2ui &num_cells, const Vector2d &resolution, const T& default_value, const boost::shared_ptr<LocalMapData> &data) : LocalMap(data), R(num_cells, default_value), resolution(resolution) {} /** @brief default destructor */ ~GridMap() { } public: using R::getNumCells; size_t getNumElements() const { return getNumCells().prod(); } const Vector2d& getResolution() const { return resolution; } void setResolution(const Vector2d& newRes) { if(newRes.isApprox(resolution, 0.00001)) return; resolution = newRes; this->clear(); } Vector2d getSize() const { return resolution.array() * Vector2ui(getNumCells()).cast<double>().array(); } bool inGrid(const Index& idx) const { // do not need to check idx against (0,0), // until idx is of type unsigned int return idx.isInside(Index(getNumCells())); } /** @brief get a position of an index from the Grid * */ bool fromGrid(const Index& idx, Vector3d& pos) const { /** Index inside the grid **/ if (inGrid(idx)) { // position at the cell center without offset transformation Vector2d center = (idx.cast<double>() + Vector2d(0.5, 0.5)).array() * resolution.array(); // Apply the offset transformation to the obtained position // pos_local = (Tgrid_local)^-1 * pos_grid pos = this->getLocalFrame().inverse() * Vector3d(center.x(), center.y(), 0.); return true; } else { /** Index outside the grid **/ return false; } } /** @brief get a position of an index from the Grid applying an offset * set in the argument of the method * transformation. T_offset = frame_in_map = Tmap_frame * frame expressed with respect to the map_frame. * map_frame is the local_frame in case there is an offset or grid_map * in case there is not offset * */ bool fromGrid(const Index& idx, Vector3d& pos_in_frame, const base::Transform3d &frame_in_map) const { Vector3d pos_in_map; if (fromGrid(idx, pos_in_map) == false) return false; /** Transform the position by the offset form the argument **/ /** pos_in_frame = (Tmap_frame)^inverse * pos_in_map **/ pos_in_frame = frame_in_map.inverse() * pos_in_map; return true; } /** @brief get the index to grid of a position * */ bool toGrid(const Vector3d& pos, Index& idx, Vector3d &pos_diff) const { // Get the 2D position without the offset (in grid_frame) // pos_grid = Tgrid_local pos_local Vector2d pos_grid = Vector3d(this->getLocalFrame() * pos).head<2>(); // Get the index for the pos_grid // cast to float due to position which lies on the border between two cells Eigen::Vector2d idx_double = pos_grid.array() / resolution.array(); Index idx_temp(std::floor(idx_double.x()), std::floor(idx_double.y())); Vector3d center; if(inGrid(idx_temp) && fromGrid(idx_temp, center)) { idx = idx_temp; pos_diff = pos - center; return true; } else { return false; } } /** @brief get an index of a position in the map applying an offset set * in the argument of the method. * * transformation. T_offset = frame_in_map = Tmap_frame * frame expressed with respect to the map_frame. * map_frame is the local_frame in case there is an offset or grid_map * in case there is not offset * */ bool toGrid(const Vector3d& pos_in_frame, Index& idx, const base::Transform3d &frame_in_map) const { /** Transform the position by the offset form the argument **/ /** pos_in_map = Tmap_frame * pos_in_frame **/ Eigen::Vector3d pos_in_map = frame_in_map * pos_in_frame; Eigen::Vector3d pos_diff; return toGrid(pos_in_map, idx, pos_diff); } bool toGrid(const Vector3d& pos, Index& idx) const { Vector3d pos_diff; return toGrid(pos, idx, pos_diff); } const T& at(const Vector3d& pos) const { Index idx; if (!this->toGrid(pos, idx)) throw std::runtime_error("Provided position is out of the grid."); return at(idx); } T& at(const Vector3d& pos) { Index idx; if (!this->toGrid(pos, idx)) throw std::runtime_error("Provided position is out of the grid"); return at(idx); } using R::at; /** * @brief [brief description] * @details enable this function only for arithmetic types (integral and floating types) * hide this function e.g. for class types * * It also has the possibility to exclude the default_value * * @return [description] */ template<class Q = T> const typename std::enable_if<std::is_arithmetic<Q>::value, Q>::type& getMax(const bool include_default_value = true) const { Vector2ui numCells(getNumCells()); std::cout << "Num Cells is " << numCells.transpose() << std::endl; if(numCells == Vector2ui(0,0)) throw std::runtime_error("Tried to compute max on empty map"); auto it = this->begin(); auto endIt = this->end(); const Q *first = &(*it); // const Q *last = &(*(this->end())); /** Include the default value as a possible max value to return **/ if (include_default_value) { return *std::max_element(this->begin(), this->end()); } else { const Q *largest = first; while (it != endIt) { const Q *curElem = &(*it); if(!this->isDefault(*largest)) { if ((*largest < *curElem)&&(!this->isDefault(*curElem))) { largest = curElem; } } else { if (!this->isDefault(*curElem)) largest = curElem; } it++; } return *largest; } } /** * @brief [brief description] * @details enable this function only for arithmetic types (integral and floating types) * hide this function e.g. for class types * * It also has the possibility to exclude the default_value * * @return [description] */ template<class Q = T> const typename std::enable_if<std::is_arithmetic<Q>::value, Q>::type& getMin(const bool include_default_value = true) const { Vector2ui numCells(getNumCells()); std::cout << "Num Cells is " << numCells.transpose() << std::endl; if(numCells == Vector2ui(0,0)) throw std::runtime_error("Tried to compute max on empty map"); auto it = this->begin(); auto endIt = this->end(); const Q *first = &(*it); // const Q *last = &(*(this->end())); /** Include the default value as a possible max value to return **/ if (include_default_value) { return *std::min_element(this->begin(), this->end()); } else { const Q *smallest = first; while (it != endIt) { const Q *curElem = &(*it); if(!this->isDefault(*smallest)) { if ((*curElem < *smallest) &&(!this->isDefault(*curElem))) { smallest = curElem; } } else { if (!this->isDefault(*curElem)) smallest = curElem; } it++; } return *smallest; } } bool isDefault(const T &value) const { if (boost::math::isnan(this->getDefaultValue())) { return boost::math::isnan(value); } else { return value == this->getDefaultValue(); } } protected: /** Grants access to boost serialization */ friend class boost::serialization::access; /** Serializes the members of this class*/ template <typename Archive> void serialize(Archive &ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(::maps::LocalMap); ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(R); ar & BOOST_SERIALIZATION_NVP(resolution); } }; typedef GridMap<char> GridMapC; typedef GridMap<int> GridMapI; typedef GridMap<float> GridMapF; typedef GridMap<double> GridMapD; }} #endif /* __MAPS_GRIDMAP_HPP_ */ <commit_msg>Added function to extend a gridMap<commit_after>#ifndef __MAPS_GRIDMAP_HPP_ #define __MAPS_GRIDMAP_HPP_ #pragma once #include <maps/LocalMap.hpp> #include <maps/grid/GridCell.hpp> /** std **/ #include <iostream> #include <type_traits> /** Boost **/ #include <boost/shared_ptr.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <boost/serialization/access.hpp> #include <boost/serialization/nvp.hpp> namespace maps { namespace grid { /**@brief GridMap class IEEE 1873 standard * This map is a Grid structure for a raster metric (Cartesian) map * This map offers a template class for all maps that are regular grids */ template <typename T, typename R = GridCell<T> > class GridMap: public LocalMap, public R { private: /** * @brief Resolution of the cell in local x-axis and y-axis * @details * Size of the cell in local x- und y-axis in some distance/length unit * (e.g. meter or inch) * The unit used in the resolution should be the same as the unit used for * the translation part of the local frame. (s. LocalMapData::offset) */ Vector2d resolution; public: typedef R GridCellType; typedef T CellType; GridMap() : LocalMap(maps::LocalMapType::GRID_MAP), R(), resolution(0,0) { } GridMap(const GridMap& other) : LocalMap(other), R(other), resolution(other.resolution) { } template<class T2, class R2> GridMap(const GridMap<T2, R2>& other, const R& storage) : LocalMap(other) , R(storage) , resolution(other.getResolution()) { } /** @brief Constructor of the abstract GridMap class * * Defines the extends and positioning of the grid. The grid is assumed * to be on the x-y plane of the reference frame. The number of grid * cells is given by the num_cells parameter. Each dimension (x and y) * also has an scaling and offset parameter, such that the origin of the * grid (grid_map) can be moved around and the grid scaled. * * The relation between the grid cell index and position is: * * @verbatim * * v_position = v_index * resolution + offset * * where: * v_position is a 2x1 vector [x, y] wrt the local coordinate frame * v_index is a 2x1 vector [x, y] defining the index in the grid * resolution is a 2x1 vector defining the resolution of each grid cell * offset as it is defined in LocalMap class * * @endverbatim * * @param resolution - resolution of the x and y axis * @param num_cell - number of cells in x and y direction * @param default_value - default value */ GridMap(const Vector2ui &num_cells, const Vector2d &resolution, const T& default_value) : LocalMap(maps::LocalMapType::GRID_MAP), R(num_cells, default_value), resolution(resolution) { } GridMap(const Vector2ui &num_cells, const Vector2d &resolution, const T& default_value, const boost::shared_ptr<LocalMapData> &data) : LocalMap(data), R(num_cells, default_value), resolution(resolution) {} /** @brief default destructor */ ~GridMap() { } public: using R::getNumCells; size_t getNumElements() const { return getNumCells().prod(); } const Vector2d& getResolution() const { return resolution; } void setResolution(const Vector2d& newRes) { if(newRes.isApprox(resolution, 0.00001)) return; resolution = newRes; this->clear(); } Vector2d getSize() const { return resolution.array() * Vector2ui(getNumCells()).cast<double>().array(); } bool inGrid(const Index& idx) const { // do not need to check idx against (0,0), // until idx is of type unsigned int return idx.isInside(Index(getNumCells())); } /** @brief get a position of an index from the Grid * */ bool fromGrid(const Index& idx, Vector3d& pos) const { /** Index inside the grid **/ if (inGrid(idx)) { // position at the cell center without offset transformation Vector2d center = (idx.cast<double>() + Vector2d(0.5, 0.5)).array() * resolution.array(); // Apply the offset transformation to the obtained position // pos_local = (Tgrid_local)^-1 * pos_grid pos = this->getLocalFrame().inverse() * Vector3d(center.x(), center.y(), 0.); return true; } else { /** Index outside the grid **/ return false; } } /** @brief get a position of an index from the Grid applying an offset * set in the argument of the method * transformation. T_offset = frame_in_map = Tmap_frame * frame expressed with respect to the map_frame. * map_frame is the local_frame in case there is an offset or grid_map * in case there is not offset * */ bool fromGrid(const Index& idx, Vector3d& pos_in_frame, const base::Transform3d &frame_in_map) const { Vector3d pos_in_map; if (fromGrid(idx, pos_in_map) == false) return false; /** Transform the position by the offset form the argument **/ /** pos_in_frame = (Tmap_frame)^inverse * pos_in_map **/ pos_in_frame = frame_in_map.inverse() * pos_in_map; return true; } /** @brief get the index to grid of a position * */ bool toGrid(const Vector3d& pos, Index& idx, Vector3d &pos_diff) const { // Get the 2D position without the offset (in grid_frame) // pos_grid = Tgrid_local pos_local Vector2d pos_grid = Vector3d(this->getLocalFrame() * pos).head<2>(); // Get the index for the pos_grid // cast to float due to position which lies on the border between two cells Eigen::Vector2d idx_double = pos_grid.array() / resolution.array(); Index idx_temp(std::floor(idx_double.x()), std::floor(idx_double.y())); Vector3d center; if(inGrid(idx_temp) && fromGrid(idx_temp, center)) { idx = idx_temp; pos_diff = pos - center; return true; } else { return false; } } /** @brief get an index of a position in the map applying an offset set * in the argument of the method. * * transformation. T_offset = frame_in_map = Tmap_frame * frame expressed with respect to the map_frame. * map_frame is the local_frame in case there is an offset or grid_map * in case there is not offset * */ bool toGrid(const Vector3d& pos_in_frame, Index& idx, const base::Transform3d &frame_in_map) const { /** Transform the position by the offset form the argument **/ /** pos_in_map = Tmap_frame * pos_in_frame **/ Eigen::Vector3d pos_in_map = frame_in_map * pos_in_frame; Eigen::Vector3d pos_diff; return toGrid(pos_in_map, idx, pos_diff); } bool toGrid(const Vector3d& pos, Index& idx) const { Vector3d pos_diff; return toGrid(pos, idx, pos_diff); } const T& at(const Vector3d& pos) const { Index idx; if (!this->toGrid(pos, idx)) throw std::runtime_error("Provided position is out of the grid."); return at(idx); } T& at(const Vector3d& pos) { Index idx; if (!this->toGrid(pos, idx)) throw std::runtime_error("Provided position is out of the grid"); return at(idx); } using R::at; /** * @brief [brief description] * @details enable this function only for arithmetic types (integral and floating types) * hide this function e.g. for class types * * It also has the possibility to exclude the default_value * * @return [description] */ template<class Q = T> const typename std::enable_if<std::is_arithmetic<Q>::value, Q>::type& getMax(const bool include_default_value = true) const { Vector2ui numCells(getNumCells()); std::cout << "Num Cells is " << numCells.transpose() << std::endl; if(numCells == Vector2ui(0,0)) throw std::runtime_error("Tried to compute max on empty map"); auto it = this->begin(); auto endIt = this->end(); const Q *first = &(*it); // const Q *last = &(*(this->end())); /** Include the default value as a possible max value to return **/ if (include_default_value) { return *std::max_element(this->begin(), this->end()); } else { const Q *largest = first; while (it != endIt) { const Q *curElem = &(*it); if(!this->isDefault(*largest)) { if ((*largest < *curElem)&&(!this->isDefault(*curElem))) { largest = curElem; } } else { if (!this->isDefault(*curElem)) largest = curElem; } it++; } return *largest; } } /** * @brief [brief description] * @details enable this function only for arithmetic types (integral and floating types) * hide this function e.g. for class types * * It also has the possibility to exclude the default_value * * @return [description] */ template<class Q = T> const typename std::enable_if<std::is_arithmetic<Q>::value, Q>::type& getMin(const bool include_default_value = true) const { Vector2ui numCells(getNumCells()); std::cout << "Num Cells is " << numCells.transpose() << std::endl; if(numCells == Vector2ui(0,0)) throw std::runtime_error("Tried to compute max on empty map"); auto it = this->begin(); auto endIt = this->end(); const Q *first = &(*it); // const Q *last = &(*(this->end())); /** Include the default value as a possible max value to return **/ if (include_default_value) { return *std::min_element(this->begin(), this->end()); } else { const Q *smallest = first; while (it != endIt) { const Q *curElem = &(*it); if(!this->isDefault(*smallest)) { if ((*curElem < *smallest) &&(!this->isDefault(*curElem))) { smallest = curElem; } } else { if (!this->isDefault(*curElem)) smallest = curElem; } it++; } return *smallest; } } bool isDefault(const T &value) const { if (boost::math::isnan(this->getDefaultValue())) { return boost::math::isnan(value); } else { return value == this->getDefaultValue(); } } void extend(const Vector2ui &minSize) { Vector2ui newSize; newSize.x() = std::max(minSize.x(), getNumCells().x()); newSize.y() = std::max(minSize.y(), getNumCells().y()); this->resize(newSize); } protected: /** Grants access to boost serialization */ friend class boost::serialization::access; /** Serializes the members of this class*/ template <typename Archive> void serialize(Archive &ar, const unsigned int version) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(::maps::LocalMap); ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(R); ar & BOOST_SERIALIZATION_NVP(resolution); } }; typedef GridMap<char> GridMapC; typedef GridMap<int> GridMapI; typedef GridMap<float> GridMapF; typedef GridMap<double> GridMapD; }} #endif /* __MAPS_GRIDMAP_HPP_ */ <|endoftext|>
<commit_before>/* * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji * * 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 <memory> #include <vector> #include <algorithm> #include <bcc/BPF.h> extern "C" { #include <unistd.h> #include <stdarg.h> #include <sys/time.h> #include <fnmatch.h> #include "h2o/memory.h" #include "h2o/version.h" } #include "h2olog.h" #define POLL_TIMEOUT (1000) #define PERF_BUFFER_PAGE_COUNT 256 static void usage(void) { printf(R"(h2olog (h2o v%s) Usage: h2olog -p PID h2olog quic -p PID Optional arguments: -d Print debugging information (-dd shows more) -h Print this help and exit -l Print the list of available tracepoints and exit -s RESPONSE_HEADER_NAME A response header name to show, e.g. "content-type" -t TRACEPOINT A tracepoint, or fully-qualified probe name, to show, accepting a glob pattern, e.g. "quicly:accept", "h2o:*" -r Run without dropping root privilege -w Path to write the output (default: stdout) Examples: h2olog quic -p $(pgrep -o h2o) h2olog quic -p $(pgrep -o h2o) -t quicly:accept -t quicly:free h2olog quic -p $(pgrep -o h2o) -t h2o:send_response_header -t h2o:h3s_accept -t h2o:h3s_destroy -s alt-svc )", H2O_VERSION); return; } static void make_timestamp(char *buf, size_t buf_len) { time_t t = time(NULL); struct tm tms; localtime_r(&t, &tms); const char *iso8601format = "%FT%TZ"; strftime(buf, buf_len, iso8601format, &tms); } static void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2))); static void infof(const char *fmt, ...) { char buf[1024]; va_list args; va_start(args, fmt); vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); char timestamp[128]; make_timestamp(timestamp, sizeof(timestamp)); fprintf(stderr, "%s %s\n", timestamp, buf); } uint64_t h2o_tracer::time_milliseconds() { struct timeval tv; gettimeofday(&tv, NULL); return (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000; } void h2o_tracer::show_event_per_sec(time_t *t0) { time_t t1 = time(NULL); int64_t d = t1 - *t0; if (d > 10) { uint64_t c = stats_.num_events / d; if (c > 0) { if (stats_.num_lost > 0) { infof("%20" PRIu64 " events/s (possibly lost %" PRIu64 " events)", c, stats_.num_lost); stats_.num_lost = 0; } else { infof("%20" PRIu64 " events/s", c); } stats_.num_events = 0; } *t0 = t1; } } static void show_process(pid_t pid) { char cmdline[256]; char proc_file[256]; snprintf(proc_file, sizeof(proc_file), "/proc/%d/cmdline", pid); FILE *f = fopen(proc_file, "r"); if (f == nullptr) { fprintf(stderr, "Error: failed to open %s: %s\n", proc_file, strerror(errno)); exit(EXIT_FAILURE); } size_t nread = fread(cmdline, 1, sizeof(cmdline), f); fclose(f); if (nread == 0) { fprintf(stderr, "Error: failed to read from %s: %s\n", proc_file, strerror(errno)); exit(EXIT_FAILURE); } nread--; // skip trailing nul for (size_t i = 0; i < nread; i++) { if (cmdline[i] == '\0') { cmdline[i] = ' '; } } infof("Attaching pid=%d (%s)", pid, cmdline); } static void drop_root_privilege(void) { if (getuid() == 0) { const char *sudo_gid = getenv("SUDO_GID"); if (sudo_gid == NULL) { fprintf(stderr, "Error: the SUDO_GID environment variable is not set\n"); exit(EXIT_FAILURE); } errno = 0; gid_t gid = (gid_t)strtol(sudo_gid, NULL, 10); if (errno != 0) { fprintf(stderr, "Error: failed to parse SUDO_GID\n"); exit(EXIT_FAILURE); } if (setgid(gid) != 0) { perror("Error: setgid(2) failed"); exit(EXIT_FAILURE); } const char *sudo_uid = getenv("SUDO_UID"); if (sudo_uid == NULL) { fprintf(stderr, "Error: the SUDO_UID environment variable is not set\n"); exit(EXIT_FAILURE); } errno = 0; uid_t uid = (uid_t)strtol(sudo_uid, NULL, 10); if (errno != 0) { fprintf(stderr, "Error: failed to parse SUDO_UID\n"); exit(EXIT_FAILURE); } if (setuid(uid) != 0) { perror("Error: setuid(2) failed"); exit(EXIT_FAILURE); } } } static std::string join_str(const std::string &sep, const std::vector<std::string> &strs) { std::string s; for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) { if (iter != strs.cbegin()) { s += sep; } s += *iter; } return s; } static std::string generate_header_filter_cflag(const std::vector<std::string> &tokens) { std::vector<std::string> conditions; for (auto &token : tokens) { char buf[256]; snprintf(buf, sizeof(buf), "/* %s */ (slen) == %zu", token.c_str(), token.size()); std::vector<std::string> exprs = {buf}; for (size_t i = 0; i < token.size(); ++i) { snprintf(buf, sizeof(buf), "(s)[%zu] == '%c'", i, token[i]); exprs.push_back(buf); } conditions.push_back("(" + join_str(" && ", exprs) + ")"); } std::string cflag("-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=("); cflag += join_str(" || ", conditions); cflag += ")"; return cflag; } static std::string make_pid_cflag(const char *macro_name, pid_t pid) { char buf[256]; snprintf(buf, sizeof(buf), "-D%s=%d", macro_name, pid); return std::string(buf); } static void event_cb(void *context, void *data, int len) { h2o_tracer *tracer = (h2o_tracer *)context; tracer->handle_event(data, len); } static void lost_cb(void *context, uint64_t lost) { h2o_tracer *tracer = (h2o_tracer *)context; tracer->handle_lost(lost); } static size_t add_matched_usdts(std::vector<h2o_tracer::usdt> &selected_usdts, const std::vector<h2o_tracer::usdt> &available_usdts, const char *pattern) { size_t added = 0; for (const auto &usdt : available_usdts) { if (fnmatch(pattern, usdt.fully_qualified_name().c_str(), 0) == 0) { selected_usdts.push_back(usdt); added++; } } return added; } int main(int argc, char **argv) { std::unique_ptr<h2o_tracer> tracer; if (argc > 1 && strcmp(argv[1], "quic") == 0) { tracer.reset(create_quic_tracer()); --argc; ++argv; } else { tracer.reset(create_http_tracer()); } const std::vector<h2o_tracer::usdt> available_usdts = tracer->usdt_probes(); int debug = 0; int preserve_root = 0; FILE *outfp = stdout; std::vector<h2o_tracer::usdt> selected_usdts; std::vector<std::string> response_header_filters; int c; pid_t h2o_pid = -1; while ((c = getopt(argc, argv, "hdrlp:t:s:w:")) != -1) { switch (c) { case 'p': h2o_pid = atoi(optarg); break; case 't': { size_t added = add_matched_usdts(selected_usdts, available_usdts, optarg); if (added == 0) { fprintf(stderr, "No such tracepoint: %s\n", optarg); exit(EXIT_FAILURE); } break; } case 's': response_header_filters.push_back(optarg); break; case 'w': if ((outfp = fopen(optarg, "w")) == nullptr) { fprintf(stderr, "Error: failed to open %s: %s", optarg, strerror(errno)); exit(EXIT_FAILURE); } break; case 'd': debug++; break; case 'l': for (const auto &usdt : available_usdts) { printf("%s\n", usdt.fully_qualified_name().c_str()); } exit(EXIT_SUCCESS); break; case 'r': preserve_root = 1; break; case 'h': usage(); exit(EXIT_SUCCESS); default: usage(); exit(EXIT_FAILURE); } } if (argc > optind) { fprintf(stderr, "Error: too many aruments\n"); usage(); exit(EXIT_FAILURE); } if (h2o_pid == -1) { fprintf(stderr, "Error: -p option is missing\n"); usage(); exit(EXIT_FAILURE); } if (geteuid() != 0) { fprintf(stderr, "Error: root privilege is required\n"); exit(EXIT_FAILURE); } tracer->init(outfp); std::vector<std::string> cflags({ make_pid_cflag("H2OLOG_H2O_PID", h2o_pid), }); if (!response_header_filters.empty()) { cflags.push_back(generate_header_filter_cflag(response_header_filters)); } if (selected_usdts.empty()) { selected_usdts = available_usdts; } if (debug >= 2) { fprintf(stderr, "selected_usdts="); for (auto iter = selected_usdts.cbegin(); iter != selected_usdts.cend(); iter++) { if (iter != selected_usdts.cbegin()) { fprintf(stderr, ","); } fprintf(stderr, "%s", iter->fully_qualified_name().c_str()); } fprintf(stderr, "\n"); fprintf(stderr, "cflags="); for (size_t i = 0; i < cflags.size(); i++) { if (i > 0) { fprintf(stderr, " "); } fprintf(stderr, "%s", cflags[i].c_str()); } fprintf(stderr, "\n"); fprintf(stderr, "<BPF>\n%s\n</BPF>\n", tracer->bpf_text().c_str()); } ebpf::BPF *bpf = new ebpf::BPF(); std::vector<ebpf::USDT> probes; for (const auto &usdt : selected_usdts) { probes.push_back(ebpf::USDT(h2o_pid, usdt.provider, usdt.name, usdt.probe_func)); } ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes); if (ret.code() != 0) { fprintf(stderr, "Error: init: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } bpf->attach_tracepoint("sched:sched_process_exit", "trace_sched_process_exit"); for (auto &probe : probes) { ret = bpf->attach_usdt(probe); if (ret.code() != 0) { fprintf(stderr, "Error: attach_usdt: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } } ret = bpf->open_perf_buffer("events", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT); if (ret.code() != 0) { fprintf(stderr, "Error: open_perf_buffer: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } if (debug) { show_process(h2o_pid); } if (!preserve_root) { drop_root_privilege(); } ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events"); if (perf_buffer) { time_t t0 = time(NULL); while (true) { perf_buffer->poll(POLL_TIMEOUT); tracer->flush(); if (debug) { tracer->show_event_per_sec(&t0); } } } fprintf(stderr, "Error: failed to get_perf_buffer()\n"); return EXIT_FAILURE; } <commit_msg>Update src/h2olog/h2olog.cc<commit_after>/* * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji * * 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 <memory> #include <vector> #include <algorithm> #include <bcc/BPF.h> extern "C" { #include <unistd.h> #include <stdarg.h> #include <sys/time.h> #include <fnmatch.h> #include "h2o/memory.h" #include "h2o/version.h" } #include "h2olog.h" #define POLL_TIMEOUT (1000) #define PERF_BUFFER_PAGE_COUNT 256 static void usage(void) { printf(R"(h2olog (h2o v%s) Usage: h2olog -p PID h2olog quic -p PID Optional arguments: -d Print debugging information (-dd shows more) -h Print this help and exit -l Print the list of available tracepoints and exit -s RESPONSE_HEADER_NAME A response header name to show, e.g. "content-type" -t TRACEPOINT A tracepoint, or fully-qualified probe name, to show, including a glob pattern, e.g. "quicly:accept", "h2o:*" -r Run without dropping root privilege -w Path to write the output (default: stdout) Examples: h2olog quic -p $(pgrep -o h2o) h2olog quic -p $(pgrep -o h2o) -t quicly:accept -t quicly:free h2olog quic -p $(pgrep -o h2o) -t h2o:send_response_header -t h2o:h3s_accept -t h2o:h3s_destroy -s alt-svc )", H2O_VERSION); return; } static void make_timestamp(char *buf, size_t buf_len) { time_t t = time(NULL); struct tm tms; localtime_r(&t, &tms); const char *iso8601format = "%FT%TZ"; strftime(buf, buf_len, iso8601format, &tms); } static void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2))); static void infof(const char *fmt, ...) { char buf[1024]; va_list args; va_start(args, fmt); vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); char timestamp[128]; make_timestamp(timestamp, sizeof(timestamp)); fprintf(stderr, "%s %s\n", timestamp, buf); } uint64_t h2o_tracer::time_milliseconds() { struct timeval tv; gettimeofday(&tv, NULL); return (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000; } void h2o_tracer::show_event_per_sec(time_t *t0) { time_t t1 = time(NULL); int64_t d = t1 - *t0; if (d > 10) { uint64_t c = stats_.num_events / d; if (c > 0) { if (stats_.num_lost > 0) { infof("%20" PRIu64 " events/s (possibly lost %" PRIu64 " events)", c, stats_.num_lost); stats_.num_lost = 0; } else { infof("%20" PRIu64 " events/s", c); } stats_.num_events = 0; } *t0 = t1; } } static void show_process(pid_t pid) { char cmdline[256]; char proc_file[256]; snprintf(proc_file, sizeof(proc_file), "/proc/%d/cmdline", pid); FILE *f = fopen(proc_file, "r"); if (f == nullptr) { fprintf(stderr, "Error: failed to open %s: %s\n", proc_file, strerror(errno)); exit(EXIT_FAILURE); } size_t nread = fread(cmdline, 1, sizeof(cmdline), f); fclose(f); if (nread == 0) { fprintf(stderr, "Error: failed to read from %s: %s\n", proc_file, strerror(errno)); exit(EXIT_FAILURE); } nread--; // skip trailing nul for (size_t i = 0; i < nread; i++) { if (cmdline[i] == '\0') { cmdline[i] = ' '; } } infof("Attaching pid=%d (%s)", pid, cmdline); } static void drop_root_privilege(void) { if (getuid() == 0) { const char *sudo_gid = getenv("SUDO_GID"); if (sudo_gid == NULL) { fprintf(stderr, "Error: the SUDO_GID environment variable is not set\n"); exit(EXIT_FAILURE); } errno = 0; gid_t gid = (gid_t)strtol(sudo_gid, NULL, 10); if (errno != 0) { fprintf(stderr, "Error: failed to parse SUDO_GID\n"); exit(EXIT_FAILURE); } if (setgid(gid) != 0) { perror("Error: setgid(2) failed"); exit(EXIT_FAILURE); } const char *sudo_uid = getenv("SUDO_UID"); if (sudo_uid == NULL) { fprintf(stderr, "Error: the SUDO_UID environment variable is not set\n"); exit(EXIT_FAILURE); } errno = 0; uid_t uid = (uid_t)strtol(sudo_uid, NULL, 10); if (errno != 0) { fprintf(stderr, "Error: failed to parse SUDO_UID\n"); exit(EXIT_FAILURE); } if (setuid(uid) != 0) { perror("Error: setuid(2) failed"); exit(EXIT_FAILURE); } } } static std::string join_str(const std::string &sep, const std::vector<std::string> &strs) { std::string s; for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) { if (iter != strs.cbegin()) { s += sep; } s += *iter; } return s; } static std::string generate_header_filter_cflag(const std::vector<std::string> &tokens) { std::vector<std::string> conditions; for (auto &token : tokens) { char buf[256]; snprintf(buf, sizeof(buf), "/* %s */ (slen) == %zu", token.c_str(), token.size()); std::vector<std::string> exprs = {buf}; for (size_t i = 0; i < token.size(); ++i) { snprintf(buf, sizeof(buf), "(s)[%zu] == '%c'", i, token[i]); exprs.push_back(buf); } conditions.push_back("(" + join_str(" && ", exprs) + ")"); } std::string cflag("-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=("); cflag += join_str(" || ", conditions); cflag += ")"; return cflag; } static std::string make_pid_cflag(const char *macro_name, pid_t pid) { char buf[256]; snprintf(buf, sizeof(buf), "-D%s=%d", macro_name, pid); return std::string(buf); } static void event_cb(void *context, void *data, int len) { h2o_tracer *tracer = (h2o_tracer *)context; tracer->handle_event(data, len); } static void lost_cb(void *context, uint64_t lost) { h2o_tracer *tracer = (h2o_tracer *)context; tracer->handle_lost(lost); } static size_t add_matched_usdts(std::vector<h2o_tracer::usdt> &selected_usdts, const std::vector<h2o_tracer::usdt> &available_usdts, const char *pattern) { size_t added = 0; for (const auto &usdt : available_usdts) { if (fnmatch(pattern, usdt.fully_qualified_name().c_str(), 0) == 0) { selected_usdts.push_back(usdt); added++; } } return added; } int main(int argc, char **argv) { std::unique_ptr<h2o_tracer> tracer; if (argc > 1 && strcmp(argv[1], "quic") == 0) { tracer.reset(create_quic_tracer()); --argc; ++argv; } else { tracer.reset(create_http_tracer()); } const std::vector<h2o_tracer::usdt> available_usdts = tracer->usdt_probes(); int debug = 0; int preserve_root = 0; FILE *outfp = stdout; std::vector<h2o_tracer::usdt> selected_usdts; std::vector<std::string> response_header_filters; int c; pid_t h2o_pid = -1; while ((c = getopt(argc, argv, "hdrlp:t:s:w:")) != -1) { switch (c) { case 'p': h2o_pid = atoi(optarg); break; case 't': { size_t added = add_matched_usdts(selected_usdts, available_usdts, optarg); if (added == 0) { fprintf(stderr, "No such tracepoint: %s\n", optarg); exit(EXIT_FAILURE); } break; } case 's': response_header_filters.push_back(optarg); break; case 'w': if ((outfp = fopen(optarg, "w")) == nullptr) { fprintf(stderr, "Error: failed to open %s: %s", optarg, strerror(errno)); exit(EXIT_FAILURE); } break; case 'd': debug++; break; case 'l': for (const auto &usdt : available_usdts) { printf("%s\n", usdt.fully_qualified_name().c_str()); } exit(EXIT_SUCCESS); break; case 'r': preserve_root = 1; break; case 'h': usage(); exit(EXIT_SUCCESS); default: usage(); exit(EXIT_FAILURE); } } if (argc > optind) { fprintf(stderr, "Error: too many aruments\n"); usage(); exit(EXIT_FAILURE); } if (h2o_pid == -1) { fprintf(stderr, "Error: -p option is missing\n"); usage(); exit(EXIT_FAILURE); } if (geteuid() != 0) { fprintf(stderr, "Error: root privilege is required\n"); exit(EXIT_FAILURE); } tracer->init(outfp); std::vector<std::string> cflags({ make_pid_cflag("H2OLOG_H2O_PID", h2o_pid), }); if (!response_header_filters.empty()) { cflags.push_back(generate_header_filter_cflag(response_header_filters)); } if (selected_usdts.empty()) { selected_usdts = available_usdts; } if (debug >= 2) { fprintf(stderr, "selected_usdts="); for (auto iter = selected_usdts.cbegin(); iter != selected_usdts.cend(); iter++) { if (iter != selected_usdts.cbegin()) { fprintf(stderr, ","); } fprintf(stderr, "%s", iter->fully_qualified_name().c_str()); } fprintf(stderr, "\n"); fprintf(stderr, "cflags="); for (size_t i = 0; i < cflags.size(); i++) { if (i > 0) { fprintf(stderr, " "); } fprintf(stderr, "%s", cflags[i].c_str()); } fprintf(stderr, "\n"); fprintf(stderr, "<BPF>\n%s\n</BPF>\n", tracer->bpf_text().c_str()); } ebpf::BPF *bpf = new ebpf::BPF(); std::vector<ebpf::USDT> probes; for (const auto &usdt : selected_usdts) { probes.push_back(ebpf::USDT(h2o_pid, usdt.provider, usdt.name, usdt.probe_func)); } ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes); if (ret.code() != 0) { fprintf(stderr, "Error: init: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } bpf->attach_tracepoint("sched:sched_process_exit", "trace_sched_process_exit"); for (auto &probe : probes) { ret = bpf->attach_usdt(probe); if (ret.code() != 0) { fprintf(stderr, "Error: attach_usdt: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } } ret = bpf->open_perf_buffer("events", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT); if (ret.code() != 0) { fprintf(stderr, "Error: open_perf_buffer: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } if (debug) { show_process(h2o_pid); } if (!preserve_root) { drop_root_privilege(); } ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events"); if (perf_buffer) { time_t t0 = time(NULL); while (true) { perf_buffer->poll(POLL_TIMEOUT); tracer->flush(); if (debug) { tracer->show_event_per_sec(&t0); } } } fprintf(stderr, "Error: failed to get_perf_buffer()\n"); return EXIT_FAILURE; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy/dhcp_proxy_script_adapter_fetcher_win.h" #include "base/bind.h" #include "base/message_loop_proxy.h" #include "base/metrics/histogram.h" #include "base/sys_string_conversions.h" #include "base/threading/worker_pool.h" #include "base/time.h" #include "net/base/net_errors.h" #include "net/proxy/dhcpcsvc_init_win.h" #include "net/proxy/proxy_script_fetcher_impl.h" #include "net/url_request/url_request_context.h" #include <windows.h> #include <winsock2.h> #include <dhcpcsdk.h> #pragma comment(lib, "dhcpcsvc.lib") namespace { // Maximum amount of time to wait for response from the Win32 DHCP API. const int kTimeoutMs = 2000; } // namespace namespace net { DhcpProxyScriptAdapterFetcher::DhcpProxyScriptAdapterFetcher( URLRequestContext* url_request_context) : state_(STATE_START), result_(ERR_IO_PENDING), callback_(NULL), ALLOW_THIS_IN_INITIALIZER_LIST( script_fetcher_callback_( this, &DhcpProxyScriptAdapterFetcher::OnFetcherDone)), url_request_context_(url_request_context) { } DhcpProxyScriptAdapterFetcher::~DhcpProxyScriptAdapterFetcher() { Cancel(); // The WeakPtr we passed to the worker thread may be destroyed on the // worker thread. This detaches any outstanding WeakPtr state from // the current thread. base::SupportsWeakPtr<DhcpProxyScriptAdapterFetcher>::DetachFromThread(); } void DhcpProxyScriptAdapterFetcher::Fetch( const std::string& adapter_name, OldCompletionCallback* callback) { DCHECK(CalledOnValidThread()); DCHECK_EQ(state_, STATE_START); result_ = ERR_IO_PENDING; pac_script_ = string16(); state_ = STATE_WAIT_DHCP; callback_ = callback; wait_timer_.Start(FROM_HERE, ImplGetTimeout(), this, &DhcpProxyScriptAdapterFetcher::OnTimeout); scoped_refptr<DhcpQuery> dhcp_query(ImplCreateDhcpQuery()); base::WorkerPool::PostTaskAndReply( FROM_HERE, base::Bind( &DhcpProxyScriptAdapterFetcher::DhcpQuery::GetPacURLForAdapter, dhcp_query.get(), adapter_name), base::Bind( &DhcpProxyScriptAdapterFetcher::OnDhcpQueryDone, AsWeakPtr(), dhcp_query), true); } void DhcpProxyScriptAdapterFetcher::Cancel() { DCHECK(CalledOnValidThread()); callback_ = NULL; wait_timer_.Stop(); script_fetcher_.reset(); switch (state_) { case STATE_WAIT_DHCP: // Nothing to do here, we let the worker thread run to completion, // the task it posts back when it completes will check the state. break; case STATE_WAIT_URL: break; case STATE_START: case STATE_FINISH: case STATE_CANCEL: break; } if (state_ != STATE_FINISH) { result_ = ERR_ABORTED; state_ = STATE_CANCEL; } } bool DhcpProxyScriptAdapterFetcher::DidFinish() const { DCHECK(CalledOnValidThread()); return state_ == STATE_FINISH; } int DhcpProxyScriptAdapterFetcher::GetResult() const { DCHECK(CalledOnValidThread()); return result_; } string16 DhcpProxyScriptAdapterFetcher::GetPacScript() const { DCHECK(CalledOnValidThread()); return pac_script_; } GURL DhcpProxyScriptAdapterFetcher::GetPacURL() const { DCHECK(CalledOnValidThread()); return pac_url_; } DhcpProxyScriptAdapterFetcher::DhcpQuery::DhcpQuery() { } DhcpProxyScriptAdapterFetcher::DhcpQuery::~DhcpQuery() { } void DhcpProxyScriptAdapterFetcher::DhcpQuery::GetPacURLForAdapter( const std::string& adapter_name) { url_ = ImplGetPacURLFromDhcp(adapter_name); } const std::string& DhcpProxyScriptAdapterFetcher::DhcpQuery::url() const { return url_; } std::string DhcpProxyScriptAdapterFetcher::DhcpQuery::ImplGetPacURLFromDhcp( const std::string& adapter_name) { return DhcpProxyScriptAdapterFetcher::GetPacURLFromDhcp(adapter_name); } void DhcpProxyScriptAdapterFetcher::OnDhcpQueryDone( scoped_refptr<DhcpQuery> dhcp_query) { DCHECK(CalledOnValidThread()); // Because we can't cancel the call to the Win32 API, we can expect // it to finish while we are in a few different states. The expected // one is WAIT_DHCP, but it could be in CANCEL if Cancel() was called, // or FINISH if timeout occurred. DCHECK(state_ == STATE_WAIT_DHCP || state_ == STATE_CANCEL || state_ == STATE_FINISH); if (state_ != STATE_WAIT_DHCP) return; wait_timer_.Stop(); pac_url_ = GURL(dhcp_query->url()); if (pac_url_.is_empty() || !pac_url_.is_valid()) { result_ = ERR_PAC_NOT_IN_DHCP; TransitionToFinish(); } else { state_ = STATE_WAIT_URL; script_fetcher_.reset(ImplCreateScriptFetcher()); script_fetcher_->Fetch(pac_url_, &pac_script_, &script_fetcher_callback_); } } void DhcpProxyScriptAdapterFetcher::OnTimeout() { DCHECK_EQ(state_, STATE_WAIT_DHCP); result_ = ERR_TIMED_OUT; TransitionToFinish(); } void DhcpProxyScriptAdapterFetcher::OnFetcherDone(int result) { DCHECK(CalledOnValidThread()); DCHECK(state_ == STATE_WAIT_URL || state_ == STATE_CANCEL); if (state_ == STATE_CANCEL) return; // At this point, pac_script_ has already been written to. script_fetcher_.reset(); result_ = result; TransitionToFinish(); } void DhcpProxyScriptAdapterFetcher::TransitionToFinish() { DCHECK(state_ == STATE_WAIT_DHCP || state_ == STATE_WAIT_URL); state_ = STATE_FINISH; OldCompletionCallback* callback = callback_; callback_ = NULL; // Be careful not to touch any member state after this, as the client // may delete us during this callback. callback->Run(result_); } DhcpProxyScriptAdapterFetcher::State DhcpProxyScriptAdapterFetcher::state() const { return state_; } ProxyScriptFetcher* DhcpProxyScriptAdapterFetcher::ImplCreateScriptFetcher() { return new ProxyScriptFetcherImpl(url_request_context_); } DhcpProxyScriptAdapterFetcher::DhcpQuery* DhcpProxyScriptAdapterFetcher::ImplCreateDhcpQuery() { return new DhcpQuery(); } base::TimeDelta DhcpProxyScriptAdapterFetcher::ImplGetTimeout() const { return base::TimeDelta::FromMilliseconds(kTimeoutMs); } // static std::string DhcpProxyScriptAdapterFetcher::GetPacURLFromDhcp( const std::string& adapter_name) { EnsureDhcpcsvcInit(); std::wstring adapter_name_wide = base::SysMultiByteToWide(adapter_name, CP_ACP); DHCPCAPI_PARAMS_ARRAY send_params = { 0, NULL }; BYTE option_data[] = { 1, 252 }; DHCPCAPI_PARAMS wpad_params = { 0 }; wpad_params.OptionId = 252; wpad_params.IsVendor = FALSE; // Surprising, but intentional. DHCPCAPI_PARAMS_ARRAY request_params = { 0 }; request_params.nParams = 1; request_params.Params = &wpad_params; // The maximum message size is typically 4096 bytes on Windows per // http://support.microsoft.com/kb/321592 DWORD result_buffer_size = 4096; scoped_ptr_malloc<BYTE> result_buffer; int retry_count = 0; DWORD res = NO_ERROR; do { result_buffer.reset(reinterpret_cast<BYTE*>(malloc(result_buffer_size))); // Note that while the DHCPCAPI_REQUEST_SYNCHRONOUS flag seems to indicate // there might be an asynchronous mode, there seems to be (at least in // terms of well-documented use of this API) only a synchronous mode, with // an optional "async notifications later if the option changes" mode. // Even IE9, which we hope to emulate as IE is the most widely deployed // previous implementation of the DHCP aspect of WPAD and the only one // on Windows (Konqueror is the other, on Linux), uses this API with the // synchronous flag. There seem to be several Microsoft Knowledge Base // articles about calls to this function failing when other flags are used // (e.g. http://support.microsoft.com/kb/885270) so we won't take any // chances on non-standard, poorly documented usage. res = ::DhcpRequestParams(DHCPCAPI_REQUEST_SYNCHRONOUS, NULL, const_cast<LPWSTR>(adapter_name_wide.c_str()), NULL, send_params, request_params, result_buffer.get(), &result_buffer_size, NULL); ++retry_count; } while (res == ERROR_MORE_DATA && retry_count <= 3); if (res != NO_ERROR) { LOG(INFO) << "Error fetching PAC URL from DHCP: " << res; UMA_HISTOGRAM_COUNTS("Net.DhcpWpadUnhandledDhcpError", 1); } else if (wpad_params.nBytesData) { // The result should be ASCII, not wide character. DCHECK_EQ(strlen(reinterpret_cast<const char*>(wpad_params.Data)) + 1, wpad_params.nBytesData); // Return only up to the first null in case of embedded NULLs; if the // server is giving us back a buffer with embedded NULLs, something is // broken anyway. return std::string(reinterpret_cast<const char *>(wpad_params.Data)); } return ""; } } // namespace net <commit_msg>Add range check to allow for NULL to be counted as data or not by DHCP server.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy/dhcp_proxy_script_adapter_fetcher_win.h" #include "base/bind.h" #include "base/message_loop_proxy.h" #include "base/metrics/histogram.h" #include "base/sys_string_conversions.h" #include "base/threading/worker_pool.h" #include "base/time.h" #include "net/base/net_errors.h" #include "net/proxy/dhcpcsvc_init_win.h" #include "net/proxy/proxy_script_fetcher_impl.h" #include "net/url_request/url_request_context.h" #include <windows.h> #include <winsock2.h> #include <dhcpcsdk.h> #pragma comment(lib, "dhcpcsvc.lib") namespace { // Maximum amount of time to wait for response from the Win32 DHCP API. const int kTimeoutMs = 2000; } // namespace namespace net { DhcpProxyScriptAdapterFetcher::DhcpProxyScriptAdapterFetcher( URLRequestContext* url_request_context) : state_(STATE_START), result_(ERR_IO_PENDING), callback_(NULL), ALLOW_THIS_IN_INITIALIZER_LIST( script_fetcher_callback_( this, &DhcpProxyScriptAdapterFetcher::OnFetcherDone)), url_request_context_(url_request_context) { } DhcpProxyScriptAdapterFetcher::~DhcpProxyScriptAdapterFetcher() { Cancel(); // The WeakPtr we passed to the worker thread may be destroyed on the // worker thread. This detaches any outstanding WeakPtr state from // the current thread. base::SupportsWeakPtr<DhcpProxyScriptAdapterFetcher>::DetachFromThread(); } void DhcpProxyScriptAdapterFetcher::Fetch( const std::string& adapter_name, OldCompletionCallback* callback) { DCHECK(CalledOnValidThread()); DCHECK_EQ(state_, STATE_START); result_ = ERR_IO_PENDING; pac_script_ = string16(); state_ = STATE_WAIT_DHCP; callback_ = callback; wait_timer_.Start(FROM_HERE, ImplGetTimeout(), this, &DhcpProxyScriptAdapterFetcher::OnTimeout); scoped_refptr<DhcpQuery> dhcp_query(ImplCreateDhcpQuery()); base::WorkerPool::PostTaskAndReply( FROM_HERE, base::Bind( &DhcpProxyScriptAdapterFetcher::DhcpQuery::GetPacURLForAdapter, dhcp_query.get(), adapter_name), base::Bind( &DhcpProxyScriptAdapterFetcher::OnDhcpQueryDone, AsWeakPtr(), dhcp_query), true); } void DhcpProxyScriptAdapterFetcher::Cancel() { DCHECK(CalledOnValidThread()); callback_ = NULL; wait_timer_.Stop(); script_fetcher_.reset(); switch (state_) { case STATE_WAIT_DHCP: // Nothing to do here, we let the worker thread run to completion, // the task it posts back when it completes will check the state. break; case STATE_WAIT_URL: break; case STATE_START: case STATE_FINISH: case STATE_CANCEL: break; } if (state_ != STATE_FINISH) { result_ = ERR_ABORTED; state_ = STATE_CANCEL; } } bool DhcpProxyScriptAdapterFetcher::DidFinish() const { DCHECK(CalledOnValidThread()); return state_ == STATE_FINISH; } int DhcpProxyScriptAdapterFetcher::GetResult() const { DCHECK(CalledOnValidThread()); return result_; } string16 DhcpProxyScriptAdapterFetcher::GetPacScript() const { DCHECK(CalledOnValidThread()); return pac_script_; } GURL DhcpProxyScriptAdapterFetcher::GetPacURL() const { DCHECK(CalledOnValidThread()); return pac_url_; } DhcpProxyScriptAdapterFetcher::DhcpQuery::DhcpQuery() { } DhcpProxyScriptAdapterFetcher::DhcpQuery::~DhcpQuery() { } void DhcpProxyScriptAdapterFetcher::DhcpQuery::GetPacURLForAdapter( const std::string& adapter_name) { url_ = ImplGetPacURLFromDhcp(adapter_name); } const std::string& DhcpProxyScriptAdapterFetcher::DhcpQuery::url() const { return url_; } std::string DhcpProxyScriptAdapterFetcher::DhcpQuery::ImplGetPacURLFromDhcp( const std::string& adapter_name) { return DhcpProxyScriptAdapterFetcher::GetPacURLFromDhcp(adapter_name); } void DhcpProxyScriptAdapterFetcher::OnDhcpQueryDone( scoped_refptr<DhcpQuery> dhcp_query) { DCHECK(CalledOnValidThread()); // Because we can't cancel the call to the Win32 API, we can expect // it to finish while we are in a few different states. The expected // one is WAIT_DHCP, but it could be in CANCEL if Cancel() was called, // or FINISH if timeout occurred. DCHECK(state_ == STATE_WAIT_DHCP || state_ == STATE_CANCEL || state_ == STATE_FINISH); if (state_ != STATE_WAIT_DHCP) return; wait_timer_.Stop(); pac_url_ = GURL(dhcp_query->url()); if (pac_url_.is_empty() || !pac_url_.is_valid()) { result_ = ERR_PAC_NOT_IN_DHCP; TransitionToFinish(); } else { state_ = STATE_WAIT_URL; script_fetcher_.reset(ImplCreateScriptFetcher()); script_fetcher_->Fetch(pac_url_, &pac_script_, &script_fetcher_callback_); } } void DhcpProxyScriptAdapterFetcher::OnTimeout() { DCHECK_EQ(state_, STATE_WAIT_DHCP); result_ = ERR_TIMED_OUT; TransitionToFinish(); } void DhcpProxyScriptAdapterFetcher::OnFetcherDone(int result) { DCHECK(CalledOnValidThread()); DCHECK(state_ == STATE_WAIT_URL || state_ == STATE_CANCEL); if (state_ == STATE_CANCEL) return; // At this point, pac_script_ has already been written to. script_fetcher_.reset(); result_ = result; TransitionToFinish(); } void DhcpProxyScriptAdapterFetcher::TransitionToFinish() { DCHECK(state_ == STATE_WAIT_DHCP || state_ == STATE_WAIT_URL); state_ = STATE_FINISH; OldCompletionCallback* callback = callback_; callback_ = NULL; // Be careful not to touch any member state after this, as the client // may delete us during this callback. callback->Run(result_); } DhcpProxyScriptAdapterFetcher::State DhcpProxyScriptAdapterFetcher::state() const { return state_; } ProxyScriptFetcher* DhcpProxyScriptAdapterFetcher::ImplCreateScriptFetcher() { return new ProxyScriptFetcherImpl(url_request_context_); } DhcpProxyScriptAdapterFetcher::DhcpQuery* DhcpProxyScriptAdapterFetcher::ImplCreateDhcpQuery() { return new DhcpQuery(); } base::TimeDelta DhcpProxyScriptAdapterFetcher::ImplGetTimeout() const { return base::TimeDelta::FromMilliseconds(kTimeoutMs); } // static std::string DhcpProxyScriptAdapterFetcher::GetPacURLFromDhcp( const std::string& adapter_name) { EnsureDhcpcsvcInit(); std::wstring adapter_name_wide = base::SysMultiByteToWide(adapter_name, CP_ACP); DHCPCAPI_PARAMS_ARRAY send_params = { 0, NULL }; BYTE option_data[] = { 1, 252 }; DHCPCAPI_PARAMS wpad_params = { 0 }; wpad_params.OptionId = 252; wpad_params.IsVendor = FALSE; // Surprising, but intentional. DHCPCAPI_PARAMS_ARRAY request_params = { 0 }; request_params.nParams = 1; request_params.Params = &wpad_params; // The maximum message size is typically 4096 bytes on Windows per // http://support.microsoft.com/kb/321592 DWORD result_buffer_size = 4096; scoped_ptr_malloc<BYTE> result_buffer; int retry_count = 0; DWORD res = NO_ERROR; do { result_buffer.reset(reinterpret_cast<BYTE*>(malloc(result_buffer_size))); // Note that while the DHCPCAPI_REQUEST_SYNCHRONOUS flag seems to indicate // there might be an asynchronous mode, there seems to be (at least in // terms of well-documented use of this API) only a synchronous mode, with // an optional "async notifications later if the option changes" mode. // Even IE9, which we hope to emulate as IE is the most widely deployed // previous implementation of the DHCP aspect of WPAD and the only one // on Windows (Konqueror is the other, on Linux), uses this API with the // synchronous flag. There seem to be several Microsoft Knowledge Base // articles about calls to this function failing when other flags are used // (e.g. http://support.microsoft.com/kb/885270) so we won't take any // chances on non-standard, poorly documented usage. res = ::DhcpRequestParams(DHCPCAPI_REQUEST_SYNCHRONOUS, NULL, const_cast<LPWSTR>(adapter_name_wide.c_str()), NULL, send_params, request_params, result_buffer.get(), &result_buffer_size, NULL); ++retry_count; } while (res == ERROR_MORE_DATA && retry_count <= 3); if (res != NO_ERROR) { LOG(INFO) << "Error fetching PAC URL from DHCP: " << res; UMA_HISTOGRAM_COUNTS("Net.DhcpWpadUnhandledDhcpError", 1); } else if (wpad_params.nBytesData) { #ifndef NDEBUG // The result should be ASCII, not wide character. Some DHCP // servers appear to count the trailing NULL in nBytesData, others // do not. size_t count_without_null = strlen(reinterpret_cast<const char*>(wpad_params.Data)); DCHECK(count_without_null == wpad_params.nBytesData || count_without_null + 1 == wpad_params.nBytesData); #endif // Belt and suspenders: First, ensure we NULL-terminate after // nBytesData; this is the inner constructor with nBytesData as a // parameter. Then, return only up to the first null in case of // embedded NULLs; this is the outer constructor that takes the // result of c_str() on the inner. If the server is giving us // back a buffer with embedded NULLs, something is broken anyway. return std::string( std::string(reinterpret_cast<const char *>(wpad_params.Data), wpad_params.nBytesData).c_str()); } return ""; } } // namespace net <|endoftext|>
<commit_before>#pragma once // `krbn::session_monitor::components_manager` can be used safely in a multi-threaded environment. #include "monitor/version_monitor.hpp" #include "receiver.hpp" #include "session_monitor_receiver_client.hpp" #include <pqrs/osx/session.hpp> namespace krbn { namespace session_monitor { class components_manager final : public pqrs::dispatcher::extra::dispatcher_client { public: components_manager(const components_manager&) = delete; components_manager(std::weak_ptr<version_monitor> weak_version_monitor) : dispatcher_client(), on_console_(false) { // ---------------------------------------- // client_ client_ = std::make_unique<session_monitor_receiver_client>(); client_->connected.connect([this] { send_to_receiver(); }); // ---------------------------------------- // receiver_ receiver_ = std::make_unique<receiver>(); receiver_->bound.connect([this] { send_to_receiver(); }); // ---------------------------------------- // session_monitor_ session_monitor_ = std::make_unique<pqrs::osx::session::monitor>(weak_dispatcher_); session_monitor_->on_console_changed.connect([this](auto&& on_console) { logger::get_logger()->info("on_console_changed: {0}", on_console); on_console_ = on_console; send_to_receiver(); }); } virtual ~components_manager(void) { detach_from_dispatcher([this] { session_monitor_ = nullptr; receiver_ = nullptr; client_ = nullptr; }); } void async_start(void) { enqueue_to_dispatcher([this] { if (client_) { client_->async_start(); } if (receiver_) { receiver_->async_start(); } if (session_monitor_) { session_monitor_->async_start(std::chrono::milliseconds(3000)); } }); } private: void send_to_receiver(void) const { if (client_) { client_->async_console_user_id_changed(getuid(), on_console_); } } bool on_console_; std::unique_ptr<session_monitor_receiver_client> client_; std::unique_ptr<receiver> receiver_; std::unique_ptr<pqrs::osx::session::monitor> session_monitor_; }; } // namespace session_monitor } // namespace krbn <commit_msg>add send_timer_ to session_monitor<commit_after>#pragma once // `krbn::session_monitor::components_manager` can be used safely in a multi-threaded environment. #include "monitor/version_monitor.hpp" #include "receiver.hpp" #include "session_monitor_receiver_client.hpp" #include <pqrs/osx/session.hpp> namespace krbn { namespace session_monitor { class components_manager final : public pqrs::dispatcher::extra::dispatcher_client { public: components_manager(const components_manager&) = delete; components_manager(std::weak_ptr<version_monitor> weak_version_monitor) : dispatcher_client(), on_console_(false), send_timer_(*this) { // ---------------------------------------- // client_ client_ = std::make_unique<session_monitor_receiver_client>(); client_->connected.connect([this] { send_to_receiver(); }); // ---------------------------------------- // receiver_ receiver_ = std::make_unique<receiver>(); receiver_->bound.connect([this] { send_to_receiver(); }); // ---------------------------------------- // session_monitor_ session_monitor_ = std::make_unique<pqrs::osx::session::monitor>(weak_dispatcher_); session_monitor_->on_console_changed.connect([this](auto&& on_console) { logger::get_logger()->info("on_console_changed: {0}", on_console); on_console_ = on_console; send_to_receiver(); }); } virtual ~components_manager(void) { detach_from_dispatcher([this] { send_timer_.stop(); session_monitor_ = nullptr; receiver_ = nullptr; client_ = nullptr; }); } void async_start(void) { enqueue_to_dispatcher([this] { if (client_) { client_->async_start(); } if (receiver_) { receiver_->async_start(); } if (session_monitor_) { session_monitor_->async_start(std::chrono::milliseconds(3000)); } // Call send_to_receiver periodically to ensure `grabber` receive the event. send_timer_.start( [this] { send_to_receiver(); }, std::chrono::milliseconds(3000)); }); } private: void send_to_receiver(void) const { if (client_) { client_->async_console_user_id_changed(getuid(), on_console_); } } bool on_console_; std::unique_ptr<session_monitor_receiver_client> client_; std::unique_ptr<receiver> receiver_; std::unique_ptr<pqrs::osx::session::monitor> session_monitor_; pqrs::dispatcher::extra::timer send_timer_; }; } // namespace session_monitor } // namespace krbn <|endoftext|>
<commit_before>// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "DecodeStep_Translation.h" #include "PhraseDictionary.h" #include "TranslationOption.h" #include "TranslationOptionCollection.h" #include "PartialTranslOptColl.h" #include "FactorCollection.h" TranslationDecodeStep::TranslationDecodeStep(PhraseDictionaryBase* dict, const DecodeStep* prev) : DecodeStep(dict, prev) { } const PhraseDictionaryBase &TranslationDecodeStep::GetPhraseDictionary() const { return *static_cast<const PhraseDictionaryBase*>(m_ptr); } TranslationOption *TranslationDecodeStep::MergeTranslation(const TranslationOption& oldTO, const TargetPhrase &targetPhrase) const { if (IsFilteringStep()) { if (!oldTO.IsCompatible(targetPhrase, m_conflictFactors)) return 0; } TranslationOption *newTransOpt = new TranslationOption(oldTO); newTransOpt->MergeNewFeatures(targetPhrase, targetPhrase.GetScoreBreakdown(), m_newOutputFactors); return newTransOpt; } void TranslationDecodeStep::Process(const TranslationOption &inputPartialTranslOpt , const DecodeStep &decodeStep , PartialTranslOptColl &outputPartialTranslOptColl , FactorCollection &factorCollection , TranslationOptionCollection *toc , bool observeTableLimit) const { //TRACE_ERR(inputPartialTranslOpt << endl); if (inputPartialTranslOpt.GetTargetPhrase().GetSize() == 0) { // word deletion outputPartialTranslOptColl.Add(new TranslationOption(inputPartialTranslOpt)); return; } // normal trans step const WordsRange &sourceWordsRange = inputPartialTranslOpt.GetSourceWordsRange(); const PhraseDictionaryBase &phraseDictionary = decodeStep.GetPhraseDictionary(); const size_t currSize = inputPartialTranslOpt.GetTargetPhrase().GetSize(); const size_t tableLimit = phraseDictionary.GetTableLimit(); const TargetPhraseCollection *phraseColl= phraseDictionary.GetTargetPhraseCollection(toc->GetSource(),sourceWordsRange); if (phraseColl != NULL) { TargetPhraseCollection::const_iterator iterTargetPhrase, iterEnd; iterEnd = (observeTableLimit && phraseColl->GetSize() > tableLimit) ? phraseColl->begin() + tableLimit + 1 : phraseColl->end(); for (iterTargetPhrase = phraseColl->begin(); iterTargetPhrase != iterEnd; ++iterTargetPhrase) { const TargetPhrase& targetPhrase = **iterTargetPhrase; // skip if the if (targetPhrase.GetSize() != currSize) continue; TranslationOption *newTransOpt = MergeTranslation(inputPartialTranslOpt, targetPhrase); if (newTransOpt != NULL) { outputPartialTranslOptColl.Add( newTransOpt ); } } } else if (sourceWordsRange.GetWordsCount() == 1) { // unknown handler //toc->ProcessUnknownWord(sourceWordsRange.GetStartPos(), factorCollection); } } <commit_msg>getting ready to implement new phrase dictionary pruning<commit_after>// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "DecodeStep_Translation.h" #include "PhraseDictionary.h" #include "TranslationOption.h" #include "TranslationOptionCollection.h" #include "PartialTranslOptColl.h" #include "FactorCollection.h" TranslationDecodeStep::TranslationDecodeStep(PhraseDictionaryBase* dict, const DecodeStep* prev) : DecodeStep(dict, prev) { } const PhraseDictionaryBase &TranslationDecodeStep::GetPhraseDictionary() const { return *static_cast<const PhraseDictionaryBase*>(m_ptr); } TranslationOption *TranslationDecodeStep::MergeTranslation(const TranslationOption& oldTO, const TargetPhrase &targetPhrase) const { if (IsFilteringStep()) { if (!oldTO.IsCompatible(targetPhrase, m_conflictFactors)) return 0; } TranslationOption *newTransOpt = new TranslationOption(oldTO); newTransOpt->MergeNewFeatures(targetPhrase, targetPhrase.GetScoreBreakdown(), m_newOutputFactors); return newTransOpt; } void TranslationDecodeStep::Process(const TranslationOption &inputPartialTranslOpt , const DecodeStep &decodeStep , PartialTranslOptColl &outputPartialTranslOptColl , FactorCollection &factorCollection , TranslationOptionCollection *toc , bool observeTableLimit) const { //TRACE_ERR(inputPartialTranslOpt << endl); if (inputPartialTranslOpt.GetTargetPhrase().GetSize() == 0) { // word deletion outputPartialTranslOptColl.Add(new TranslationOption(inputPartialTranslOpt)); return; } // normal trans step const WordsRange &sourceWordsRange = inputPartialTranslOpt.GetSourceWordsRange(); const PhraseDictionaryBase &phraseDictionary = decodeStep.GetPhraseDictionary(); const size_t currSize = inputPartialTranslOpt.GetTargetPhrase().GetSize(); const size_t tableLimit = phraseDictionary.GetTableLimit(); const TargetPhraseCollection *phraseColl= phraseDictionary.GetTargetPhraseCollection(toc->GetSource(),sourceWordsRange); if (phraseColl != NULL) { TargetPhraseCollection::const_iterator iterTargetPhrase, iterEnd; //iterEnd = (observeTableLimit && phraseColl->GetSize() > tableLimit) ? phraseColl->begin() + tableLimit + 1 : phraseColl->end(); iterEnd = phraseColl->end(); for (iterTargetPhrase = phraseColl->begin(); iterTargetPhrase != iterEnd; ++iterTargetPhrase) { const TargetPhrase& targetPhrase = **iterTargetPhrase; // skip if the if (targetPhrase.GetSize() != currSize) continue; TranslationOption *newTransOpt = MergeTranslation(inputPartialTranslOpt, targetPhrase); if (newTransOpt != NULL) { outputPartialTranslOptColl.Add( newTransOpt ); } } } else if (sourceWordsRange.GetWordsCount() == 1) { // unknown handler //toc->ProcessUnknownWord(sourceWordsRange.GetStartPos(), factorCollection); } } <|endoftext|>
<commit_before>// 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 "net/base/platform_mime_util.h" #include <string> #include "base/logging.h" #include "build/build_config.h" #if defined(OS_ANDROID) #include "net/android/network_library.h" #else #include "base/nix/mime_util_xdg.h" #endif namespace net { #if defined(OS_ANDROID) bool PlatformMimeUtil::GetPlatformMimeTypeFromExtension( const FilePath::StringType& ext, std::string* result) const { // TODO(jingzhao): Recover the original implementation once we support JNI. #if 0 return android::GetMimeTypeFromExtension(ext, result); #else NOTIMPLEMENTED(); return false; #endif } #else bool PlatformMimeUtil::GetPlatformMimeTypeFromExtension( const FilePath::StringType& ext, std::string* result) const { // TODO(thestig): This is a temporary hack until we can fix this // properly in test shell / webkit. // We have to play dumb and not return application/x-perl here // to make the reload-subframe-object layout test happy. if (ext == "pl") return false; FilePath dummy_path("foo." + ext); std::string out = base::nix::GetFileMimeType(dummy_path); // GetFileMimeType likes to return application/octet-stream // for everything it doesn't know - ignore that. if (out == "application/octet-stream" || out.empty()) return false; // GetFileMimeType returns image/x-ico because that's what's in the XDG // mime database. That database is the merger of the Gnome and KDE mime // databases. Apparently someone working on KDE in 2001 decided .ico // resolves to image/x-ico, whereas the rest of the world uses image/x-icon. // FWIW, image/vnd.microsoft.icon is the official IANA assignment. if (out == "image/x-ico") out = "image/x-icon"; *result = out; return true; } #endif // defined(OS_ANDROID) struct MimeToExt { const char* mime_type; const char* ext; }; const struct MimeToExt mime_type_ext_map[] = { {"application/pdf", "pdf"}, {"application/x-tar", "tar"}, {"audio/mpeg", "mp3"}, {"image/gif", "gif"}, {"image/jpeg", "jpg"}, {"image/png", "png"}, {"text/html", "html"}, {"video/mp4", "mp4"}, {"video/mpeg", "mpg"}, {"text/plain", "txt"}, {"text/x-sh", "sh"}, }; bool PlatformMimeUtil::GetPreferredExtensionForMimeType( const std::string& mime_type, FilePath::StringType* ext) const { for (size_t x = 0; x < (sizeof(mime_type_ext_map) / sizeof(MimeToExt)); x++) { if (mime_type_ext_map[x].mime_type == mime_type) { *ext = mime_type_ext_map[x].ext; return true; } } // TODO(dhg): Fix this the right way by implementing what's said below. // Unlike GetPlatformMimeTypeFromExtension, this method doesn't have a // default list that it uses, but for now we are also returning false since // this doesn't really matter as much under Linux. // // If we wanted to do this properly, we would read the mime.cache file which // has a section where they assign a glob (*.gif) to a mimetype // (image/gif). We look up the "heaviest" glob for a certain mime type and // then then try to chop off "*.". return false; } void PlatformMimeUtil::GetPlatformExtensionsForMimeType( const std::string& mime_type, base::hash_set<FilePath::StringType>* extensions) const { FilePath::StringType ext; if (GetPreferredExtensionForMimeType(mime_type, &ext)) extensions->insert(ext); } } // namespace net <commit_msg>enable android GetMimeTypeFromExtention in mime_util<commit_after>// 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 "net/base/platform_mime_util.h" #include <string> #include "base/logging.h" #include "build/build_config.h" #if defined(OS_ANDROID) #include "net/android/network_library.h" #else #include "base/nix/mime_util_xdg.h" #endif namespace net { #if defined(OS_ANDROID) bool PlatformMimeUtil::GetPlatformMimeTypeFromExtension( const FilePath::StringType& ext, std::string* result) const { return android::GetMimeTypeFromExtension(ext, result); } #else bool PlatformMimeUtil::GetPlatformMimeTypeFromExtension( const FilePath::StringType& ext, std::string* result) const { // TODO(thestig): This is a temporary hack until we can fix this // properly in test shell / webkit. // We have to play dumb and not return application/x-perl here // to make the reload-subframe-object layout test happy. if (ext == "pl") return false; FilePath dummy_path("foo." + ext); std::string out = base::nix::GetFileMimeType(dummy_path); // GetFileMimeType likes to return application/octet-stream // for everything it doesn't know - ignore that. if (out == "application/octet-stream" || out.empty()) return false; // GetFileMimeType returns image/x-ico because that's what's in the XDG // mime database. That database is the merger of the Gnome and KDE mime // databases. Apparently someone working on KDE in 2001 decided .ico // resolves to image/x-ico, whereas the rest of the world uses image/x-icon. // FWIW, image/vnd.microsoft.icon is the official IANA assignment. if (out == "image/x-ico") out = "image/x-icon"; *result = out; return true; } #endif // defined(OS_ANDROID) struct MimeToExt { const char* mime_type; const char* ext; }; const struct MimeToExt mime_type_ext_map[] = { {"application/pdf", "pdf"}, {"application/x-tar", "tar"}, {"audio/mpeg", "mp3"}, {"image/gif", "gif"}, {"image/jpeg", "jpg"}, {"image/png", "png"}, {"text/html", "html"}, {"video/mp4", "mp4"}, {"video/mpeg", "mpg"}, {"text/plain", "txt"}, {"text/x-sh", "sh"}, }; bool PlatformMimeUtil::GetPreferredExtensionForMimeType( const std::string& mime_type, FilePath::StringType* ext) const { for (size_t x = 0; x < (sizeof(mime_type_ext_map) / sizeof(MimeToExt)); x++) { if (mime_type_ext_map[x].mime_type == mime_type) { *ext = mime_type_ext_map[x].ext; return true; } } // TODO(dhg): Fix this the right way by implementing what's said below. // Unlike GetPlatformMimeTypeFromExtension, this method doesn't have a // default list that it uses, but for now we are also returning false since // this doesn't really matter as much under Linux. // // If we wanted to do this properly, we would read the mime.cache file which // has a section where they assign a glob (*.gif) to a mimetype // (image/gif). We look up the "heaviest" glob for a certain mime type and // then then try to chop off "*.". return false; } void PlatformMimeUtil::GetPlatformExtensionsForMimeType( const std::string& mime_type, base::hash_set<FilePath::StringType>* extensions) const { FilePath::StringType ext; if (GetPreferredExtensionForMimeType(mime_type, &ext)) extensions->insert(ext); } } // namespace net <|endoftext|>
<commit_before>// $Id$ // Author: Sergey Linev 8/01/2018 /************************************************************************* * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "THttpLongPollEngine.h" #include "THttpCallArg.h" #include "TSystem.h" #include <ROOT/TLogger.hxx> #include <cstring> #include <cstdlib> ////////////////////////////////////////////////////////////////////////// // // // THttpLongPollEngine // // // // Emulation of websocket with long poll requests // // Allows to send data from server to client without explicit request // // // ////////////////////////////////////////////////////////////////////////// const char *THttpLongPollEngine::gLongPollNope = "<<nope>>"; ////////////////////////////////////////////////////////////////////////// /// constructor THttpLongPollEngine::THttpLongPollEngine(std::shared_ptr<THttpCallArg> arg, bool raw) : THttpWSEngine(arg), fRaw(raw) { arg->SetWSId(GetId()); } ////////////////////////////////////////////////////////////////////////// /// returns ID of the engine, created from this pointer UInt_t THttpLongPollEngine::GetId() const { const void *ptr = (const void *)this; return TString::Hash((void *)&ptr, sizeof(void *)); } ////////////////////////////////////////////////////////////////////////// /// clear request, waiting for next portion of data void THttpLongPollEngine::ClearHandle() { if (fPoll) { fPoll->Set404(); fPoll->NotifyCondition(); fPoll.reset(); } } ////////////////////////////////////////////////////////////////////////// /// Create raw buffer which should be send as reply /// For the raw mode all information must be send via binary response std::string THttpLongPollEngine::MakeBuffer(const void *buf, int len, const char *hdr) { std::string res; if (!fRaw) { res.resize(len); memcpy((void *) res.data(), buf, len); return res; } int hdrlen = hdr ? strlen(hdr) : 0; std::string hdrstr = "bin:"; hdrstr.append(std::to_string(hdrlen)); while ((hdrstr.length() + 1 + hdrlen) % 8 != 0) hdrstr.append(" "); hdrstr.append(":"); if (hdrlen > 0) hdrstr.append(hdr); res.resize(hdrstr.length() + len); memcpy((void *)res.data(), hdrstr.data(), hdrstr.length()); memcpy((char *)res.data() + hdrstr.length(), buf, len); return res; } ////////////////////////////////////////////////////////////////////////// /// Send binary data via connection - not supported void THttpLongPollEngine::Send(const void *buf, int len) { std::string buf2 = MakeBuffer(buf, len); if (fPoll) { fPoll->SetBinaryContent(std::move(buf2)); fPoll->NotifyCondition(); fPoll.reset(); } else { fQueue.emplace_back(true, std::move(buf2)); if (fQueue.size() > 100) R__ERROR_HERE("http") << "Too many send operations " << fQueue.size() << " in the queue, check algorithms"; } } ////////////////////////////////////////////////////////////////////////// /// Send binary data with text header via connection - not supported void THttpLongPollEngine::SendHeader(const char *hdr, const void *buf, int len) { std::string buf2 = MakeBuffer(buf, len, hdr); if (fPoll) { fPoll->SetBinaryContent(std::move(buf2)); if (!fRaw) fPoll->SetExtraHeader("LongpollHeader", hdr); fPoll->NotifyCondition(); fPoll.reset(); } else { fQueue.emplace_back(true, std::move(buf2), hdr); if (fQueue.size() > 100) R__ERROR_HERE("http") << "Too many send operations " << fQueue.size() << " in the queue, check algorithms"; } } ////////////////////////////////////////////////////////////////////////// /// Send const char data /// Either do it immediately or keep in internal buffer void THttpLongPollEngine::SendCharStar(const char *buf) { std::string sendbuf(fRaw ? "txt:" : ""); sendbuf.append(buf); if (fPoll) { if (fRaw) fPoll->SetBinaryContent(std::move(sendbuf)); else fPoll->SetTextContent(std::move(sendbuf)); fPoll->NotifyCondition(); fPoll.reset(); } else { fQueue.emplace_back(false, std::move(sendbuf)); if (fQueue.size() > 100) R__ERROR_HERE("http") << "Too many send operations " << fQueue.size() << " in the queue, check algorithms"; } } ////////////////////////////////////////////////////////////////////////////// /// Preview data for given socket /// function called in the user code before processing correspondent websocket data /// returns kTRUE when user should ignore such http request - it is for internal use Bool_t THttpLongPollEngine::PreviewData(std::shared_ptr<THttpCallArg> &arg) { if (!strstr(arg->GetQuery(), "&dummy")) { // this is normal request, deliver and process it as any other // put dummy content, it can be overwritten in the future arg->SetTextContent(std::string(gLongPollNope)); return kFALSE; } if (arg == fPoll) R__FATAL_HERE("http") << "Same object once again"; if (fPoll) { R__ERROR_HERE("http") << "Get next dummy request when previous not completed"; // if there are pending request, reply it immediately if (fRaw) fPoll->SetBinaryContent(std::string("txt:") + gLongPollNope); else fPoll->SetTextContent(std::string(gLongPollNope)); // normally should never happen fPoll->NotifyCondition(); // inform http server that request is processed fPoll.reset(); } if (fQueue.size() > 0) { QueueItem &item = fQueue.front(); if (item.fBinary) { arg->SetBinaryContent(std::move(item.fData)); if (!fRaw && !item.fHdr.empty()) arg->SetExtraHeader("LongpollHeader", item.fHdr.c_str()); } else { arg->SetTextContent(std::move(item.fData)); } fQueue.erase(fQueue.begin()); } else { arg->SetPostponed(); // mark http request as pending, http server should wait for notification fPoll = arg; // keep reference on polling request } // if arguments has "&dummy" string, user should not process it return kTRUE; } ////////////////////////////////////////////////////////////////////////////// /// Normally requests from client does not replied directly /// Therefore one can use it to send data with it void THttpLongPollEngine::PostProcess(std::shared_ptr<THttpCallArg> &arg) { if (arg->IsText() && (arg->GetContentLength() == (Long_t)strlen(gLongPollNope)) && (strcmp((const char *)arg->GetContent(), gLongPollNope) == 0)) { if (fQueue.size() > 0) { QueueItem &item = fQueue.front(); if (item.fBinary) { arg->SetBinaryContent(std::move(item.fData)); if (!fRaw && !item.fHdr.empty()) arg->SetExtraHeader("LongpollHeader", item.fHdr.c_str()); } else { arg->SetTextContent(std::move(item.fData)); } fQueue.erase(fQueue.begin()); } else if (fRaw) { arg->SetContent(std::string("txt:") + gLongPollNope); } } } <commit_msg>http: do not use ROOT/TLogger in normal code<commit_after>// $Id$ // Author: Sergey Linev 8/01/2018 /************************************************************************* * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "THttpLongPollEngine.h" #include "THttpCallArg.h" #include "TSystem.h" #include <cstring> #include <cstdlib> ////////////////////////////////////////////////////////////////////////// // // // THttpLongPollEngine // // // // Emulation of websocket with long poll requests // // Allows to send data from server to client without explicit request // // // ////////////////////////////////////////////////////////////////////////// const char *THttpLongPollEngine::gLongPollNope = "<<nope>>"; ////////////////////////////////////////////////////////////////////////// /// constructor THttpLongPollEngine::THttpLongPollEngine(std::shared_ptr<THttpCallArg> arg, bool raw) : THttpWSEngine(arg), fRaw(raw) { arg->SetWSId(GetId()); } ////////////////////////////////////////////////////////////////////////// /// returns ID of the engine, created from this pointer UInt_t THttpLongPollEngine::GetId() const { const void *ptr = (const void *)this; return TString::Hash((void *)&ptr, sizeof(void *)); } ////////////////////////////////////////////////////////////////////////// /// clear request, waiting for next portion of data void THttpLongPollEngine::ClearHandle() { if (fPoll) { fPoll->Set404(); fPoll->NotifyCondition(); fPoll.reset(); } } ////////////////////////////////////////////////////////////////////////// /// Create raw buffer which should be send as reply /// For the raw mode all information must be send via binary response std::string THttpLongPollEngine::MakeBuffer(const void *buf, int len, const char *hdr) { std::string res; if (!fRaw) { res.resize(len); memcpy((void *) res.data(), buf, len); return res; } int hdrlen = hdr ? strlen(hdr) : 0; std::string hdrstr = "bin:"; hdrstr.append(std::to_string(hdrlen)); while ((hdrstr.length() + 1 + hdrlen) % 8 != 0) hdrstr.append(" "); hdrstr.append(":"); if (hdrlen > 0) hdrstr.append(hdr); res.resize(hdrstr.length() + len); memcpy((void *)res.data(), hdrstr.data(), hdrstr.length()); memcpy((char *)res.data() + hdrstr.length(), buf, len); return res; } ////////////////////////////////////////////////////////////////////////// /// Send binary data via connection - not supported void THttpLongPollEngine::Send(const void *buf, int len) { std::string buf2 = MakeBuffer(buf, len); if (fPoll) { fPoll->SetBinaryContent(std::move(buf2)); fPoll->NotifyCondition(); fPoll.reset(); } else { fQueue.emplace_back(true, std::move(buf2)); if (fQueue.size() > 100) Error("Send", "Too many send operations %u in the queue, check algorithms", (unsigned) fQueue.size()); } } ////////////////////////////////////////////////////////////////////////// /// Send binary data with text header via connection - not supported void THttpLongPollEngine::SendHeader(const char *hdr, const void *buf, int len) { std::string buf2 = MakeBuffer(buf, len, hdr); if (fPoll) { fPoll->SetBinaryContent(std::move(buf2)); if (!fRaw) fPoll->SetExtraHeader("LongpollHeader", hdr); fPoll->NotifyCondition(); fPoll.reset(); } else { fQueue.emplace_back(true, std::move(buf2), hdr); if (fQueue.size() > 100) Error("SendHeader", "Too many send operations %u in the queue, check algorithms", (unsigned) fQueue.size()); } } ////////////////////////////////////////////////////////////////////////// /// Send const char data /// Either do it immediately or keep in internal buffer void THttpLongPollEngine::SendCharStar(const char *buf) { std::string sendbuf(fRaw ? "txt:" : ""); sendbuf.append(buf); if (fPoll) { if (fRaw) fPoll->SetBinaryContent(std::move(sendbuf)); else fPoll->SetTextContent(std::move(sendbuf)); fPoll->NotifyCondition(); fPoll.reset(); } else { fQueue.emplace_back(false, std::move(sendbuf)); if (fQueue.size() > 100) Error("SendCharStar", "Too many send operations %u in the queue, check algorithms", (unsigned) fQueue.size()); } } ////////////////////////////////////////////////////////////////////////////// /// Preview data for given socket /// function called in the user code before processing correspondent websocket data /// returns kTRUE when user should ignore such http request - it is for internal use Bool_t THttpLongPollEngine::PreviewData(std::shared_ptr<THttpCallArg> &arg) { if (!strstr(arg->GetQuery(), "&dummy")) { // this is normal request, deliver and process it as any other // put dummy content, it can be overwritten in the future arg->SetTextContent(std::string(gLongPollNope)); return kFALSE; } if (arg == fPoll) Fatal("PreviewData", "Submit same THttpCallArg object once again"); if (fPoll) { Error("PreviewData", "Get next dummy request when previous not completed"); // if there are pending request, reply it immediately if (fRaw) fPoll->SetBinaryContent(std::string("txt:") + gLongPollNope); else fPoll->SetTextContent(std::string(gLongPollNope)); // normally should never happen fPoll->NotifyCondition(); // inform http server that request is processed fPoll.reset(); } if (fQueue.size() > 0) { QueueItem &item = fQueue.front(); if (item.fBinary) { arg->SetBinaryContent(std::move(item.fData)); if (!fRaw && !item.fHdr.empty()) arg->SetExtraHeader("LongpollHeader", item.fHdr.c_str()); } else { arg->SetTextContent(std::move(item.fData)); } fQueue.erase(fQueue.begin()); } else { arg->SetPostponed(); // mark http request as pending, http server should wait for notification fPoll = arg; // keep reference on polling request } // if arguments has "&dummy" string, user should not process it return kTRUE; } ////////////////////////////////////////////////////////////////////////////// /// Normally requests from client does not replied directly /// Therefore one can use it to send data with it void THttpLongPollEngine::PostProcess(std::shared_ptr<THttpCallArg> &arg) { if (arg->IsText() && (arg->GetContentLength() == (Long_t)strlen(gLongPollNope)) && (strcmp((const char *)arg->GetContent(), gLongPollNope) == 0)) { if (fQueue.size() > 0) { QueueItem &item = fQueue.front(); if (item.fBinary) { arg->SetBinaryContent(std::move(item.fData)); if (!fRaw && !item.fHdr.empty()) arg->SetExtraHeader("LongpollHeader", item.fHdr.c_str()); } else { arg->SetTextContent(std::move(item.fData)); } fQueue.erase(fQueue.begin()); } else if (fRaw) { arg->SetContent(std::string("txt:") + gLongPollNope); } } } <|endoftext|>
<commit_before>/** * KQOAuth - An OAuth authentication library for Qt. * * Author: Johan Paul ([email protected]) * http://www.johanpaul.com * * KQOAuth 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 3 of the License, or * (at your option) any later version. * * KQOAuth 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 KQOAuth. If not, see <http://www.gnu.org/licenses/>. */ #include <QString> #include <QCryptographicHash> #include <QByteArray> #include <QtDebug> #include "kqoauthutils.h" QString KQOAuthUtils::hmac_sha1(const QString &message, const QString &key) { QByteArray keyBytes = key.toAscii(); int keyLength; // Lenght of key word const int blockSize = 64; // Both MD5 and SHA-1 have a block size of 64. keyLength = keyBytes.size(); // If key is longer than block size, we need to hash the key if(keyLength > blockSize) { QCryptographicHash hash(QCryptographicHash::Sha1); hash.addData(keyBytes); keyBytes = hash.result(); keyLength = keyBytes.size(); } /* http://tools.ietf.org/html/rfc2104 - (1) */ // Create the opad and ipad for the hash function. QByteArray ipad; QByteArray opad; ipad.append(keyBytes.constData()); opad.append(keyBytes.constData()); /* http://tools.ietf.org/html/rfc2104 - (2) & (5) */ for (int i=0; i<64; i++) { ipad[i] = ipad[i] ^ 0x36; opad[i] = opad[i] ^ 0x5c; } QByteArray workArray; workArray.append(ipad, 64); /* http://tools.ietf.org/html/rfc2104 - (3) */ workArray.append(message.toAscii()); /* http://tools.ietf.org/html/rfc2104 - (4) */ QByteArray sha1 = QCryptographicHash::hash(workArray, QCryptographicHash::Sha1); /* http://tools.ietf.org/html/rfc2104 - (6) */ workArray.clear(); workArray.append(opad, 64); workArray.append(sha1); sha1.clear(); /* http://tools.ietf.org/html/rfc2104 - (7) */ sha1 = QCryptographicHash::hash(workArray, QCryptographicHash::Sha1); return QString(sha1.toBase64()); } <commit_msg>Filled HMAC arrays with 0 just to be sure<commit_after>/** * KQOAuth - An OAuth authentication library for Qt. * * Author: Johan Paul ([email protected]) * http://www.johanpaul.com * * KQOAuth 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 3 of the License, or * (at your option) any later version. * * KQOAuth 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 KQOAuth. If not, see <http://www.gnu.org/licenses/>. */ #include <QString> #include <QCryptographicHash> #include <QByteArray> #include <QtDebug> #include "kqoauthutils.h" QString KQOAuthUtils::hmac_sha1(const QString &message, const QString &key) { QByteArray keyBytes = key.toAscii(); int keyLength; // Lenght of key word const int blockSize = 64; // Both MD5 and SHA-1 have a block size of 64. keyLength = keyBytes.size(); // If key is longer than block size, we need to hash the key if(keyLength > blockSize) { QCryptographicHash hash(QCryptographicHash::Sha1); hash.addData(keyBytes); keyBytes = hash.result(); keyLength = keyBytes.size(); } /* http://tools.ietf.org/html/rfc2104 - (1) */ // Create the opad and ipad for the hash function. QByteArray ipad; QByteArray opad; ipad.fill( 0, blockSize+1); opad.fill( 0, blockSize+1); ipad.replace(0, keyBytes.length(), keyBytes.constData()); opad.replace(0, keyBytes.length(), keyBytes.constData()); /* http://tools.ietf.org/html/rfc2104 - (2) & (5) */ for (int i=0; i<64; i++) { ipad[i] = ipad[i] ^ 0x36; opad[i] = opad[i] ^ 0x5c; } QByteArray workArray; workArray.append(ipad, 64); /* http://tools.ietf.org/html/rfc2104 - (3) */ workArray.append(message.toAscii()); /* http://tools.ietf.org/html/rfc2104 - (4) */ QByteArray sha1 = QCryptographicHash::hash(workArray, QCryptographicHash::Sha1); /* http://tools.ietf.org/html/rfc2104 - (6) */ workArray.clear(); workArray.append(opad, 64); workArray.append(sha1); sha1.clear(); /* http://tools.ietf.org/html/rfc2104 - (7) */ sha1 = QCryptographicHash::hash(workArray, QCryptographicHash::Sha1); return QString(sha1.toBase64()); } <|endoftext|>
<commit_before>/* * Copyright (C) 2003 Unai Garro <[email protected]> */ #include "krecipesview.h" #include <iostream> #include <qpainter.h> #include <qlayout.h> #include <qsplitter.h> #include <kurl.h> #include <kapp.h> #include <ktrader.h> #include <klibloader.h> #include <kmessagebox.h> #include <krun.h> #include <klocale.h> #include <kconfig.h> #include "setupwizard.h" #include "recipeinputdialog.h" #include "recipeviewdialog.h" #include "selectrecipedialog.h" #include "ingredientsdialog.h" #include "propertiesdialog.h" #include "shoppinglistdialog.h" #include "dietwizarddialog.h" #include "categorieseditordialog.h" #include "authorsdialog.h" #include "unitsdialog.h" #include "recipedb.h" #include "menugroup.h" KrecipesView::KrecipesView(QWidget *parent) : QVBox(parent) { // Init the setup wizard if necessary wizard(); // Initialize Database KConfig *config; config=kapp->config(); config->setGroup("Server"); QString host=config->readEntry( "Host","localhost"); QString user=config->readEntry( "Username",QString::null); QString pass=config->readEntry("Password",QString::null); QString dbname=config->readEntry( "DBName", DEFAULT_DB_NAME); database=new RecipeDB(host,user,pass,dbname); splitter=new QSplitter(this); // Set Splitter Parameters splitter->setFrameShape( QSplitter::NoFrame ); splitter->setFrameShadow( QSplitter::Plain ); splitter->setOrientation( QSplitter::Horizontal ); splitter->setOpaqueResize(); // Create Left and Right Panels (splitter) leftPanel=new MenuGroup(splitter,"leftPanel"); rightPanel=new QWidgetStack(splitter,"rightPanel"); leftPanel->setMinimumWidth(22); // Design Resizing of the panels splitter->setResizeMode(leftPanel,QSplitter::FollowSizeHint); // Design Left Panel il=new KIconLoader; button0=new QPushButton(leftPanel); button0->setFlat(true); button0->setIconSet(il->loadIconSet("filefind", KIcon::Small)); button0->setGeometry(0,0,150,30); button1=new QPushButton(leftPanel); button1->setFlat(true); button1->setIconSet(il->loadIconSet( "trolley", KIcon::Small )); button1->setGeometry(0,30,150,30); button2=new QPushButton(leftPanel); button2->setFlat(true); button2->setIconSet(il->loadIconSet( "ingredients", KIcon::Small )); button2->setGeometry(0,60,150,30); button3=new QPushButton(leftPanel); button3->setFlat(true); button3->setIconSet(il->loadIconSet( "properties", KIcon::Small )); button3->setGeometry(0,90,150,30); button4=new QPushButton(leftPanel); button4->setFlat(true); button4->setIconSet(il->loadIconSet( "units", KIcon::Small )); button4->setGeometry(0,120,150,30); button5=new QPushButton(leftPanel); button5->setFlat(true); button5->setIconSet(il->loadIconSet( "categories", KIcon::Small )); button5->setGeometry(0,150,150,30); button6=new QPushButton(leftPanel); button6->setFlat(true); button6->setIconSet(il->loadIconSet( "personal", KIcon::Small )); button6->setGeometry(0,180,150,30); // Right Panel Widgets inputPanel=new RecipeInputDialog(rightPanel,database); rightPanel->addWidget(inputPanel); viewPanel=new RecipeViewDialog(rightPanel,database,1);rightPanel->addWidget(viewPanel); selectPanel=new SelectRecipeDialog(rightPanel,database);rightPanel->addWidget(selectPanel); ingredientsPanel=new IngredientsDialog(rightPanel,database);rightPanel->addWidget(ingredientsPanel); propertiesPanel=new PropertiesDialog(rightPanel,database);rightPanel->addWidget(propertiesPanel); unitsPanel=new UnitsDialog(rightPanel,database); rightPanel->addWidget(unitsPanel); shoppingListPanel=new ShoppingListDialog(rightPanel,database); rightPanel->addWidget(shoppingListPanel); dietPanel=new DietWizardDialog(rightPanel,database);rightPanel->addWidget(dietPanel); categoriesPanel=new CategoriesEditorDialog(rightPanel,database); rightPanel->addWidget(categoriesPanel); authorsPanel=new AuthorsDialog(rightPanel,database); rightPanel->addWidget(inputPanel); rightPanel->addWidget(authorsPanel); // i18n translate(); // Initialize Variables recipeButton=0; // Connect Signals from Left Panel to slotSetPanel() connect( leftPanel, SIGNAL(clicked(int)),this, SLOT(slotSetPanel(int)) ); connect(shoppingListPanel,SIGNAL(wizardClicked()),this,SLOT(slotSetDietWizardPanel())); rightPanel->raiseWidget(selectPanel); // Retransmit signal to parent to Enable/Disable the Save Button connect (inputPanel, SIGNAL(enableSaveOption(bool)), this, SIGNAL(enableSaveOption(bool))); // Create a new button when a recipe is unsaved connect (inputPanel, SIGNAL(createButton(QWidget*,QString)), this, SLOT(addRecipeButton(QWidget*,QString))); // Connect Signals from selectPanel (SelectRecipeDialog) connect (selectPanel, SIGNAL(recipeSelected(int,int)),this, SLOT(actionRecipe(int,int))); // Resize signal connect (leftPanel, SIGNAL(resized(int,int)),this, SLOT(resizeButtons())); // Close a recipe when requested (just switch panels) connect(inputPanel,SIGNAL(closeRecipe()),this,SLOT(closeRecipe())); // Show a recipe when requested (just switch panels) connect(inputPanel,SIGNAL(showRecipe(int)),this,SLOT(showRecipe(int))); // Add recipe to the shopping list when requested connect(inputPanel,SIGNAL(addRecipeToShoppingList(int)),shoppingListPanel,SLOT(addRecipeToShoppingList(int))); } KrecipesView::~KrecipesView() { delete il; // remove iconloader } void KrecipesView::translate(){ button0->setText(i18n("Find/Edit Recipes")); QToolTip::add(button0, i18n("Find/Edit Recipes")); button1->setText(i18n("Shopping List")); QToolTip::add(button1, i18n("Shopping List")); button2->setText(i18n("Ingredients")); QToolTip::add(button2, i18n("Ingredients")); button3->setText(i18n("Properties")); QToolTip::add(button3, i18n("Properties")); button4->setText(i18n("Units")); QToolTip::add(button4, i18n("Units")); button5->setText(i18n("Recipe Categories")); QToolTip::add(button5, i18n("Recipe Categories")); button6->setText(i18n("Authors")); QToolTip::add(button6, i18n("Authors")); } void KrecipesView::print(QPainter *p, int height, int width) { // do the actual printing, here // p->drawText(etc..) } void KrecipesView::slotSetTitle(const QString& title) { emit signalChangeCaption(title); } // Function to switch panels void KrecipesView::slotSetPanel(int w) { switch (w) { case SelectP: selectPanel->reload(); // Reload data this->rightPanel->raiseWidget(selectPanel); break; case ShoppingP: shoppingListPanel->reload(); // Reload data this->rightPanel->raiseWidget(shoppingListPanel); break; case IngredientsP: ingredientsPanel->reload();// Reload data this->rightPanel->raiseWidget(ingredientsPanel); break; case PropertiesP: propertiesPanel->reload(); this->rightPanel->raiseWidget(propertiesPanel); break; case UnitsP: unitsPanel->reload(); // Reload data this->rightPanel->raiseWidget(unitsPanel); break; case CategoriesP: this->rightPanel->raiseWidget(categoriesPanel); break; case DietWizardP: dietPanel->reload(); this->rightPanel->raiseWidget(dietPanel); break; case AuthorsP: authorsPanel->reload(); this->rightPanel->raiseWidget(authorsPanel); break; } } void KrecipesView::save(void) { inputPanel->save(); } void KrecipesView::actionRecipe(int recipeID, int action) { if (action==0) //Show { showRecipe(recipeID); } else if (action==1) // Edit { if ( !inputPanel->everythingSaved() ) { switch( KMessageBox::questionYesNoCancel( this, i18n(QString("Recipe \"%1\" contains unsaved changes.\n" "Do you want to save changes made to this recipe before editing another recipe?").arg(recipeButton->text())), i18n("Unsaved changes") ) ) { case KMessageBox::Yes: inputPanel->save(); break; case KMessageBox::No: break; case KMessageBox::Cancel: return; } } inputPanel->loadRecipe(recipeID); rightPanel->raiseWidget(inputPanel); } else if (action==2) //Remove { database->removeRecipe(recipeID); selectPanel->reload(); } } void KrecipesView::createNewRecipe(void) { if ( !inputPanel->everythingSaved() ) { switch( KMessageBox::questionYesNoCancel( this, i18n(QString("Recipe \"%1\" contains unsaved changes.\n" "Do you want to save changes made to this recipe before creating a new recipe?").arg(recipeButton->text())), i18n("Unsaved changes") ) ) { case KMessageBox::Yes: inputPanel->save(); break; case KMessageBox::No: break; case KMessageBox::Cancel: return; } } inputPanel->newRecipe(); rightPanel->raiseWidget(inputPanel); } void KrecipesView::createNewElement(void) { if (rightPanel->id(rightPanel->visibleWidget())==4) //Properties Panel is the active one { propertiesPanel->createNewProperty(); } else{ createNewRecipe(); } } void KrecipesView::wizard(void) { KConfig *config=kapp->config(); config->setGroup("Wizard"); bool setupDone=config->readBoolEntry( "SystemSetup",false); if (!setupDone) { bool setupUser,initData,adminEnabled; QString adminUser,adminPass,user,pass,host,client,dbName; bool isRemote; SetupWizard *setupWizard=new SetupWizard(this); if(setupWizard->exec()== QDialog::Accepted) { std::cerr<<"Setting up\n"; setupWizard->getOptions(setupUser,initData); // Setup user if necessary if (setupUser) // Don't setup user if checkbox of existing user... was set { std::cerr<<"Setting up user\n"; setupWizard->getAdminInfo(adminEnabled,adminUser,adminPass); setupWizard->getServerInfo(isRemote,host,client,dbName,user,pass); if (!adminEnabled) // Use root without password { std::cerr<<"Using default admin\n"; adminUser="root"; adminPass=QString::null; } if (!isRemote) // Use localhost { std::cerr<<"Using localhost\n"; host="localhost"; client="localhost"; } setupUserPermissions(host,client,dbName,user,pass,adminUser,adminPass); } // Initialize database with data if requested if (initData) { setupWizard->getServerInfo(isRemote,host,client,dbName,user,pass); initializeData(host,dbName,user,pass); // Populate data as normal user } } delete setupWizard; } } void KrecipesView::slotSetDietWizardPanel(void) { dietPanel->reload(); rightPanel->raiseWidget(dietPanel); } void KrecipesView::setupUserPermissions(const QString &host, const QString &client, const QString &dbName, const QString &newUser,const QString &newPass,const QString &adminUser,const QString &adminPass) { RecipeDB *db; if (adminUser!=QString::null) { // Login as admin in the (remote) server and createDB if necessary std::cerr<<"Open db as:"<< adminUser.latin1() <<",*** with password ****\n"; db= new RecipeDB(host,adminUser,adminPass,dbName,true); // true means initialize db structure (It won't destroy data if exists) } else{ // Login as root with no password std::cerr<<"Open db as root, with no password\n"; db=new RecipeDB(host,"root",QString::null,dbName,true); } db->givePermissions(dbName,newUser,newPass,client); // give permissions to the user delete db; //it closes the db automatically } void KrecipesView::initializeData(const QString &host,const QString &dbName, const QString &user,const QString &pass) { RecipeDB *db; db= new RecipeDB(host,user,pass,dbName); db->initializeData(); delete db; //it closes the db automatically } void KrecipesView::resizeButtons(){ button0->resize(leftPanel->width(), 30); button1->resize(leftPanel->width(), 30); button2->resize(leftPanel->width(), 30); button3->resize(leftPanel->width(), 30); button4->resize(leftPanel->width(), 30); button5->resize(leftPanel->width(), 30); button6->resize(leftPanel->width(), 30); if(recipeButton){ recipeButton->resize(leftPanel->width(), 30); } } void KrecipesView::addRecipeButton(QWidget *w,QString title) { recipeWidget=w; if (!recipeButton) { recipeButton=new MenuButton(leftPanel,"recipeButton"); recipeButton->setFlat(true);recipeButton->setIconSet(il->loadIconSet("filesave",KIcon::Small)); recipeButton->setGeometry(0,250,150,30); recipeButton->setTitle(title); recipeButton->resize(leftPanel->width(),30); recipeButton->show(); connect(recipeButton,SIGNAL(clicked()),this,SLOT(switchToRecipe())); connect((RecipeInputDialog *)w,SIGNAL(titleChanged(const QString&)),recipeButton,SLOT(setTitle(const QString&))); } } void KrecipesView::switchToRecipe(void) { rightPanel->raiseWidget(recipeWidget); } void KrecipesView::closeRecipe(void) { selectPanel->reload(); rightPanel->raiseWidget(selectPanel); } void KrecipesView::showRecipe(int recipeID) { viewPanel->loadRecipe(recipeID); rightPanel->raiseWidget(viewPanel); } ////////////////// Class MenuButton Methods/////////////////// MenuButton::MenuButton(QWidget *parent,const char *name):QPushButton(parent,name) { } MenuButton::~MenuButton() { } void MenuButton::setTitle(const QString &title) { setText(title); QToolTip::add(this, title); } #include "krecipesview.moc" <commit_msg>Remove the recipe button after the recipe has been closed<commit_after>/* * Copyright (C) 2003 Unai Garro <[email protected]> */ #include "krecipesview.h" #include <iostream> #include <qpainter.h> #include <qlayout.h> #include <qsplitter.h> #include <kurl.h> #include <kapp.h> #include <ktrader.h> #include <klibloader.h> #include <kmessagebox.h> #include <krun.h> #include <klocale.h> #include <kconfig.h> #include "setupwizard.h" #include "recipeinputdialog.h" #include "recipeviewdialog.h" #include "selectrecipedialog.h" #include "ingredientsdialog.h" #include "propertiesdialog.h" #include "shoppinglistdialog.h" #include "dietwizarddialog.h" #include "categorieseditordialog.h" #include "authorsdialog.h" #include "unitsdialog.h" #include "recipedb.h" #include "menugroup.h" KrecipesView::KrecipesView(QWidget *parent) : QVBox(parent) { // Init the setup wizard if necessary wizard(); // Initialize Database KConfig *config; config=kapp->config(); config->setGroup("Server"); QString host=config->readEntry( "Host","localhost"); QString user=config->readEntry( "Username",QString::null); QString pass=config->readEntry("Password",QString::null); QString dbname=config->readEntry( "DBName", DEFAULT_DB_NAME); database=new RecipeDB(host,user,pass,dbname); splitter=new QSplitter(this); // Set Splitter Parameters splitter->setFrameShape( QSplitter::NoFrame ); splitter->setFrameShadow( QSplitter::Plain ); splitter->setOrientation( QSplitter::Horizontal ); splitter->setOpaqueResize(); // Create Left and Right Panels (splitter) leftPanel=new MenuGroup(splitter,"leftPanel"); rightPanel=new QWidgetStack(splitter,"rightPanel"); leftPanel->setMinimumWidth(22); // Design Resizing of the panels splitter->setResizeMode(leftPanel,QSplitter::FollowSizeHint); // Design Left Panel il=new KIconLoader; button0=new QPushButton(leftPanel); button0->setFlat(true); button0->setIconSet(il->loadIconSet("filefind", KIcon::Small)); button0->setGeometry(0,0,150,30); button1=new QPushButton(leftPanel); button1->setFlat(true); button1->setIconSet(il->loadIconSet( "trolley", KIcon::Small )); button1->setGeometry(0,30,150,30); button2=new QPushButton(leftPanel); button2->setFlat(true); button2->setIconSet(il->loadIconSet( "ingredients", KIcon::Small )); button2->setGeometry(0,60,150,30); button3=new QPushButton(leftPanel); button3->setFlat(true); button3->setIconSet(il->loadIconSet( "properties", KIcon::Small )); button3->setGeometry(0,90,150,30); button4=new QPushButton(leftPanel); button4->setFlat(true); button4->setIconSet(il->loadIconSet( "units", KIcon::Small )); button4->setGeometry(0,120,150,30); button5=new QPushButton(leftPanel); button5->setFlat(true); button5->setIconSet(il->loadIconSet( "categories", KIcon::Small )); button5->setGeometry(0,150,150,30); button6=new QPushButton(leftPanel); button6->setFlat(true); button6->setIconSet(il->loadIconSet( "personal", KIcon::Small )); button6->setGeometry(0,180,150,30); // Right Panel Widgets inputPanel=new RecipeInputDialog(rightPanel,database); rightPanel->addWidget(inputPanel); viewPanel=new RecipeViewDialog(rightPanel,database,1);rightPanel->addWidget(viewPanel); selectPanel=new SelectRecipeDialog(rightPanel,database);rightPanel->addWidget(selectPanel); ingredientsPanel=new IngredientsDialog(rightPanel,database);rightPanel->addWidget(ingredientsPanel); propertiesPanel=new PropertiesDialog(rightPanel,database);rightPanel->addWidget(propertiesPanel); unitsPanel=new UnitsDialog(rightPanel,database); rightPanel->addWidget(unitsPanel); shoppingListPanel=new ShoppingListDialog(rightPanel,database); rightPanel->addWidget(shoppingListPanel); dietPanel=new DietWizardDialog(rightPanel,database);rightPanel->addWidget(dietPanel); categoriesPanel=new CategoriesEditorDialog(rightPanel,database); rightPanel->addWidget(categoriesPanel); authorsPanel=new AuthorsDialog(rightPanel,database); rightPanel->addWidget(inputPanel); rightPanel->addWidget(authorsPanel); // i18n translate(); // Initialize Variables recipeButton=0; // Connect Signals from Left Panel to slotSetPanel() connect( leftPanel, SIGNAL(clicked(int)),this, SLOT(slotSetPanel(int)) ); connect(shoppingListPanel,SIGNAL(wizardClicked()),this,SLOT(slotSetDietWizardPanel())); rightPanel->raiseWidget(selectPanel); // Retransmit signal to parent to Enable/Disable the Save Button connect (inputPanel, SIGNAL(enableSaveOption(bool)), this, SIGNAL(enableSaveOption(bool))); // Create a new button when a recipe is unsaved connect (inputPanel, SIGNAL(createButton(QWidget*,QString)), this, SLOT(addRecipeButton(QWidget*,QString))); // Connect Signals from selectPanel (SelectRecipeDialog) connect (selectPanel, SIGNAL(recipeSelected(int,int)),this, SLOT(actionRecipe(int,int))); // Resize signal connect (leftPanel, SIGNAL(resized(int,int)),this, SLOT(resizeButtons())); // Close a recipe when requested (just switch panels) connect(inputPanel,SIGNAL(closeRecipe()),this,SLOT(closeRecipe())); // Show a recipe when requested (just switch panels) connect(inputPanel,SIGNAL(showRecipe(int)),this,SLOT(showRecipe(int))); // Add recipe to the shopping list when requested connect(inputPanel,SIGNAL(addRecipeToShoppingList(int)),shoppingListPanel,SLOT(addRecipeToShoppingList(int))); } KrecipesView::~KrecipesView() { delete il; // remove iconloader } void KrecipesView::translate(){ button0->setText(i18n("Find/Edit Recipes")); QToolTip::add(button0, i18n("Find/Edit Recipes")); button1->setText(i18n("Shopping List")); QToolTip::add(button1, i18n("Shopping List")); button2->setText(i18n("Ingredients")); QToolTip::add(button2, i18n("Ingredients")); button3->setText(i18n("Properties")); QToolTip::add(button3, i18n("Properties")); button4->setText(i18n("Units")); QToolTip::add(button4, i18n("Units")); button5->setText(i18n("Recipe Categories")); QToolTip::add(button5, i18n("Recipe Categories")); button6->setText(i18n("Authors")); QToolTip::add(button6, i18n("Authors")); } void KrecipesView::print(QPainter *p, int height, int width) { // do the actual printing, here // p->drawText(etc..) } void KrecipesView::slotSetTitle(const QString& title) { emit signalChangeCaption(title); } // Function to switch panels void KrecipesView::slotSetPanel(int w) { switch (w) { case SelectP: selectPanel->reload(); // Reload data this->rightPanel->raiseWidget(selectPanel); break; case ShoppingP: shoppingListPanel->reload(); // Reload data this->rightPanel->raiseWidget(shoppingListPanel); break; case IngredientsP: ingredientsPanel->reload();// Reload data this->rightPanel->raiseWidget(ingredientsPanel); break; case PropertiesP: propertiesPanel->reload(); this->rightPanel->raiseWidget(propertiesPanel); break; case UnitsP: unitsPanel->reload(); // Reload data this->rightPanel->raiseWidget(unitsPanel); break; case CategoriesP: this->rightPanel->raiseWidget(categoriesPanel); break; case DietWizardP: dietPanel->reload(); this->rightPanel->raiseWidget(dietPanel); break; case AuthorsP: authorsPanel->reload(); this->rightPanel->raiseWidget(authorsPanel); break; } } void KrecipesView::save(void) { inputPanel->save(); } void KrecipesView::actionRecipe(int recipeID, int action) { if (action==0) //Show { showRecipe(recipeID); } else if (action==1) // Edit { if ( !inputPanel->everythingSaved() ) { switch( KMessageBox::questionYesNoCancel( this, i18n(QString("Recipe \"%1\" contains unsaved changes.\n" "Do you want to save changes made to this recipe before editing another recipe?").arg(recipeButton->text())), i18n("Unsaved changes") ) ) { case KMessageBox::Yes: inputPanel->save(); break; case KMessageBox::No: break; case KMessageBox::Cancel: return; } } inputPanel->loadRecipe(recipeID); rightPanel->raiseWidget(inputPanel); } else if (action==2) //Remove { database->removeRecipe(recipeID); selectPanel->reload(); } } void KrecipesView::createNewRecipe(void) { if ( !inputPanel->everythingSaved() ) { switch( KMessageBox::questionYesNoCancel( this, i18n(QString("Recipe \"%1\" contains unsaved changes.\n" "Do you want to save changes made to this recipe before creating a new recipe?").arg(recipeButton->text())), i18n("Unsaved changes") ) ) { case KMessageBox::Yes: inputPanel->save(); break; case KMessageBox::No: break; case KMessageBox::Cancel: return; } } inputPanel->newRecipe(); rightPanel->raiseWidget(inputPanel); } void KrecipesView::createNewElement(void) { if (rightPanel->id(rightPanel->visibleWidget())==4) //Properties Panel is the active one { propertiesPanel->createNewProperty(); } else{ createNewRecipe(); } } void KrecipesView::wizard(void) { KConfig *config=kapp->config(); config->setGroup("Wizard"); bool setupDone=config->readBoolEntry( "SystemSetup",false); if (!setupDone) { bool setupUser,initData,adminEnabled; QString adminUser,adminPass,user,pass,host,client,dbName; bool isRemote; SetupWizard *setupWizard=new SetupWizard(this); if(setupWizard->exec()== QDialog::Accepted) { std::cerr<<"Setting up\n"; setupWizard->getOptions(setupUser,initData); // Setup user if necessary if (setupUser) // Don't setup user if checkbox of existing user... was set { std::cerr<<"Setting up user\n"; setupWizard->getAdminInfo(adminEnabled,adminUser,adminPass); setupWizard->getServerInfo(isRemote,host,client,dbName,user,pass); if (!adminEnabled) // Use root without password { std::cerr<<"Using default admin\n"; adminUser="root"; adminPass=QString::null; } if (!isRemote) // Use localhost { std::cerr<<"Using localhost\n"; host="localhost"; client="localhost"; } setupUserPermissions(host,client,dbName,user,pass,adminUser,adminPass); } // Initialize database with data if requested if (initData) { setupWizard->getServerInfo(isRemote,host,client,dbName,user,pass); initializeData(host,dbName,user,pass); // Populate data as normal user } } delete setupWizard; } } void KrecipesView::slotSetDietWizardPanel(void) { dietPanel->reload(); rightPanel->raiseWidget(dietPanel); } void KrecipesView::setupUserPermissions(const QString &host, const QString &client, const QString &dbName, const QString &newUser,const QString &newPass,const QString &adminUser,const QString &adminPass) { RecipeDB *db; if (adminUser!=QString::null) { // Login as admin in the (remote) server and createDB if necessary std::cerr<<"Open db as:"<< adminUser.latin1() <<",*** with password ****\n"; db= new RecipeDB(host,adminUser,adminPass,dbName,true); // true means initialize db structure (It won't destroy data if exists) } else{ // Login as root with no password std::cerr<<"Open db as root, with no password\n"; db=new RecipeDB(host,"root",QString::null,dbName,true); } db->givePermissions(dbName,newUser,newPass,client); // give permissions to the user delete db; //it closes the db automatically } void KrecipesView::initializeData(const QString &host,const QString &dbName, const QString &user,const QString &pass) { RecipeDB *db; db= new RecipeDB(host,user,pass,dbName); db->initializeData(); delete db; //it closes the db automatically } void KrecipesView::resizeButtons(){ button0->resize(leftPanel->width(), 30); button1->resize(leftPanel->width(), 30); button2->resize(leftPanel->width(), 30); button3->resize(leftPanel->width(), 30); button4->resize(leftPanel->width(), 30); button5->resize(leftPanel->width(), 30); button6->resize(leftPanel->width(), 30); if(recipeButton){ recipeButton->resize(leftPanel->width(), 30); } } void KrecipesView::addRecipeButton(QWidget *w,QString title) { recipeWidget=w; if (!recipeButton) { recipeButton=new MenuButton(leftPanel,"recipeButton"); recipeButton->setFlat(true);recipeButton->setIconSet(il->loadIconSet("filesave",KIcon::Small)); recipeButton->setGeometry(0,250,150,30); recipeButton->setTitle(title); recipeButton->resize(leftPanel->width(),30); recipeButton->show(); connect(recipeButton,SIGNAL(clicked()),this,SLOT(switchToRecipe())); connect((RecipeInputDialog *)w,SIGNAL(titleChanged(const QString&)),recipeButton,SLOT(setTitle(const QString&))); } } void KrecipesView::switchToRecipe(void) { rightPanel->raiseWidget(recipeWidget); } void KrecipesView::closeRecipe(void) { selectPanel->reload(); rightPanel->raiseWidget(selectPanel); delete recipeButton; recipeButton=0; } void KrecipesView::showRecipe(int recipeID) { viewPanel->loadRecipe(recipeID); rightPanel->raiseWidget(viewPanel); } ////////////////// Class MenuButton Methods/////////////////// MenuButton::MenuButton(QWidget *parent,const char *name):QPushButton(parent,name) { } MenuButton::~MenuButton() { } void MenuButton::setTitle(const QString &title) { setText(title); QToolTip::add(this, title); } #include "krecipesview.moc" <|endoftext|>
<commit_before>/* * Image.cpp * * Created on: Sep 8, 2009 * Author: rasmussn */ #include "Image.hpp" #include "../io/imageio.hpp" #include <assert.h> #include <string.h> namespace PV { Image::Image() { initialize_base(); } Image::Image(const char * name, HyPerCol * hc, const char * filename) { initialize_base(); initialize(name, hc, filename); } Image::~Image() { free(filename); filename = NULL; } int Image::initialize_base() { mpi_datatypes = NULL; data = NULL; filename = NULL; imageData = NULL; return PV_SUCCESS; } int Image::checkpointRead(float * timef){ PVParams * params = parent->parameters(); this->useParamsImage = (int) params->value(name,"useParamsImage", 0); if (this->useParamsImage) { fprintf(stderr,"Initializing image from params file location ! \n"); * timef = parent->simulationTime(); // fakes the pvp time stamp } else { fprintf(stderr,"Initializing image from checkpoint NOT from params file location! \n"); HyPerLayer::checkpointRead(timef); } return PV_SUCCESS; } int Image::initialize(const char * name, HyPerCol * hc, const char * filename) { HyPerLayer::initialize(name, hc, 0); int status = PV_SUCCESS; PVParams * params = parent->parameters(); this->writeImages = params->value(name, "writeImages", 0) != 0; readOffsets(); if(filename != NULL ) { this->filename = strdup(filename); assert( this->filename != NULL ); status = getImageInfo(filename, parent->icCommunicator(), &imageLoc); if( getLayerLoc()->nf != imageLoc.nf && getLayerLoc()->nf != 1) { fprintf(stderr, "Image %s: file %s has %d features but the layer has %d features. Exiting.\n", name, filename, imageLoc.nf, getLayerLoc()->nf); exit(PV_FAILURE); } } else { this->filename = NULL; this->imageLoc = * getLayerLoc(); } this->lastUpdateTime = 0.0; // TODO - must make image conform to layer size data = clayer->activity->data; // create mpi_datatypes for border transfer mpi_datatypes = Communicator::newDatatypes(getLayerLoc()); if (filename != NULL) { readImage(filename, offsetX, offsetY); } // exchange border information exchange(); return status; } int Image::readOffsets() { PVParams * params = parent->parameters(); this->offsetX = (int) params->value(name,"offsetX", 0); this->offsetY = (int) params->value(name,"offsetY", 0); return PV_SUCCESS; } int Image::initializeV() { assert(parent->parameters()->value(name, "restart", 0.0f, false)==0.0f); // initializeV should only be called if restart is false // Image doesn't use the V buffer so free it and set the pointer to null. free(clayer->V); clayer->V = NULL; return PV_SUCCESS; } #ifdef PV_USE_OPENCL // no need for threads for now for image // int Image::initializeThreadBuffers() { return CL_SUCCESS; } // no need for threads for now for image // int Image::initializeThreadKernels() { return CL_SUCCESS; } #endif /** * return some useful information about the image */ int Image::tag() { return 0; } int Image::recvSynapticInput(HyPerConn * conn, const PVLayerCube * cube, int neighbor) { // this should never be called as an image shouldn't have an incoming connection recvsyn_timer->start(); recvsyn_timer->stop(); return 0; } /** * update the image buffers */ int Image::updateState(float time, float dt) { // make sure image is copied to activity buffer // update_timer->start(); update_timer->stop(); return 0; } int Image::outputState(float time, bool last) { // this could probably use Marion's update time interval // for some classes // return 0; } //! CLEAR IMAGE /*! * this is Image specific. */ int Image::clearImage() { // default is to do nothing for now // it could, for example, set the data buffer to zero. return 0; } int Image::readImage(const char * filename) { return readImage(filename, 0, 0); } int Image::readImage(const char * filename, int offsetX, int offsetY) { int status = 0; PVLayerLoc * loc = & clayer->loc; const int n = loc->nx * loc->ny * imageLoc.nf; // Use number of bands in file instead of in params, to allow for grayscale conversion float * buf = new float[n]; assert(buf != NULL); // read the image and scatter the local portions status = scatterImageFile(filename, offsetX, offsetY, parent->icCommunicator(), loc, buf); if( loc->nf == 1 && imageLoc.nf > 1 ) { buf = convertToGrayScale(buf,loc->nx,loc->ny,imageLoc.nf); } // now buf is loc->nf by loc->nx by loc->ny // Scaling by 1/255 moved to scatterImageFileGDAL and the compressed part of scatterImageFilePVP, // since it is unnecessary for uncompressed PVP files. // if (status == 0) { // float fac = 1.0f / 255.0f; // normalize to 1.0 // status = copyFromInteriorBuffer(buf, fac); // } if( status == 0 ) copyFromInteriorBuffer(buf, 1.0f); delete buf; return status; } /** * * The data buffer lives in the extended space. Here, we only copy the restricted space * to the buffer buf. The size of this buffer is the size of the image patch - borders * are not included. * */ int Image::write(const char * filename) { int status = 0; const PVLayerLoc * loc = getLayerLoc(); const int n = loc->nx * loc->ny * loc->nf; unsigned char * buf = new unsigned char[n]; assert(buf != NULL); status = copyToInteriorBuffer(buf, 255.0); // gather the local portions and write the image status = gatherImageFile(filename, parent->icCommunicator(), loc, buf); delete buf; return status; } int Image::exchange() { return parent->icCommunicator()->exchange(data, mpi_datatypes, getLayerLoc()); } int Image::copyToInteriorBuffer(unsigned char * buf, float fac) { const PVLayerLoc * loc = getLayerLoc(); const int nx = loc->nx; const int ny = loc->ny; const int nf = loc->nf; const int nBorder = loc->nb; for(int n=0; n<getNumNeurons(); n++) { int n_ex = kIndexExtended(n, nx, ny, nf, nBorder); buf[n] = (unsigned char) (fac * data[n_ex]); } return 0; } int Image::copyFromInteriorBuffer(float * buf, float fac) { const PVLayerLoc * loc = getLayerLoc(); const int nx = loc->nx; const int ny = loc->ny; const int nf = loc->nf; const int nBorder = loc->nb; for(int n=0; n<getNumNeurons(); n++) { int n_ex = kIndexExtended(n, nx, ny, nf, nBorder); data[n_ex] = fac*buf[n]; } return 0; } #ifdef OBSOLETE // Marked obsolete July 10, 2011 int Image::toGrayScale() { const PVLayerLoc * loc = getLayerLoc(); const int nx_ex = loc->nx + 2*loc->nb; const int ny_ex = loc->ny + 2*loc->nb; const int numBands = loc->nf; const size_t sx = 1; const size_t sy = loc->nx + loc->halo.lt + loc->halo.rt; const size_t sb = sy * (loc->ny + loc->halo.dn + loc->halo.up); if (numBands < 2) return 0; for (int j = 0; j < ny_ex; j++) { for (int i = 0; i < nx_ex; i++) { float val = 0; for (int b = 0; b < numBands; b++) { float d = data[i*sx + j*sy + b*sb]; val += d*d; // val += d; } // store the converted image in the first color band data[i*sx + j*sy + 0*sb] = sqrtf(val/numBands); // data[i*sx + j*sy + 0*sb] = val/numBands; } } // turn off the color clayer->loc.nf = 1; clayer->numNeurons = clayer->loc.nx * clayer->loc.ny; clayer->numExtended = (clayer->loc.nx + 2*clayer->loc.nb) * (clayer->loc.ny + 2*clayer->loc.nb); return 0; } #endif // OBSOLETE float * Image::convertToGrayScale(float * buf, int nx, int ny, int numBands) { // even though the numBands argument goes last, the routine assumes that // the organization of buf is, bands vary fastest, then x, then y. if (numBands < 2) return buf; const int sxcolor = numBands; const int sycolor = numBands*nx; const int sb = 1; const int sxgray = 1; const int sygray = nx; float * graybuf = new float[nx*ny]; for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { float val = 0; for (int b = 0; b < numBands; b++) { float d = buf[i*sxcolor + j*sycolor + b*sb]; val += d*d; } graybuf[i*sxgray + j*sygray] = sqrtf(val/numBands); } } delete buf; return graybuf; } int Image::convolve(int width) { const PVLayerLoc * loc = getLayerLoc(); const int nx_ex = loc->nx + 2*loc->nb; const int ny_ex = loc->ny + 2*loc->nb; //const int nb = loc->nf; const int size_ex = nx_ex * ny_ex; // an image is different from normal layers as features (bands) vary last const size_t sx = 1; const size_t sy = loc->nx + loc->halo.lt + loc->halo.rt; const int npx = width; const int npy = width; const int npx_2 = width/2; const int npy_2 = width/2; assert(npx <= loc->nb); assert(npy <= loc->nb); float * buf = new float[size_ex]; //for (int i = 0; i < size_ex; i++) buf[i] = 0; float max = -1.0e9; float min = -max; // ignore image bands for now for (int jex = npy_2; jex < ny_ex - npy_2; jex++) { for (int iex = npx_2; iex < nx_ex - npx_2; iex++) { float av = 0; float sq = 0; for (int jp = 0; jp < npy; jp++) { for (int ip = 0; ip < npx; ip++) { // int ix = i + ip - npx_2; // int iy = j + jp - npy_2; // float val = data[ix*sx + iy*sy]; // av += val; // sq += val * val; } } av = av / (npx*npy); min = (av < min) ? av : min; max = (av > max) ? av : max; // sq = sqrt( sq/(nPad*nPad) - av*av ) + tau; // buf[i*sx + j*sy] = data[i*sx + j*sy] + mid - av; buf[iex*sx + jex*sy] = .95f * 255.0f * (data[iex*sx + jex*sy] - .95f * av) / sq; } } printf("min==%f max==%f\n", min, max); for (int k = 0; k < size_ex; k++) data[k] = buf[k]; return 0; } } // namespace PV <commit_msg>Changes convertToGrayScale to take the mean across color bands instead of root-mean-square.<commit_after>/* * Image.cpp * * Created on: Sep 8, 2009 * Author: rasmussn */ #include "Image.hpp" #include "../io/imageio.hpp" #include <assert.h> #include <string.h> namespace PV { Image::Image() { initialize_base(); } Image::Image(const char * name, HyPerCol * hc, const char * filename) { initialize_base(); initialize(name, hc, filename); } Image::~Image() { free(filename); filename = NULL; } int Image::initialize_base() { mpi_datatypes = NULL; data = NULL; filename = NULL; imageData = NULL; return PV_SUCCESS; } int Image::checkpointRead(float * timef){ PVParams * params = parent->parameters(); this->useParamsImage = (int) params->value(name,"useParamsImage", 0); if (this->useParamsImage) { fprintf(stderr,"Initializing image from params file location ! \n"); * timef = parent->simulationTime(); // fakes the pvp time stamp } else { fprintf(stderr,"Initializing image from checkpoint NOT from params file location! \n"); HyPerLayer::checkpointRead(timef); } return PV_SUCCESS; } int Image::initialize(const char * name, HyPerCol * hc, const char * filename) { HyPerLayer::initialize(name, hc, 0); int status = PV_SUCCESS; PVParams * params = parent->parameters(); this->writeImages = params->value(name, "writeImages", 0) != 0; readOffsets(); if(filename != NULL ) { this->filename = strdup(filename); assert( this->filename != NULL ); status = getImageInfo(filename, parent->icCommunicator(), &imageLoc); if( getLayerLoc()->nf != imageLoc.nf && getLayerLoc()->nf != 1) { fprintf(stderr, "Image %s: file %s has %d features but the layer has %d features. Exiting.\n", name, filename, imageLoc.nf, getLayerLoc()->nf); exit(PV_FAILURE); } } else { this->filename = NULL; this->imageLoc = * getLayerLoc(); } this->lastUpdateTime = 0.0; // TODO - must make image conform to layer size data = clayer->activity->data; // create mpi_datatypes for border transfer mpi_datatypes = Communicator::newDatatypes(getLayerLoc()); if (filename != NULL) { readImage(filename, offsetX, offsetY); } // exchange border information exchange(); return status; } int Image::readOffsets() { PVParams * params = parent->parameters(); this->offsetX = (int) params->value(name,"offsetX", 0); this->offsetY = (int) params->value(name,"offsetY", 0); return PV_SUCCESS; } int Image::initializeV() { assert(parent->parameters()->value(name, "restart", 0.0f, false)==0.0f); // initializeV should only be called if restart is false // Image doesn't use the V buffer so free it and set the pointer to null. free(clayer->V); clayer->V = NULL; return PV_SUCCESS; } #ifdef PV_USE_OPENCL // no need for threads for now for image // int Image::initializeThreadBuffers() { return CL_SUCCESS; } // no need for threads for now for image // int Image::initializeThreadKernels() { return CL_SUCCESS; } #endif /** * return some useful information about the image */ int Image::tag() { return 0; } int Image::recvSynapticInput(HyPerConn * conn, const PVLayerCube * cube, int neighbor) { // this should never be called as an image shouldn't have an incoming connection recvsyn_timer->start(); recvsyn_timer->stop(); return 0; } /** * update the image buffers */ int Image::updateState(float time, float dt) { // make sure image is copied to activity buffer // update_timer->start(); update_timer->stop(); return 0; } int Image::outputState(float time, bool last) { // this could probably use Marion's update time interval // for some classes // return 0; } //! CLEAR IMAGE /*! * this is Image specific. */ int Image::clearImage() { // default is to do nothing for now // it could, for example, set the data buffer to zero. return 0; } int Image::readImage(const char * filename) { return readImage(filename, 0, 0); } int Image::readImage(const char * filename, int offsetX, int offsetY) { int status = 0; PVLayerLoc * loc = & clayer->loc; const int n = loc->nx * loc->ny * imageLoc.nf; // Use number of bands in file instead of in params, to allow for grayscale conversion float * buf = new float[n]; assert(buf != NULL); // read the image and scatter the local portions status = scatterImageFile(filename, offsetX, offsetY, parent->icCommunicator(), loc, buf); if( loc->nf == 1 && imageLoc.nf > 1 ) { buf = convertToGrayScale(buf,loc->nx,loc->ny,imageLoc.nf); } // now buf is loc->nf by loc->nx by loc->ny // Scaling by 1/255 moved to scatterImageFileGDAL and the compressed part of scatterImageFilePVP, // since it is unnecessary for uncompressed PVP files. // if (status == 0) { // float fac = 1.0f / 255.0f; // normalize to 1.0 // status = copyFromInteriorBuffer(buf, fac); // } if( status == 0 ) copyFromInteriorBuffer(buf, 1.0f); delete buf; return status; } /** * * The data buffer lives in the extended space. Here, we only copy the restricted space * to the buffer buf. The size of this buffer is the size of the image patch - borders * are not included. * */ int Image::write(const char * filename) { int status = 0; const PVLayerLoc * loc = getLayerLoc(); const int n = loc->nx * loc->ny * loc->nf; unsigned char * buf = new unsigned char[n]; assert(buf != NULL); status = copyToInteriorBuffer(buf, 255.0); // gather the local portions and write the image status = gatherImageFile(filename, parent->icCommunicator(), loc, buf); delete buf; return status; } int Image::exchange() { return parent->icCommunicator()->exchange(data, mpi_datatypes, getLayerLoc()); } int Image::copyToInteriorBuffer(unsigned char * buf, float fac) { const PVLayerLoc * loc = getLayerLoc(); const int nx = loc->nx; const int ny = loc->ny; const int nf = loc->nf; const int nBorder = loc->nb; for(int n=0; n<getNumNeurons(); n++) { int n_ex = kIndexExtended(n, nx, ny, nf, nBorder); buf[n] = (unsigned char) (fac * data[n_ex]); } return 0; } int Image::copyFromInteriorBuffer(float * buf, float fac) { const PVLayerLoc * loc = getLayerLoc(); const int nx = loc->nx; const int ny = loc->ny; const int nf = loc->nf; const int nBorder = loc->nb; for(int n=0; n<getNumNeurons(); n++) { int n_ex = kIndexExtended(n, nx, ny, nf, nBorder); data[n_ex] = fac*buf[n]; } return 0; } float * Image::convertToGrayScale(float * buf, int nx, int ny, int numBands) { // even though the numBands argument goes last, the routine assumes that // the organization of buf is, bands vary fastest, then x, then y. if (numBands < 2) return buf; const int sxcolor = numBands; const int sycolor = numBands*nx; const int sb = 1; const int sxgray = 1; const int sygray = nx; float * graybuf = new float[nx*ny]; for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { float val = 0; for (int b = 0; b < numBands; b++) { float d = buf[i*sxcolor + j*sycolor + b*sb]; val += d; } graybuf[i*sxgray + j*sygray] = val/numBands; } } delete buf; return graybuf; } int Image::convolve(int width) { const PVLayerLoc * loc = getLayerLoc(); const int nx_ex = loc->nx + 2*loc->nb; const int ny_ex = loc->ny + 2*loc->nb; //const int nb = loc->nf; const int size_ex = nx_ex * ny_ex; // an image is different from normal layers as features (bands) vary last const size_t sx = 1; const size_t sy = loc->nx + loc->halo.lt + loc->halo.rt; const int npx = width; const int npy = width; const int npx_2 = width/2; const int npy_2 = width/2; assert(npx <= loc->nb); assert(npy <= loc->nb); float * buf = new float[size_ex]; //for (int i = 0; i < size_ex; i++) buf[i] = 0; float max = -1.0e9; float min = -max; // ignore image bands for now for (int jex = npy_2; jex < ny_ex - npy_2; jex++) { for (int iex = npx_2; iex < nx_ex - npx_2; iex++) { float av = 0; float sq = 0; for (int jp = 0; jp < npy; jp++) { for (int ip = 0; ip < npx; ip++) { // int ix = i + ip - npx_2; // int iy = j + jp - npy_2; // float val = data[ix*sx + iy*sy]; // av += val; // sq += val * val; } } av = av / (npx*npy); min = (av < min) ? av : min; max = (av > max) ? av : max; // sq = sqrt( sq/(nPad*nPad) - av*av ) + tau; // buf[i*sx + j*sy] = data[i*sx + j*sy] + mid - av; buf[iex*sx + jex*sy] = .95f * 255.0f * (data[iex*sx + jex*sy] - .95f * av) / sq; } } printf("min==%f max==%f\n", min, max); for (int k = 0; k < size_ex; k++) data[k] = buf[k]; return 0; } } // namespace PV <|endoftext|>
<commit_before>/** * File : C.cpp * Author : Kazune Takahashi * Created : 2018-10-27 20:57:45 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N; ll A[100010]; ll B[100010]; int main() { cin >> N; for (auto i = 0; i < N; i++) { cin >> A[i]; } sort(A, A + N); for (auto i = 0; i < N; i++) { if (i % 2 == 0) { B[i / 2] = A[i]; } else { B[N - i / 2 - 1] = A[i]; } } ll sum = 0; for (auto i = 0; i < N - 1; i++) { sum += abs(B[i] - B[i + 1]); } cout << sum << endl; }<commit_msg>tried C.cpp to 'C'<commit_after>/** * File : C.cpp * Author : Kazune Takahashi * Created : 2018-10-27 20:57:45 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N; ll A[100010]; ll B[100010]; int main() { cin >> N; for (auto i = 0; i < N; i++) { cin >> A[i]; } sort(A, A + N); for (auto i = 0; i < N; i++) { if (i % 2 == 0) { B[i / 2] = A[i]; } else { B[N - i / 2 - 1] = A[i]; } } ll sum = 0; for (auto i = 0; i < N - 1; i++) { cerr << "B[" << i << "] = " << B[i] << endl; sum += abs(B[i] - B[i + 1]); } cout << sum << endl; }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2019-5-11 22:04:36 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; const int MAX_SIZE = 1000010; const long long MOD = 1000000007; long long inv[MAX_SIZE]; long long fact[MAX_SIZE]; long long factinv[MAX_SIZE]; void init() { inv[1] = 1; for (int i = 2; i < MAX_SIZE; i++) { inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD; } fact[0] = factinv[0] = 1; for (int i = 1; i < MAX_SIZE; i++) { fact[i] = (i * fact[i - 1]) % MOD; factinv[i] = (inv[i] * factinv[i - 1]) % MOD; } } long long C(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD; } return 0; } long long power(long long x, long long n) { if (n == 0) { return 1; } else if (n % 2 == 1) { return (x * power(x, n - 1)) % MOD; } else { long long half = power(x, n / 2); return (half * half) % MOD; } } long long gcd(long long x, long long y) { return y ? gcd(y, x % y) : x; } typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; typedef tuple<int, int> edge; typedef tuple<int, int, int> info; int N, M; int a[210]; int b[210]; vector<edge> V[20]; vector<int> W[1 << 20]; vector<int> masks; vector<ll> scores[1 << 20]; void add_mask(int mask, ll score) { scores[mask].push_back(score); for (auto i = 0; i < N; i++) { if (((mask >> i) & 1) == 0) { add_mask(mask + (1 << i), score - 1); } } } int main() { init(); cin >> N >> M; for (auto i = 0; i < M; i++) { cin >> a[i] >> b[i]; a[i]--; b[i]--; } for (auto i = 0; i < N - 1; i++) { V[a[i]].push_back(edge(b[i], i)); V[b[i]].push_back(edge(a[i], i)); } for (auto i = N - 1; i < M; i++) { edge from[20]; fill(from, from + 20, edge(-1, -1)); stack<info> S; S.push(info(a[i], -1, -1)); while (!S.empty()) { info e = S.top(); int dst = get<0>(e); int src = get<1>(e); int num = get<2>(e); S.pop(); if (from[dst] == edge(-1, -1)) { from[dst] = edge(src, num); if (dst == b[i]) { break; } for (auto x : V[dst]) { int next = get<0>(x); int next_num = get<1>(x); if (from[next] == edge(-1, -1)) { S.push(info(next, dst, next_num)); } } } } int mask = 0; int temp = b[i]; while (temp != a[i]) { int num = get<1>(from[temp]); mask += (1 << num); temp = get<0>(from[temp]); } masks.push_back(mask); } for (auto mask : masks) { int x = (1 << N) - mask; ll score = 0; for (auto i = 0; i < N; i++) { if ((x >> i) & 1) { score++; } } add_mask(mask, score); } #if DEBUG == 1 for (auto i = 0; i < (1 << N); i++) { cerr << "scores[" << i << "] = {"; for (auto x : scores[i]) { cerr << x << ", "; } cerr << "}" << endl; } #endif ll ans = (fact[N] * fact[M]) % MOD; }<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2019-5-11 22:04:36 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; const int MAX_SIZE = 1000010; const long long MOD = 1000000007; long long inv[MAX_SIZE]; long long fact[MAX_SIZE]; long long factinv[MAX_SIZE]; void init() { inv[1] = 1; for (int i = 2; i < MAX_SIZE; i++) { inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD; } fact[0] = factinv[0] = 1; for (int i = 1; i < MAX_SIZE; i++) { fact[i] = (i * fact[i - 1]) % MOD; factinv[i] = (inv[i] * factinv[i - 1]) % MOD; } } long long C(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD; } return 0; } long long power(long long x, long long n) { if (n == 0) { return 1; } else if (n % 2 == 1) { return (x * power(x, n - 1)) % MOD; } else { long long half = power(x, n / 2); return (half * half) % MOD; } } long long gcd(long long x, long long y) { return y ? gcd(y, x % y) : x; } typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; typedef tuple<int, int> edge; typedef tuple<int, int, int> info; int N, M; int a[210]; int b[210]; vector<edge> V[20]; vector<int> W[1 << 20]; vector<int> memo[1 << 20]; set<int> sets[1 << 20]; void add_mask(int mask, int num) { if (sets[mask].find(num) == sets[mask].end()) { return; } sets[mask].insert(num); for (auto i = 0; i < N; i++) { if (((mask >> i) & 1) == 0) { add_mask(mask + (1 << i), num); } } } int main() { init(); cin >> N >> M; for (auto i = 0; i < M; i++) { cin >> a[i] >> b[i]; a[i]--; b[i]--; } for (auto i = 0; i < N - 1; i++) { V[a[i]].push_back(edge(b[i], i)); V[b[i]].push_back(edge(a[i], i)); } for (auto i = N - 1; i < M; i++) { edge from[20]; fill(from, from + 20, edge(-1, -1)); stack<info> S; S.push(info(a[i], -1, -1)); while (!S.empty()) { info e = S.top(); int dst = get<0>(e); int src = get<1>(e); int num = get<2>(e); S.pop(); if (from[dst] == edge(-1, -1)) { from[dst] = edge(src, num); if (dst == b[i]) { break; } for (auto x : V[dst]) { int next = get<0>(x); int next_num = get<1>(x); if (from[next] == edge(-1, -1)) { S.push(info(next, dst, next_num)); } } } } int mask = 0; int temp = b[i]; while (temp != a[i]) { int num = get<1>(from[temp]); mask += (1 << num); temp = get<0>(from[temp]); } int x = (1 << N) - mask; ll score = 0; for (auto i = 0; i < N; i++) { if ((x >> i) & 1) { score++; } } memo[mask].push_back(i); } #if DEBUG == 1 for (auto i = 0; i < (1 << N); i++) { cerr << "sets[" << i << "] = {"; for (auto x : sets[i]) { cerr << x << ", "; } cerr << "}" << endl; } #endif ll ans = (fact[N] * fact[M]) % MOD; }<|endoftext|>
<commit_before> #include "stdafx.h" #include "2DTransform.h" #include "math/Math.h" #include <vector> #include <algorithm> using namespace std; #define MAX_LOADSTRING 100 HINSTANCE hInst; HWND g_hWnd; TCHAR szTitle[MAX_LOADSTRING]; TCHAR szWindowClass[MAX_LOADSTRING]; vector<Vector3> g_vertices1; vector<Vector3> g_vertices2; Matrix44 g_matWorld1; Matrix44 g_matLocal1; Matrix44 g_matWorld2; Matrix44 g_matLocal2; Matrix44 g_matWorld3; Matrix44 g_matLocal3; ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); void MainLoop(int elapse_time); void Render(HWND hWnd); void Paint(HWND hWnd, HDC hdc); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_MY2DTRANSFORM, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // vertices1 // (-50,-50) ----------------- (+50, -50) // | | // | + | // | | // (-50,+50) ----------------- (+50, +50) const float w = 50.f; g_vertices1.push_back( Vector3(-w,-w,1) ); g_vertices1.push_back( Vector3(w,-w,1) ); g_vertices1.push_back( Vector3(w,w,1) ); g_vertices1.push_back( Vector3(-w,w,1) ); g_vertices1.push_back( Vector3(-w,-w,1) ); // vertices2 // +(0,0) ----------------- (+100, 0) // | | // | | // | | // (0,+100) ------------- (+1-0, +100) const float w2 = 100.f; g_vertices2.push_back( Vector3(0,0,1) ); g_vertices2.push_back( Vector3(w2,0,1) ); g_vertices2.push_back( Vector3(w2,w2,1) ); g_vertices2.push_back( Vector3(0,w2,1) ); g_vertices2.push_back( Vector3(0,0,1) ); g_matWorld1.SetIdentity(); g_matWorld1.Translate(Vector3(150,200,0)); g_matLocal1.SetIdentity(); g_matWorld2.SetIdentity(); g_matWorld2.Translate(Vector3(400,200,0)); g_matLocal2.SetIdentity(); g_matWorld3.SetIdentity(); g_matWorld3.Translate(Vector3(600,200,0)); g_matLocal3.SetIdentity(); if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } MSG msg; HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MY2DTRANSFORM)); int oldT = GetTickCount(); while (1) { if (PeekMessageA(&msg, NULL, 0, 0, PM_REMOVE)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } if(msg.message == WM_QUIT) break; } const int curT = GetTickCount(); const int elapseT = curT - oldT; if (elapseT > 30) { oldT = curT; MainLoop(elapseT); } } return (int) msg.wParam; } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MY2DTRANSFORM)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); //wcex.lpszMenuName = MAKEINTRESOURCE(IDC_MY2DTRANSFORM); wcex.lpszMenuName = NULL; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; g_hWnd = hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); switch (wmId) { case IDM_ABOUT: break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_ERASEBKGND: return 1; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); Paint(hWnd, ps.hdc); EndPaint(hWnd, &ps); break; case WM_KEYDOWN: switch (wParam) { case VK_LEFT: { Matrix44 mat; mat.SetRotationZ(0.1f); g_matLocal1 *= mat; } break; case VK_RIGHT: { Matrix44 mat; mat.SetRotationZ(-0.1f); g_matLocal1 *= mat; } break; } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } /** @brief */ void MainLoop(int elapse_time) { Matrix44 mat2; mat2.SetRotationZ(1.f * (elapse_time*0.001f)); g_matLocal2 *= mat2; Matrix44 mat3; mat3.SetRotationZ(-4.f * (elapse_time*0.001f)); g_matLocal3 *= mat3; static int incT = 0; incT += elapse_time; Vector3 pos(0, sin(incT*0.001f)*200.f, 0); Matrix44 matT3; matT3.SetIdentity(); matT3.Translate( Vector3(600,200,0) + pos ); g_matWorld3 = matT3; // Render Render(g_hWnd); ::InvalidateRect(g_hWnd, NULL, TRUE); } /** @brief */ void Render(HWND hWnd) { HDC hdc = GetDC(hWnd); Paint(hWnd, hdc); ::ReleaseDC(hWnd, hdc); } void RenderVertices(HDC hdc, const vector<Vector3> &vertices, const Matrix44 &tm) { for (unsigned int i=0; i < vertices.size(); ++i) { Vector3 p = vertices[ i]; p = p * tm; if (0 == i) MoveToEx(hdc, (int)p.x, (int)p.y, NULL); else LineTo(hdc, (int)p.x, (int)p.y); } } /** @brief */ void Paint(HWND hWnd, HDC hdc) { RECT rc; GetClientRect(hWnd, &rc); HDC hdcMem = CreateCompatibleDC(hdc); HBITMAP hbmMem = CreateCompatibleBitmap(hdc, rc.right-rc.left, rc.bottom-rc.top); HBITMAP hbmOld = (HBITMAP)SelectObject(hdcMem, hbmMem); HBRUSH hbrBkGnd = CreateSolidBrush(GetSysColor(COLOR_WINDOW)); FillRect(hdcMem, &rc, hbrBkGnd); DeleteObject(hbrBkGnd); RenderVertices(hdcMem, g_vertices1, g_matLocal1 * g_matWorld1); RenderVertices(hdcMem, g_vertices2, g_matLocal2 * g_matWorld2); RenderVertices(hdcMem, g_vertices1, g_matLocal3 * g_matWorld3); BitBlt(hdc, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); DeleteObject(hbmMem); DeleteDC(hdcMem); } <commit_msg>update<commit_after> #include "stdafx.h" #include "2DTransform.h" #include "math/Math.h" #include <vector> #include <algorithm> using namespace std; #define MAX_LOADSTRING 100 HINSTANCE hInst; HWND g_hWnd; TCHAR szTitle[MAX_LOADSTRING]; TCHAR szWindowClass[MAX_LOADSTRING]; vector<Vector3> g_vertices1; vector<Vector3> g_vertices2; Matrix44 g_matWorld1; Matrix44 g_matLocal1; Matrix44 g_matWorld2; Matrix44 g_matLocal2; Matrix44 g_matWorld3; Matrix44 g_matLocal3; ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); void MainLoop(int elapse_time); void Render(HWND hWnd); void Paint(HWND hWnd, HDC hdc); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_MY2DTRANSFORM, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // vertices1 // (-50,-50) ----------------- (+50, -50) // | | // | + | // | | // (-50,+50) ----------------- (+50, +50) const float w = 50.f; g_vertices1.push_back( Vector3(-w,-w,1) ); g_vertices1.push_back( Vector3(w,-w,1) ); g_vertices1.push_back( Vector3(w,w,1) ); g_vertices1.push_back( Vector3(-w,w,1) ); g_vertices1.push_back( Vector3(-w,-w,1) ); // vertices2 // +(0,0) ----------------- (+100, 0) // | | // | | // | | // (0,+100) ------------- (+1-0, +100) const float w2 = 100.f; g_vertices2.push_back( Vector3(0,0,1) ); g_vertices2.push_back( Vector3(w2,0,1) ); g_vertices2.push_back( Vector3(w2,w2,1) ); g_vertices2.push_back( Vector3(0,w2,1) ); g_vertices2.push_back( Vector3(0,0,1) ); g_matWorld1.SetIdentity(); g_matWorld1.Translate(Vector3(150,200,0)); g_matLocal1.SetIdentity(); g_matWorld2.SetIdentity(); g_matWorld2.Translate(Vector3(400,200,0)); g_matLocal2.SetIdentity(); g_matWorld3.SetIdentity(); g_matWorld3.Translate(Vector3(600,200,0)); g_matLocal3.SetIdentity(); if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } MSG msg; HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MY2DTRANSFORM)); int oldT = GetTickCount(); while (1) { if (PeekMessageA(&msg, NULL, 0, 0, PM_REMOVE)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } if(msg.message == WM_QUIT) break; } const int curT = GetTickCount(); const int elapseT = curT - oldT; if (elapseT > 30) { oldT = curT; MainLoop(elapseT); } } return (int) msg.wParam; } ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MY2DTRANSFORM)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); //wcex.lpszMenuName = MAKEINTRESOURCE(IDC_MY2DTRANSFORM); wcex.lpszMenuName = NULL; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; g_hWnd = hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); switch (wmId) { case IDM_ABOUT: break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_ERASEBKGND: return 1; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); Paint(hWnd, hdc); EndPaint(hWnd, &ps); break; case WM_KEYDOWN: switch (wParam) { case VK_LEFT: { Matrix44 mat; mat.SetRotationZ(0.1f); g_matLocal1 *= mat; } break; case VK_RIGHT: { Matrix44 mat; mat.SetRotationZ(-0.1f); g_matLocal1 *= mat; } break; } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } /** @brief */ void MainLoop(int elapse_time) { Matrix44 mat2; mat2.SetRotationZ(1.f * (elapse_time*0.001f)); g_matLocal2 *= mat2; Matrix44 mat3; mat3.SetRotationZ(-4.f * (elapse_time*0.001f)); g_matLocal3 *= mat3; static int incT = 0; incT += elapse_time; Vector3 pos(0, sin(incT*0.001f)*200.f, 0); Matrix44 matT3; matT3.SetIdentity(); matT3.Translate( Vector3(600,200,0) + pos ); g_matWorld3 = matT3; // Render Render(g_hWnd); ::InvalidateRect(g_hWnd, NULL, TRUE); } /** @brief */ void Render(HWND hWnd) { HDC hdc = GetDC(hWnd); Paint(hWnd, hdc); ::ReleaseDC(hWnd, hdc); } void RenderVertices(HDC hdc, const vector<Vector3> &vertices, const Matrix44 &tm) { for (unsigned int i=0; i < vertices.size(); ++i) { Vector3 p = vertices[ i]; p = p * tm; if (0 == i) MoveToEx(hdc, (int)p.x, (int)p.y, NULL); else LineTo(hdc, (int)p.x, (int)p.y); } } /** @brief */ void Paint(HWND hWnd, HDC hdc) { RECT rc; GetClientRect(hWnd, &rc); HDC hdcMem = CreateCompatibleDC(hdc); HBITMAP hbmMem = CreateCompatibleBitmap(hdc, rc.right-rc.left, rc.bottom-rc.top); HBITMAP hbmOld = (HBITMAP)SelectObject(hdcMem, hbmMem); HBRUSH hbrBkGnd = CreateSolidBrush(GetSysColor(COLOR_WINDOW)); FillRect(hdcMem, &rc, hbrBkGnd); DeleteObject(hbrBkGnd); RenderVertices(hdcMem, g_vertices1, g_matLocal1 * g_matWorld1); RenderVertices(hdcMem, g_vertices2, g_matLocal2 * g_matWorld2); RenderVertices(hdcMem, g_vertices1, g_matLocal3 * g_matWorld3); BitBlt(hdc, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, hbmOld); DeleteObject(hbmMem); DeleteDC(hdcMem); } <|endoftext|>
<commit_before>/* * Location2.cpp * * Created on: Nov 7, 2016 * Author: szsz */ #include "Location2.h" Location2::Location2(LoggerPtr logger, Settings *settings) { _logger = logger; _settings = settings; LOG4CXX_INFO(_logger, "Location 2"); this->Pos_X = 0; this->Pos_Y = 0; this->Prop = 0; this->Pos_Alfa = 0; this->timeStamp = 0; LOG4CXX_INFO(_logger, "Before: AmberClient UdpClient"); AmberClientRoboClaw = new UdpClient(settings->RobotIP, 26233); AmberClientHokuyo = new UdpClient(settings->RobotIP, 26233); LOG4CXX_INFO(_logger, "After: AmberClient UdpClient"); LOG4CXX_INFO(_logger, "Before: InitRoomsTable"); InitRoomsTable(settings->PathMap); LOG4CXX_INFO(_logger, "After: InitRoomsTable"); LOG4CXX_INFO(_logger, "Before: RoboclawProxy()"); RoboClaw = new RoboclawProxy(_logger, AmberClientRoboClaw); LOG4CXX_INFO(_logger, "After: RoboclawProxy()"); LOG4CXX_INFO(_logger, "Before: HokuyoProxy()"); Hokuyo = new HokuyoProxy(_logger, AmberClientHokuyo, settings->SkipScan); LOG4CXX_INFO(_logger, "After: HokuyoProxy()"); kht = new KernelBasedHoughTransform(settings->maxMeasuredDistance, settings->houghResolution); NumberParticles = settings->NumberParticles; InitParticleTable(NumberParticles); IsWorking = true; #if DIAGNOSTIC_MODE == 1 diagnosticVisualisation = new DiagnosticVisualisation( new UdpClient(settings->DiagnosticIPAddress, 1234), settings->NumberParticles, Particles, RoboClaw, Hokuyo); #endif } Location2::~Location2() { LOG4CXX_INFO(_logger, "~Location"); delete Particles; delete kht; delete Hokuyo; delete RoboClaw; delete AmberClientHokuyo; delete AmberClientRoboClaw; #if DIAGNOSTIC_MODE == 1 delete diagnosticVisualisation; #endif } void Location2::InitRoomsTable(char *pathMap) { //tworzy pokoje //countRoomAndBox = parseJasonFile(pathMap,rooms); } void Location2::InitParticleTable(unsigned int numberParticles) { Particles = new Particle2[numberParticles](); //for (unsigned int i = 0; i < numberParticles; i++) // Particles[i] = new Particle2(); } void Location2::RunLocation() { LOG4CXX_INFO(_logger, "RunLocation"); struct timeval start, end; double speedRoboClaw; double angleRoboClaw; double deletaTime; double bestFitAngle; Room* currentRoom; InitDistributeParticles(); #if DIAGNOSTIC_MODE == 1 diagnosticVisualisation->Send(); #endif gettimeofday(&start, NULL); while (IsWorking) { gettimeofday(&end, NULL); deletaTime = ((end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000.0) / 1000; gettimeofday(&start, NULL); Hokuyo->GetScan(); speedRoboClaw = RoboClaw->GetSpeed(); //droga w metrach angleRoboClaw = RoboClaw->GetAngle(deletaTime); bestFitAngle = -kht->GetMainDirectionAngle(Hokuyo->GetAllAngles(), Hokuyo->GetAllDistances(), Hokuyo->ScanLengthAll); bestFitAngle = ConvertToRadian(bestFitAngle); for (unsigned int i = 0; i < NumberParticles; i++) { currentRoom = GetRoom(Particles[i].X, Particles[i].Y); } } } void Location2::InitDistributeParticles() { LOG4CXX_INFO(_logger, "InitDistributeParticles"); } double Location2::ConvertToRadian(double degree) { return ((degree * M_PI) / 180); } Room* Location2::GetRoom(double X, double Y) { for (int i = 0; i < RoomsLength; i++) { if ((X >= Rooms[i].Box.X_Left_Bottom) && (X <= Rooms[i].Box.X_Right_Bottom) && (Y >= Rooms[i].Box.Y_Left_Bottom) && (Y <= Rooms[i].Box.Y_Left_Top)) return &(Rooms[i]); } return NULL; } <commit_msg>Location2<commit_after>/* * Location2.cpp * * Created on: Nov 7, 2016 * Author: szsz */ #include "Location2.h" Location2::Location2(LoggerPtr logger, Settings *settings) { _logger = logger; _settings = settings; LOG4CXX_INFO(_logger, "Location 2"); this->Pos_X = 0; this->Pos_Y = 0; this->Prop = 0; this->Pos_Alfa = 0; this->timeStamp = 0; LOG4CXX_INFO(_logger, "Before: AmberClient UdpClient"); AmberClientRoboClaw = new UdpClient(settings->RobotIP, 26233); AmberClientHokuyo = new UdpClient(settings->RobotIP, 26233); LOG4CXX_INFO(_logger, "After: AmberClient UdpClient"); LOG4CXX_INFO(_logger, "Before: InitRoomsTable"); InitRoomsTable(settings->PathMap); LOG4CXX_INFO(_logger, "After: InitRoomsTable"); LOG4CXX_INFO(_logger, "Before: RoboclawProxy()"); RoboClaw = new RoboclawProxy(_logger, AmberClientRoboClaw); LOG4CXX_INFO(_logger, "After: RoboclawProxy()"); LOG4CXX_INFO(_logger, "Before: HokuyoProxy()"); Hokuyo = new HokuyoProxy(_logger, AmberClientHokuyo, settings->SkipScan); LOG4CXX_INFO(_logger, "After: HokuyoProxy()"); kht = new KernelBasedHoughTransform(settings->maxMeasuredDistance, settings->houghResolution); NumberParticles = settings->NumberParticles; InitParticleTable(NumberParticles); IsWorking = true; #if DIAGNOSTIC_MODE == 1 diagnosticVisualisation = new DiagnosticVisualisation( new UdpClient(settings->DiagnosticIPAddress, 1234), settings->NumberParticles, Particles, RoboClaw, Hokuyo); #endif } Location2::~Location2() { LOG4CXX_INFO(_logger, "~Location"); delete Particles; delete kht; delete Hokuyo; delete RoboClaw; delete AmberClientHokuyo; delete AmberClientRoboClaw; #if DIAGNOSTIC_MODE == 1 delete diagnosticVisualisation; #endif } void Location2::InitRoomsTable(char *pathMap) { //tworzy pokoje //countRoomAndBox = parseJasonFile(pathMap,rooms); } void Location2::InitParticleTable(unsigned int numberParticles) { Particles = new Particle2[numberParticles](); //for (unsigned int i = 0; i < numberParticles; i++) // Particles[i] = new Particle2(); } void Location2::RunLocation() { LOG4CXX_INFO(_logger, "RunLocation"); struct timeval start, end; double speedRoboClaw; double angleRoboClaw; double deletaTime; double bestFitAngle; Room* currentRoom; InitDistributeParticles(); #if DIAGNOSTIC_MODE == 1 diagnosticVisualisation->Send(); #endif gettimeofday(&start, NULL); while (IsWorking) { gettimeofday(&end, NULL); deletaTime = ((end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000.0) / 1000; gettimeofday(&start, NULL); Hokuyo->GetScan(); speedRoboClaw = RoboClaw->GetSpeed(); //droga w metrach angleRoboClaw = RoboClaw->GetAngle(deletaTime); bestFitAngle = -kht->GetMainDirectionAngle(Hokuyo->GetAllAngles(), Hokuyo->GetAllDistances(), Hokuyo->ScanLengthAll); bestFitAngle = ConvertToRadian(bestFitAngle); for (unsigned int i = 0; i < NumberParticles; i++) { currentRoom = GetRoom(Particles[i].X, Particles[i].Y); } } } void Location2::InitDistributeParticles() { LOG4CXX_INFO(_logger, "InitDistributeParticles"); } double Location2::ConvertToRadian(double degree) { return ((degree * M_PI) / 180); } Room* Location2::GetRoom(double X, double Y) { for (unsigned int i = 0; i < RoomsLength; i++) { if ((X >= Rooms[i].Box.X_Left_Bottom) && (X <= Rooms[i].Box.X_Right_Bottom) && (Y >= Rooms[i].Box.Y_Left_Bottom) && (Y <= Rooms[i].Box.Y_Left_Top)) return &(Rooms[i]); } return NULL; } <|endoftext|>
<commit_before>/** ========================================================================== * 2011 by KjellKod.cc, modified by Vrecan in https://bitbucket.org/vrecan/g2log-dev * 2015, adopted by KjellKod for g3log at:https://github.com/KjellKod/g3sinks * * This code is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * ============================================================================* * PUBLIC DOMAIN and Not copywrited. First published at KjellKod.cc * ********************************************* */ #pragma once #include <cstdio> #include <string> #include <memory> #include <fstream> #include <algorithm> #include <future> #include <cassert> #include <chrono> #include <g3log/time.hpp> #include <zlib.h> #include <boost/filesystem.hpp> #include <boost/regex.hpp> #include <map> #include <vector> #include <ctime> #include <iostream> namespace { using steady_time_point = std::chrono::time_point<std::chrono::steady_clock>; static const std::string file_name_time_formatted = "%Y%m%d-%H%M%S"; // check for filename validity - filename should not be part of PATH bool isValidFilename(const std::string& prefix_filename) { std::string illegal_characters("/,|<>:#$%{}()[]\'\"^!?+* "); size_t pos = prefix_filename.find_first_of(illegal_characters, 0); if (pos != std::string::npos) { std::cerr << "Illegal character [" << prefix_filename.at(pos) << "] in logname prefix: " << "[" << prefix_filename << "]" << std::endl; return false; } else if (prefix_filename.empty()) { std::cerr << "Empty filename prefix is not allowed" << std::endl; return false; } return true; } /// @return a corrected prefix, if needed, /// illegal characters are removed from @param prefix input std::string prefixSanityFix(std::string prefix) { prefix.erase(std::remove_if(prefix.begin(), prefix.end(), ::isspace), prefix.end()); prefix.erase(std::remove(prefix.begin(), prefix.end(), '/'), prefix.end()); // '/' prefix.erase(std::remove(prefix.begin(), prefix.end(), '\\'), prefix.end()); // '\\' prefix.erase(std::remove(prefix.begin(), prefix.end(), '.'), prefix.end()); // '.' if (!isValidFilename(prefix)) { return ""; } return prefix; } /// @return the file header std::string header() { std::ostringstream ss_entry; // Day Month Date Time Year: is written as "%a %b %d %H:%M:%S %Y" and formatted output as : Wed Sep 19 08:28:16 2012 ss_entry << "\ng3log: created log file at: " << g3::localtime_formatted(g3::systemtime_now(), "%a %b %d %H:%M:%S %Y") << "\n"; return ss_entry.str(); } /// @return result as time from the file name bool getDateFromFileName(const std::string& app_name, const std::string& file_name, long& result) { if (file_name.find(app_name) != std::string::npos) { std::string suffix = file_name.substr(app_name.size()); if (suffix.empty()) { //this is the main log file return false; } boost::regex date_regex("\\.(\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2}-\\d{2})\\.gz"); boost::smatch date_match; if (boost::regex_match(suffix, date_match, date_regex)) { if (date_match.size() == 2) { std::string date = date_match[1].str(); struct tm tm; time_t t; if (strptime(date.c_str(), "%Y-%m-%d-%H-%M-%S", &tm) == NULL) { return false; } t = mktime(&tm); if (t == -1) { return false; } result = (long) t; return true; } } } return false; } /** * Loop through the files in the folder * @param dir * @param file_name */ void expireArchives(const std::string dir, const std::string& app_name, unsigned long max_log_count) { std::map<long, std::string> files; boost::filesystem::path dir_path(dir); if (!boost::filesystem::exists(dir_path)) return; boost::filesystem::directory_iterator end_itr; for (boost::filesystem::directory_iterator itr(dir_path); itr != end_itr; ++itr) { std::string current_file(itr->path().filename().c_str()); long time; if (getDateFromFileName(app_name, current_file, time)) { files.insert(std::pair<long, std::string > (time, current_file)); } } //delete old logs. int logs_to_delete = files.size() - max_log_count; if (logs_to_delete > 0) { for (std::map<long, std::string>::iterator it = files.begin(); it != files.end(); ++it) { if (logs_to_delete <= 0) { break; } std::stringstream ss; ss << dir.c_str() << it->second.c_str(); remove(ss.str().c_str()); --logs_to_delete; } } } /// create the file name std::string createLogFileName(const std::string& verified_prefix) { std::stringstream oss_name; oss_name << verified_prefix << ".log"; return oss_name.str(); } /// @return true if @param complete_file_with_path could be opened /// @param outstream is the file stream bool openLogFile(const std::string& complete_file_with_path, std::ofstream& outstream) { std::ios_base::openmode mode = std::ios_base::out; // for clarity: it's really overkill since it's an ofstream mode |= std::ios_base::app; outstream.open(complete_file_with_path, mode); if (!outstream.is_open()) { std::ostringstream ss_error; ss_error << "FILE ERROR: could not open log file:[" << complete_file_with_path << "]"; ss_error << "\n\t\t std::ios_base state = " << outstream.rdstate(); std::cerr << ss_error.str().c_str() << std::endl; outstream.close(); return false; } return true; } /// create the file std::unique_ptr<std::ofstream> createLogFile(const std::string& file_with_full_path) { std::unique_ptr<std::ofstream> out(new std::ofstream); std::ofstream& stream(*(out.get())); bool success_with_open_file = openLogFile(file_with_full_path, stream); if (false == success_with_open_file) { out.release(); } return out; } } // anonymous /** The Real McCoy Background worker, while g3::LogWorker gives the * asynchronous API to put job in the background the LogRotateHelper * does the actual background thread work */ struct LogRotateHelper { LogRotateHelper& operator=(const LogRotateHelper&) = delete; LogRotateHelper(const LogRotateHelper& other) = delete; LogRotateHelper(const std::string& log_prefix, const std::string& log_directory); ~LogRotateHelper(); void setMaxArchiveLogCount(int size); void setMaxLogSize(int size); void fileWrite(std::string message); std::string changeLogFile(const std::string& directory, const std::string& new_name = ""); std::string logFileName(); bool archiveLog(); void addLogFileHeader(); bool rotateLog(); bool createCompressedFile(std::string file_name, std::string gzip_file_name); std::ofstream& filestream() { return *(outptr_.get()); } std::string log_file_with_path_; std::string log_directory_; std::string log_prefix_backup_; std::unique_ptr<std::ofstream> outptr_; steady_time_point steady_start_time_; int max_log_size_; int max_archive_log_count_; int cur_log_size_; }; LogRotateHelper::LogRotateHelper(const std::string& log_prefix, const std::string& log_directory) : log_file_with_path_(log_directory) , log_directory_(log_directory) , log_prefix_backup_(log_prefix) , outptr_(new std::ofstream) , steady_start_time_(std::chrono::steady_clock::now()) { // TODO: ha en timer function steadyTimer som har koll på start log_prefix_backup_ = prefixSanityFix(log_prefix); max_log_size_ = 524288000; max_archive_log_count_ = 10; if (!isValidFilename(log_prefix_backup_)) { std::cerr << "g3log: forced abort due to illegal log prefix [" << log_prefix << "]" << std::endl; abort(); } std::string file_name = createLogFileName(log_prefix_backup_); log_file_with_path_ = log_directory + file_name; outptr_ = createLogFile(log_file_with_path_); assert((nullptr != outptr_) && "cannot open log file at startup"); addLogFileHeader(); std::ofstream& is(filestream()); is.seekp(0, std::ios::end); cur_log_size_ = is.tellp(); is.seekp(0, std::ios::beg); } /** * Max number of archived logs to keep. * @param max_size */ void LogRotateHelper::setMaxArchiveLogCount(int max_size) { max_archive_log_count_ = max_size; } /** * Set the max file size in bytes. * @param max_size */ void LogRotateHelper::setMaxLogSize(int max_size) { max_log_size_ = max_size; } LogRotateHelper::~LogRotateHelper() { std::ostringstream ss_exit; ss_exit << "\ng3log file shutdown at: " << g3::localtime_formatted(g3::systemtime_now(), g3::internal::time_formatted) << "\n\n"; filestream() << ss_exit.str() << std::flush; } void LogRotateHelper::fileWrite(std::string message) { rotateLog(); std::ofstream& out(filestream()); out << message;// << std::flush; cur_log_size_ += message.size(); } std::string LogRotateHelper::changeLogFile(const std::string& directory, const std::string& new_name) { std::string file_name = new_name; if (file_name.empty()) { // std::cout << "no filename" << std::endl; file_name = createLogFileName(log_prefix_backup_); } std::string prospect_log = directory + file_name; std::unique_ptr<std::ofstream> log_stream = createLogFile(prospect_log); if (nullptr == log_stream) { fileWrite("Unable to change log file. Illegal filename or busy? Unsuccessful log name was:" + prospect_log); return ""; // no success } addLogFileHeader(); std::ofstream& is(filestream()); is.seekp(0, std::ios::end); cur_log_size_ = is.tellp(); is.seekp(0, std::ios::beg); std::string old_log = log_file_with_path_; log_file_with_path_ = prospect_log; outptr_ = std::move(log_stream); log_directory_ = directory; return log_file_with_path_; } /** * Rotate the logs once they have exceeded our set size. * @return */ bool LogRotateHelper::rotateLog() { std::ofstream& is(filestream()); if (is.is_open()) { if (cur_log_size_ > max_log_size_) { is << std::flush; std::ostringstream gz_file_name; gz_file_name << log_file_with_path_ << "."; gz_file_name << g3::localtime_formatted(g3::systemtime_now(), "%Y-%m-%d-%H-%M-%S"); gz_file_name << ".gz"; if (!createCompressedFile(log_file_with_path_, gz_file_name.str())) { fileWrite("Failed to compress log!"); return false; } is.close(); if (remove(log_file_with_path_.c_str()) == -1) { fileWrite("Failed to remove old log!"); } changeLogFile(log_directory_); std::ostringstream ss; ss << "Log rotated Archived file name: " << gz_file_name.str().c_str(); fileWrite(ss.str()); ss.clear(); ss.str(""); ss << log_prefix_backup_ << ".log"; expireArchives(log_directory_, ss.str(), max_archive_log_count_); return true; } } return false; } /** * Create a compressed file of the current log. * @param file_name * @param gzip_file_name * @return */ bool LogRotateHelper::createCompressedFile(std::string file_name, std::string gzip_file_name) { int buffer_size = 16184; char buffer[buffer_size]; FILE* input = fopen(file_name.c_str(), "rb"); gzFile output = gzopen(gzip_file_name.c_str(), "wb"); if (input == NULL || output == NULL) { return false; } int N; while ((N = fread(buffer, 1, buffer_size, input)) > 0) { gzwrite(output, buffer, N); } if (gzclose(output) != Z_OK); if (fclose(input) != 0) { return false; } return true; } std::string LogRotateHelper::logFileName() { return log_file_with_path_; } void LogRotateHelper::addLogFileHeader() { filestream() << header(); } <commit_msg>Update LogRotateHelper.ipp<commit_after>/** ========================================================================== * 2011 by KjellKod.cc, modified by Vrecan in https://bitbucket.org/vrecan/g2log-dev * 2015, adopted by KjellKod for g3log at:https://github.com/KjellKod/g3sinks * * This code is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * ============================================================================* * PUBLIC DOMAIN and Not copywrited. First published at KjellKod.cc * ********************************************* */ #pragma once #include <cstdio> #include <string> #include <memory> #include <fstream> #include <algorithm> #include <future> #include <cassert> #include <chrono> #include <g3log/time.hpp> #include <zlib.h> #include <boost/filesystem.hpp> #include <boost/regex.hpp> #include <map> #include <vector> #include <ctime> #include <iostream> namespace { using steady_time_point = std::chrono::time_point<std::chrono::steady_clock>; static const std::string file_name_time_formatted = "%Y%m%d-%H%M%S"; // check for filename validity - filename should not be part of PATH bool isValidFilename(const std::string& prefix_filename) { std::string illegal_characters("/,|<>:#$%{}()[]\'\"^!?+* "); size_t pos = prefix_filename.find_first_of(illegal_characters, 0); if (pos != std::string::npos) { std::cerr << "Illegal character [" << prefix_filename.at(pos) << "] in logname prefix: " << "[" << prefix_filename << "]" << std::endl; return false; } else if (prefix_filename.empty()) { std::cerr << "Empty filename prefix is not allowed" << std::endl; return false; } return true; } /// @return a corrected prefix, if needed, /// illegal characters are removed from @param prefix input std::string prefixSanityFix(std::string prefix) { prefix.erase(std::remove_if(prefix.begin(), prefix.end(), ::isspace), prefix.end()); prefix.erase(std::remove(prefix.begin(), prefix.end(), '/'), prefix.end()); // '/' prefix.erase(std::remove(prefix.begin(), prefix.end(), '\\'), prefix.end()); // '\\' prefix.erase(std::remove(prefix.begin(), prefix.end(), '.'), prefix.end()); // '.' if (!isValidFilename(prefix)) { return ""; } return prefix; } /// @return the file header std::string header() { std::ostringstream ss_entry; // Day Month Date Time Year: is written as "%a %b %d %H:%M:%S %Y" and formatted output as : Wed Sep 19 08:28:16 2012 ss_entry << "\ng3log: created log file at: " << g3::localtime_formatted(g3::systemtime_now(), "%a %b %d %H:%M:%S %Y") << "\n"; return ss_entry.str(); } /// @return result as time from the file name bool getDateFromFileName(const std::string& app_name, const std::string& file_name, long& result) { if (file_name.find(app_name) != std::string::npos) { std::string suffix = file_name.substr(app_name.size()); if (suffix.empty()) { //this is the main log file return false; } boost::regex date_regex("\\.(\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2}-\\d{2})\\.gz"); boost::smatch date_match; if (boost::regex_match(suffix, date_match, date_regex)) { if (date_match.size() == 2) { std::string date = date_match[1].str(); struct tm tm; time_t t; if (strptime(date.c_str(), "%Y-%m-%d-%H-%M-%S", &tm) == NULL) { return false; } t = mktime(&tm); if (t == -1) { return false; } result = (long) t; return true; } } } return false; } /** * Loop through the files in the folder * @param dir * @param file_name */ void expireArchives(const std::string dir, const std::string& app_name, unsigned long max_log_count) { std::map<long, std::string> files; boost::filesystem::path dir_path(dir); if (!boost::filesystem::exists(dir_path)) return; boost::filesystem::directory_iterator end_itr; for (boost::filesystem::directory_iterator itr(dir_path); itr != end_itr; ++itr) { std::string current_file(itr->path().filename().c_str()); long time; if (getDateFromFileName(app_name, current_file, time)) { files.insert(std::pair<long, std::string > (time, current_file)); } } //delete old logs. int logs_to_delete = files.size() - max_log_count; if (logs_to_delete > 0) { for (std::map<long, std::string>::iterator it = files.begin(); it != files.end(); ++it) { if (logs_to_delete <= 0) { break; } std::stringstream ss; ss << dir.c_str() << it->second.c_str(); remove(ss.str().c_str()); --logs_to_delete; } } } /// create the file name std::string createLogFileName(const std::string& verified_prefix) { std::stringstream oss_name; oss_name << verified_prefix << ".log"; return oss_name.str(); } /// @return true if @param complete_file_with_path could be opened /// @param outstream is the file stream bool openLogFile(const std::string& complete_file_with_path, std::ofstream& outstream) { std::ios_base::openmode mode = std::ios_base::out; // for clarity: it's really overkill since it's an ofstream mode |= std::ios_base::app; outstream.open(complete_file_with_path, mode); if (!outstream.is_open()) { std::ostringstream ss_error; ss_error << "FILE ERROR: could not open log file:[" << complete_file_with_path << "]"; ss_error << "\n\t\t std::ios_base state = " << outstream.rdstate(); std::cerr << ss_error.str().c_str() << std::endl; outstream.close(); return false; } return true; } /// create the file std::unique_ptr<std::ofstream> createLogFile(const std::string& file_with_full_path) { std::unique_ptr<std::ofstream> out(new std::ofstream); std::ofstream& stream(*(out.get())); bool success_with_open_file = openLogFile(file_with_full_path, stream); if (false == success_with_open_file) { out.release(); } return out; } } // anonymous /** The Real McCoy Background worker, while g3::LogWorker gives the * asynchronous API to put job in the background the LogRotateHelper * does the actual background thread work */ struct LogRotateHelper { LogRotateHelper& operator=(const LogRotateHelper&) = delete; LogRotateHelper(const LogRotateHelper& other) = delete; LogRotateHelper(const std::string& log_prefix, const std::string& log_directory); ~LogRotateHelper(); void setMaxArchiveLogCount(int size); void setMaxLogSize(int size); void fileWrite(std::string message); std::string changeLogFile(const std::string& directory, const std::string& new_name = ""); std::string logFileName(); bool archiveLog(); void addLogFileHeader(); bool rotateLog(); bool createCompressedFile(std::string file_name, std::string gzip_file_name); std::ofstream& filestream() { return *(outptr_.get()); } std::string log_file_with_path_; std::string log_directory_; std::string log_prefix_backup_; std::unique_ptr<std::ofstream> outptr_; steady_time_point steady_start_time_; int max_log_size_; int max_archive_log_count_; int cur_log_size_; }; LogRotateHelper::LogRotateHelper(const std::string& log_prefix, const std::string& log_directory) : log_file_with_path_(log_directory) , log_directory_(log_directory) , log_prefix_backup_(log_prefix) , outptr_(new std::ofstream) , steady_start_time_(std::chrono::steady_clock::now()) { // TODO: ha en timer function steadyTimer som har koll på start log_prefix_backup_ = prefixSanityFix(log_prefix); max_log_size_ = 524288000; max_archive_log_count_ = 10; if (!isValidFilename(log_prefix_backup_)) { std::cerr << "g3log: forced abort due to illegal log prefix [" << log_prefix << "]" << std::endl; abort(); } std::string file_name = createLogFileName(log_prefix_backup_); log_file_with_path_ = log_directory + file_name; outptr_ = createLogFile(log_file_with_path_); assert((nullptr != outptr_) && "cannot open log file at startup"); addLogFileHeader(); std::ofstream& is(filestream()); is.seekp(0, std::ios::end); cur_log_size_ = is.tellp(); is.seekp(0, std::ios::beg); } /** * Max number of archived logs to keep. * @param max_size */ void LogRotateHelper::setMaxArchiveLogCount(int max_size) { max_archive_log_count_ = max_size; } /** * Set the max file size in bytes. * @param max_size */ void LogRotateHelper::setMaxLogSize(int max_size) { max_log_size_ = max_size; } LogRotateHelper::~LogRotateHelper() { std::ostringstream ss_exit; ss_exit << "\ng3log file shutdown at: " << g3::localtime_formatted(g3::systemtime_now(), g3::internal::time_formatted) << "\n\n"; filestream() << ss_exit.str() << std::flush; } void LogRotateHelper::fileWrite(std::string message) { rotateLog(); std::ofstream& out(filestream()); out << message;// << std::flush; cur_log_size_ += message.size(); } std::string LogRotateHelper::changeLogFile(const std::string& directory, const std::string& new_name) { std::string file_name = new_name; if (file_name.empty()) { //std::cout << "no filename" << std::endl; file_name = log_prefix_backup_; } std::string prospect_log = createLogFileName(directory + file_name); std::unique_ptr<std::ofstream> log_stream = createLogFile(prospect_log); if (nullptr == log_stream) { fileWrite("Unable to change log file. Illegal filename or busy? Unsuccessful log name was:" + prospect_log); return ""; // no success } log_prefix_backup_ = file_name; addLogFileHeader(); std::ofstream& is(filestream()); is.seekp(0, std::ios::end); cur_log_size_ = is.tellp(); is.seekp(0, std::ios::beg); std::string old_log = log_file_with_path_; log_file_with_path_ = prospect_log; outptr_ = std::move(log_stream); log_directory_ = directory; return log_file_with_path_; } /** * Rotate the logs once they have exceeded our set size. * @return */ bool LogRotateHelper::rotateLog() { std::ofstream& is(filestream()); if (is.is_open()) { if (cur_log_size_ > max_log_size_) { is << std::flush; std::ostringstream gz_file_name; gz_file_name << log_file_with_path_ << "."; gz_file_name << g3::localtime_formatted(g3::systemtime_now(), "%Y-%m-%d-%H-%M-%S"); gz_file_name << ".gz"; if (!createCompressedFile(log_file_with_path_, gz_file_name.str())) { fileWrite("Failed to compress log!"); return false; } is.close(); if (remove(log_file_with_path_.c_str()) == -1) { fileWrite("Failed to remove old log!"); } changeLogFile(log_directory_); std::ostringstream ss; ss << "Log rotated Archived file name: " << gz_file_name.str().c_str(); fileWrite(ss.str()); ss.clear(); ss.str(""); ss << log_prefix_backup_ << ".log"; expireArchives(log_directory_, ss.str(), max_archive_log_count_); return true; } } return false; } /** * Create a compressed file of the current log. * @param file_name * @param gzip_file_name * @return */ bool LogRotateHelper::createCompressedFile(std::string file_name, std::string gzip_file_name) { int buffer_size = 16184; char buffer[buffer_size]; FILE* input = fopen(file_name.c_str(), "rb"); gzFile output = gzopen(gzip_file_name.c_str(), "wb"); if (input == NULL || output == NULL) { return false; } int N; while ((N = fread(buffer, 1, buffer_size, input)) > 0) { gzwrite(output, buffer, N); } if (gzclose(output) != Z_OK); if (fclose(input) != 0) { return false; } return true; } std::string LogRotateHelper::logFileName() { return log_file_with_path_; } void LogRotateHelper::addLogFileHeader() { filestream() << header(); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/diag/prdf/common/plugins/prdfParserUtils.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2021 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <prdfParserUtils.H> #include <prdfParserEnums.H> namespace PRDF { #if defined(PRDF_HOSTBOOT_ERRL_PLUGIN) namespace HOSTBOOT { #elif defined(PRDF_FSP_ERRL_PLUGIN) namespace FSP { #endif namespace PARSERUTILS { //------------------------------------------------------------------------------ template<> uint8_t symbol2Dq<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_symbol ) { uint8_t dq = OCMB_DQS_PER_DIMM; static const uint8_t symbol2dq[] = { 39, 38, 37, 36, 35, 34, 33, 32, // symbols 0- 7 79, 78, 77, 76, 71, 70, 69, 68, // symbols 8-15 63, 62, 61, 60, 55, 54, 53, 52, // symbols 16-23 31, 30, 29, 28, 23, 22, 21, 20, // symbols 24-31 15, 14, 13, 12, 7, 6, 5, 4, // symbols 32-39 75, 74, 73, 72, 67, 66, 65, 64, // symbols 40-47 59, 58, 57, 56, 51, 50, 49, 48, // symbols 48-55 27, 26, 25, 24, 19, 18, 17, 16, // symbols 56-63 11, 10, 9, 8, 3, 2, 1, 0, // symbols 64-71 }; if ( SYMBOLS_PER_RANK > i_symbol ) { dq = symbol2dq[i_symbol]; } return dq; } //------------------------------------------------------------------------------ template<> uint8_t symbol2PortSlct<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_symbol ) { // TODO RTC 210072 - Explorer only has one port, as such we can just // return 0. However, multiple ports will be supported in the future, // We'll need to figure out how to convert the symbol to a port select for // OCMB at that time. return 0; } //------------------------------------------------------------------------------ template<TARGETING::TYPE T> uint8_t dq2Symbol( uint8_t i_dq, uint8_t i_ps ) { uint8_t symbol = SYMBOLS_PER_RANK; static const uint8_t sp = SYMBOLS_PER_RANK; // Spare symbols static const uint8_t dq2symbol[] = { 71, 70, 69, 68, 39, 38, 37, 36, // dqs 0- 7 67, 66, 65, 64, 35, 34, 33, 32, // dqs 8-15 63, 62, 61, 60, 31, 30, 29, 28, // dqs 16-23 59, 58, 57, 56, 27, 26, 25, 24, // dqs 24-31 7, 6, 5, 4, 3, 2, 1, 0, // dqs 32-39 sp, sp, sp, sp, sp, sp, sp, sp, // dqs 40-47 - spare 55, 54, 53, 52, 23, 22, 21, 20, // dqs 48-55 51, 50, 49, 48, 19, 18, 17, 16, // dqs 56-63 47, 46, 45, 44, 15, 14, 13, 12, // dqs 64-71 43, 42, 41, 40, 11, 10, 9, 8, // dqs 72-80 }; if ( OCMB_DQS_PER_DIMM > i_dq ) { symbol = dq2symbol[i_dq]; } return symbol; } template uint8_t dq2Symbol<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_dq, uint8_t i_ps ); template uint8_t dq2Symbol<TARGETING::TYPE_MEM_PORT>( uint8_t i_dq, uint8_t i_ps ); //------------------------------------------------------------------------------ template<> uint8_t nibble2Symbol<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_x4Dram ) { uint8_t symbol = SYMBOLS_PER_RANK; static const uint8_t sp = SYMBOLS_PER_RANK; // Spare symbols static const uint8_t nibble2symbol[] = { 68, 36, 64, 32, 60, // nibbles 0-4 28, 56, 24, 4, 0, // nibbles 5-9 sp, sp, 52, 20, 48, // nibbles 10-14 16, 44, 12, 40, 8, // nibbles 15-19 }; if ( NIBBLES_PER_DIMM > i_x4Dram ) { symbol = nibble2symbol[i_x4Dram]; } return symbol; } //------------------------------------------------------------------------------ template<> uint8_t byte2Symbol<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_x8Dram ) { uint8_t symbol = SYMBOLS_PER_RANK; static const uint8_t sp = SYMBOLS_PER_RANK; // Spare symbols static const uint8_t byte2symbol[] = { 36, 32, 28, 24, 0, // bytes 0-4 sp, 20, 16, 12, 8, // bytes 5-9 }; if ( BYTES_PER_DIMM > i_x8Dram ) { symbol = byte2symbol[i_x8Dram]; } return symbol; } //------------------------------------------------------------------------------ template<> uint8_t symbol2Nibble<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_symbol ) { uint8_t nibble = NIBBLES_PER_DIMM; // There are 4 symbols per nibble, always grouped together, so divide // by 4 here to simplify our conversion table. uint8_t tmp = i_symbol/4; static const uint8_t symbol2nibble[] = { 17, 16, 15, 13, // symbols 0-15 11, 9, 7, 5, // symbols 16-31 3, 1, 14, 12, // symbols 32-47 10, 8, 6, 4, // symbols 48-63 2, 0, // symbols 64-71 }; if ( SYMBOLS_PER_RANK > i_symbol ) { nibble = symbol2nibble[tmp]; } return nibble; } //------------------------------------------------------------------------------ template<> uint8_t symbol2Byte<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_symbol ) { return (SYMBOLS_PER_RANK > i_symbol) ? (symbol2Nibble<TARGETING::TYPE_OCMB_CHIP>(i_symbol)/2) : MEM_BYTES_PER_RANK; } //------------------------------------------------------------------------------ template<> uint8_t dram2Symbol<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_dram, bool i_isX4Dram ) { return (true == i_isX4Dram) ? nibble2Symbol<TARGETING::TYPE_OCMB_CHIP>(i_dram) : byte2Symbol<TARGETING::TYPE_OCMB_CHIP>(i_dram); } //------------------------------------------------------------------------------ template<> uint8_t symbol2Dram<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_symbol, bool i_isX4Dram ) { return (true == i_isX4Dram) ? symbol2Nibble<TARGETING::TYPE_OCMB_CHIP>(i_symbol) : symbol2Byte<TARGETING::TYPE_OCMB_CHIP>(i_symbol); } //------------------------------------------------------------------------------ } // namespace PARSERUTILS #if defined(PRDF_HOSTBOOT_ERRL_PLUGIN) || defined(PRDF_FSP_ERRL_PLUGIN) } // end namespace FSP/HOSTBOOT #endif } // End of namespace PRDF <commit_msg>PRD: Fix nibble2symbol utility function<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/diag/prdf/common/plugins/prdfParserUtils.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2021 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <prdfParserUtils.H> #include <prdfParserEnums.H> namespace PRDF { #if defined(PRDF_HOSTBOOT_ERRL_PLUGIN) namespace HOSTBOOT { #elif defined(PRDF_FSP_ERRL_PLUGIN) namespace FSP { #endif namespace PARSERUTILS { //------------------------------------------------------------------------------ template<> uint8_t symbol2Dq<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_symbol ) { uint8_t dq = OCMB_DQS_PER_DIMM; static const uint8_t symbol2dq[] = { 39, 38, 37, 36, 35, 34, 33, 32, // symbols 0- 7 79, 78, 77, 76, 71, 70, 69, 68, // symbols 8-15 63, 62, 61, 60, 55, 54, 53, 52, // symbols 16-23 31, 30, 29, 28, 23, 22, 21, 20, // symbols 24-31 15, 14, 13, 12, 7, 6, 5, 4, // symbols 32-39 75, 74, 73, 72, 67, 66, 65, 64, // symbols 40-47 59, 58, 57, 56, 51, 50, 49, 48, // symbols 48-55 27, 26, 25, 24, 19, 18, 17, 16, // symbols 56-63 11, 10, 9, 8, 3, 2, 1, 0, // symbols 64-71 }; if ( SYMBOLS_PER_RANK > i_symbol ) { dq = symbol2dq[i_symbol]; } return dq; } //------------------------------------------------------------------------------ template<> uint8_t symbol2PortSlct<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_symbol ) { // TODO RTC 210072 - Explorer only has one port, as such we can just // return 0. However, multiple ports will be supported in the future, // We'll need to figure out how to convert the symbol to a port select for // OCMB at that time. return 0; } //------------------------------------------------------------------------------ template<TARGETING::TYPE T> uint8_t dq2Symbol( uint8_t i_dq, uint8_t i_ps ) { uint8_t symbol = SYMBOLS_PER_RANK; static const uint8_t sp = SYMBOLS_PER_RANK; // Spare symbols static const uint8_t dq2symbol[] = { 71, 70, 69, 68, 39, 38, 37, 36, // dqs 0- 7 67, 66, 65, 64, 35, 34, 33, 32, // dqs 8-15 63, 62, 61, 60, 31, 30, 29, 28, // dqs 16-23 59, 58, 57, 56, 27, 26, 25, 24, // dqs 24-31 7, 6, 5, 4, 3, 2, 1, 0, // dqs 32-39 sp, sp, sp, sp, sp, sp, sp, sp, // dqs 40-47 - spare 55, 54, 53, 52, 23, 22, 21, 20, // dqs 48-55 51, 50, 49, 48, 19, 18, 17, 16, // dqs 56-63 47, 46, 45, 44, 15, 14, 13, 12, // dqs 64-71 43, 42, 41, 40, 11, 10, 9, 8, // dqs 72-80 }; if ( OCMB_DQS_PER_DIMM > i_dq ) { symbol = dq2symbol[i_dq]; } return symbol; } template uint8_t dq2Symbol<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_dq, uint8_t i_ps ); template uint8_t dq2Symbol<TARGETING::TYPE_MEM_PORT>( uint8_t i_dq, uint8_t i_ps ); //------------------------------------------------------------------------------ template<> uint8_t nibble2Symbol<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_x4Dram ) { uint8_t symbol = SYMBOLS_PER_RANK; static const uint8_t sp = SYMBOLS_PER_RANK; // Spare symbols static const uint8_t nibble2symbol[] = { 68, 36, 64, 32, 60, // nibbles 0-4 28, 56, 24, 52, 20, // nibbles 5-9 48, 16, 44, 12, 40, // nibbles 10-14 8, 4, 0, sp, sp, // nibbles 15-19 }; if ( NIBBLES_PER_DIMM > i_x4Dram ) { symbol = nibble2symbol[i_x4Dram]; } return symbol; } //------------------------------------------------------------------------------ template<> uint8_t byte2Symbol<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_x8Dram ) { uint8_t symbol = SYMBOLS_PER_RANK; static const uint8_t sp = SYMBOLS_PER_RANK; // Spare symbols static const uint8_t byte2symbol[] = { 36, 32, 28, 24, 20, // bytes 0-4 16, 12, 8, 0, sp, // bytes 5-9 }; if ( BYTES_PER_DIMM > i_x8Dram ) { symbol = byte2symbol[i_x8Dram]; } return symbol; } //------------------------------------------------------------------------------ template<> uint8_t symbol2Nibble<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_symbol ) { uint8_t nibble = NIBBLES_PER_DIMM; // There are 4 symbols per nibble, always grouped together, so divide // by 4 here to simplify our conversion table. uint8_t tmp = i_symbol/4; static const uint8_t symbol2nibble[] = { 17, 16, 15, 13, // symbols 0-15 11, 9, 7, 5, // symbols 16-31 3, 1, 14, 12, // symbols 32-47 10, 8, 6, 4, // symbols 48-63 2, 0, // symbols 64-71 }; if ( SYMBOLS_PER_RANK > i_symbol ) { nibble = symbol2nibble[tmp]; } return nibble; } //------------------------------------------------------------------------------ template<> uint8_t symbol2Byte<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_symbol ) { return (SYMBOLS_PER_RANK > i_symbol) ? (symbol2Nibble<TARGETING::TYPE_OCMB_CHIP>(i_symbol)/2) : MEM_BYTES_PER_RANK; } //------------------------------------------------------------------------------ template<> uint8_t dram2Symbol<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_dram, bool i_isX4Dram ) { return (true == i_isX4Dram) ? nibble2Symbol<TARGETING::TYPE_OCMB_CHIP>(i_dram) : byte2Symbol<TARGETING::TYPE_OCMB_CHIP>(i_dram); } //------------------------------------------------------------------------------ template<> uint8_t symbol2Dram<TARGETING::TYPE_OCMB_CHIP>( uint8_t i_symbol, bool i_isX4Dram ) { return (true == i_isX4Dram) ? symbol2Nibble<TARGETING::TYPE_OCMB_CHIP>(i_symbol) : symbol2Byte<TARGETING::TYPE_OCMB_CHIP>(i_symbol); } //------------------------------------------------------------------------------ } // namespace PARSERUTILS #if defined(PRDF_HOSTBOOT_ERRL_PLUGIN) || defined(PRDF_FSP_ERRL_PLUGIN) } // end namespace FSP/HOSTBOOT #endif } // End of namespace PRDF <|endoftext|>
<commit_before>#include "unit_tests/suite/lumix_unit_tests.h" #include "core/log.h" #include "core/mt/lock_free_fixed_queue.h" #include "core/mt/task.h" #include "core/MT/thread.h" #include "core/mt/transaction.h" #include "core/queue.h" #include "core/array.h" #include <Windows.h> //#define ASSERT_HANDLE_FAIL namespace Lumix { namespace UnitTest { Manager* Manager::s_instance = NULL; static const int32_t C_MAX_TRANS = 16; struct UnitTestPair { const char* name; const char* parameters; Manager::unitTestFunc func; }; struct FailInfo { const char* m_file_name; uint32_t m_line; }; typedef MT::Transaction<UnitTestPair> AsynTest; typedef MT::LockFreeFixedQueue<AsynTest, C_MAX_TRANS> TransQueue; typedef Queue<AsynTest*, C_MAX_TRANS> InProgressQueue; class WorkerTask : public MT::Task { public: WorkerTask(TransQueue* tests_todo, IAllocator& allocator) : MT::Task(allocator) , m_tests_todo(tests_todo) { } virtual int task() override { while(!m_tests_todo->isAborted()) { AsynTest* test = m_tests_todo->pop(true); if(NULL == test) break; UnitTestPair& ut = test->data; g_log_info.log("unit") << "-------------------------"; g_log_info.log("unit") << ut.name; g_log_info.log("unit") << "-------------------------"; ut.func(ut.parameters); g_log_info.log("unit") << "-------------------------"; test->setCompleted(); } return 0; } private: TransQueue* m_tests_todo; }; typedef Array<UnitTestPair> UnitTestTable; typedef Array<FailInfo> FailedTestTable; struct ManagerImpl { public: void registerFunction(const char* name, Manager::unitTestFunc func, const char* params) { UnitTestPair& pair = m_unit_tests.pushEmpty(); pair.name = name; pair.parameters = params; pair.func = func; } void dumpTests() const { for(int i = 0, c = m_unit_tests.size(); i < c; ++i) { g_log_info.log("unit") << m_unit_tests[i].name; } g_log_info.log("unit") << ""; g_log_info.log("unit") << "Running tests ..."; g_log_info.log("unit") << ""; } void runTests(const char* filter_tests) { spawnWorkerTask(); int i = 0, c = m_unit_tests.size(); while(i < c || m_in_progress.size() != 0 || !m_trans_queue.isEmpty()) { if(m_in_progress.size() > 0) { AsynTest* test = m_in_progress.front(); if(test->isCompleted()) { m_in_progress.pop(); m_trans_queue.dealoc(test); } } if(i < c) { UnitTestPair& pair = m_unit_tests[i]; AsynTest* test = m_trans_queue.alloc(true); test->data.name = pair.name; test->data.func = pair.func; test->data.parameters = pair.parameters; i++; m_trans_queue.push(test, true); m_in_progress.push(test); } // fatal error occured. We need to respawn task. if (m_task.isFinished()) { // test failed, remove it from the queue and spawn new thread AsynTest* test = m_in_progress.front(); m_in_progress.pop(); m_trans_queue.dealoc(test); m_task.destroy(); spawnWorkerTask(); } Lumix::MT::yield(); } m_trans_queue.abort(); } void dumpResults() const { if (m_fails > 0) { g_log_info.log("unit") << "----------Fails----------"; for (int i = 0; i < m_failed_tests.size(); i++) { g_log_info.log("unit") << m_failed_tests[i].m_file_name << "(" << m_failed_tests[i].m_line << ")"; } } g_log_info.log("unit") << "--------- Results ---------"; g_log_info.log("unit") << "Fails: " << m_fails; g_log_info.log("unit") << "---------------------------"; } void handleFail(const char* file_name, uint32_t line) { FailInfo& fi = m_failed_tests.pushEmpty(); fi.m_file_name = file_name; fi.m_line = line; m_fails++; #if ASSERT_HANDLE_FAIL ASSERT(false); #endif //ASSERT_HANDLE_FAIL m_task.exit(10); } void spawnWorkerTask() { ASSERT(!m_task.isRunning()); m_task.create("TestWorkerTask"); m_task.run(); } ManagerImpl(IAllocator& allocator) : m_fails(0) , m_task(&m_trans_queue, allocator) , m_in_progress(allocator) , m_trans_queue(allocator) , m_allocator(allocator) , m_unit_tests(allocator) , m_failed_tests(allocator) { } ~ManagerImpl() { m_task.destroy(); } IAllocator& getAllocator() { return m_allocator; } private: IAllocator& m_allocator; uint32_t m_fails; UnitTestTable m_unit_tests; FailedTestTable m_failed_tests; TransQueue m_trans_queue; InProgressQueue m_in_progress; WorkerTask m_task; }; void Manager::registerFunction(const char* name, Manager::unitTestFunc func, const char* params) { m_impl->registerFunction(name, func, params); } void Manager::dumpTests() const { m_impl->dumpTests(); } void Manager::runTests(const char *filter_tests) { m_impl->runTests(filter_tests); } void Manager::dumpResults() const { m_impl->dumpResults(); } void Manager::handleFail(const char* file_name, uint32_t line) { m_impl->handleFail(file_name, line); } Manager::Manager(IAllocator& allocator) { m_impl = allocator.newObject<ManagerImpl>(allocator); } Manager::~Manager() { m_impl->getAllocator().deleteObject(m_impl); } } //~UnitTest } //~UnitTest<commit_msg>UT suite fix.<commit_after>#include "unit_tests/suite/lumix_unit_tests.h" #include "core/log.h" #include "core/mt/lock_free_fixed_queue.h" #include "core/mt/task.h" #include "core/MT/thread.h" #include "core/mt/transaction.h" #include "core/queue.h" #include "core/array.h" #include <Windows.h> //#define ASSERT_HANDLE_FAIL namespace Lumix { namespace UnitTest { Manager* Manager::s_instance = NULL; static const int32_t C_MAX_TRANS = 16; struct UnitTestPair { const char* name; const char* parameters; Manager::unitTestFunc func; }; struct FailInfo { const char* m_file_name; uint32_t m_line; }; typedef MT::Transaction<UnitTestPair> AsynTest; typedef MT::LockFreeFixedQueue<AsynTest, C_MAX_TRANS> TransQueue; typedef Queue<AsynTest*, C_MAX_TRANS> InProgressQueue; class WorkerTask : public MT::Task { public: WorkerTask(TransQueue* tests_todo, IAllocator& allocator) : MT::Task(allocator) , m_tests_todo(tests_todo) { } virtual int task() override { while(!m_tests_todo->isAborted()) { AsynTest* test = m_tests_todo->pop(true); if(NULL == test) break; UnitTestPair& ut = test->data; g_log_info.log("unit") << "-------------------------"; g_log_info.log("unit") << ut.name; g_log_info.log("unit") << "-------------------------"; ut.func(ut.parameters); g_log_info.log("unit") << "-------------------------"; test->setCompleted(); } return 0; } private: TransQueue* m_tests_todo; }; typedef Array<UnitTestPair> UnitTestTable; typedef Array<FailInfo> FailedTestTable; struct ManagerImpl { public: void registerFunction(const char* name, Manager::unitTestFunc func, const char* params) { UnitTestPair& pair = m_unit_tests.pushEmpty(); pair.name = name; pair.parameters = params; pair.func = func; } void dumpTests() const { for(int i = 0, c = m_unit_tests.size(); i < c; ++i) { g_log_info.log("unit") << m_unit_tests[i].name; } g_log_info.log("unit") << ""; g_log_info.log("unit") << "Running tests ..."; g_log_info.log("unit") << ""; } void runTests(const char* filter_tests) { spawnWorkerTask(); int i = 0, c = m_unit_tests.size(); while(i < c || m_in_progress.size() != 0 || !m_trans_queue.isEmpty()) { if(m_in_progress.size() > 0) { AsynTest* test = m_in_progress.front(); if(test->isCompleted()) { m_in_progress.pop(); m_trans_queue.dealoc(test); } } if(i < c) { UnitTestPair& pair = m_unit_tests[i]; AsynTest* test = m_trans_queue.alloc(false); if (test) { test->data.name = pair.name; test->data.func = pair.func; test->data.parameters = pair.parameters; i++; m_trans_queue.push(test, true); m_in_progress.push(test); } else { Lumix::MT::yield(); } } // fatal error occured. We need to respawn task. if (m_task.isFinished()) { // test failed, remove it from the queue and spawn new thread AsynTest* test = m_in_progress.front(); m_in_progress.pop(); m_trans_queue.dealoc(test); m_task.destroy(); spawnWorkerTask(); } Lumix::MT::yield(); } m_trans_queue.abort(); } void dumpResults() const { if (m_fails > 0) { g_log_info.log("unit") << "----------Fails----------"; for (int i = 0; i < m_failed_tests.size(); i++) { g_log_info.log("unit") << m_failed_tests[i].m_file_name << "(" << m_failed_tests[i].m_line << ")"; } } g_log_info.log("unit") << "--------- Results ---------"; g_log_info.log("unit") << "Fails: " << m_fails; g_log_info.log("unit") << "---------------------------"; } void handleFail(const char* file_name, uint32_t line) { FailInfo& fi = m_failed_tests.pushEmpty(); fi.m_file_name = file_name; fi.m_line = line; m_fails++; #if ASSERT_HANDLE_FAIL ASSERT(false); #endif //ASSERT_HANDLE_FAIL m_task.exit(10); } void spawnWorkerTask() { ASSERT(!m_task.isRunning()); m_task.create("TestWorkerTask"); m_task.run(); } ManagerImpl(IAllocator& allocator) : m_fails(0) , m_task(&m_trans_queue, allocator) , m_in_progress(allocator) , m_trans_queue(allocator) , m_allocator(allocator) , m_unit_tests(allocator) , m_failed_tests(allocator) { } ~ManagerImpl() { m_task.destroy(); } IAllocator& getAllocator() { return m_allocator; } private: IAllocator& m_allocator; uint32_t m_fails; UnitTestTable m_unit_tests; FailedTestTable m_failed_tests; TransQueue m_trans_queue; InProgressQueue m_in_progress; WorkerTask m_task; }; void Manager::registerFunction(const char* name, Manager::unitTestFunc func, const char* params) { m_impl->registerFunction(name, func, params); } void Manager::dumpTests() const { m_impl->dumpTests(); } void Manager::runTests(const char *filter_tests) { m_impl->runTests(filter_tests); } void Manager::dumpResults() const { m_impl->dumpResults(); } void Manager::handleFail(const char* file_name, uint32_t line) { m_impl->handleFail(file_name, line); } Manager::Manager(IAllocator& allocator) { m_impl = allocator.newObject<ManagerImpl>(allocator); } Manager::~Manager() { m_impl->getAllocator().deleteObject(m_impl); } } //~UnitTest } //~UnitTest<|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2002-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "<WebSig>" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, Institute for * Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>. * The development of this software was partly funded by the European * Commission in the <WebSig> project in the ISIS Programme. * For more information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * XSEC * * XSECURIResolverGenericUnix := A URI Resolver that will work "out of * the box" with UNIX. Re-implements * much Xerces code, but allows us to * handle HTTP redirects as is required by * the DSIG Standard * * Author(s): Berin Lautenbach * * $Id$ * * $Log$ * Revision 1.6 2004/01/26 00:29:48 blautenb * Check for Xerces new way of handling NULL hostnames in URIs * * Revision 1.5 2003/09/11 11:29:12 blautenb * Fix Xerces namespace usage in *NIX build * * Revision 1.4 2003/07/05 10:30:38 blautenb * Copyright update * * Revision 1.3 2003/05/10 07:23:36 blautenb * Updates to support anonymous references * * Revision 1.2 2003/02/20 10:35:10 blautenb * Fix for broken Xerces XMLUri * * Revision 1.1 2003/02/12 11:21:03 blautenb * UNIX generic URI resolver * * */ #include "XSECURIResolverGenericUnix.hpp" #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/XMLUri.hpp> #include <xercesc/util/XMLUni.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/BinFileInputStream.hpp> XERCES_CPP_NAMESPACE_USE #include <xsec/framework/XSECError.hpp> #include <xsec/utils/unixutils/XSECBinHTTPURIInputStream.hpp> static const XMLCh gFileScheme[] = { XERCES_CPP_NAMESPACE_QUALIFIER chLatin_f, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_i, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_l, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_e, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; static const XMLCh gHttpScheme[] = { XERCES_CPP_NAMESPACE_QUALIFIER chLatin_h, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_p, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; #if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3 static const XMLCh DOTDOT_SLASH[] = { XERCES_CPP_NAMESPACE_QUALIFIER chPeriod, XERCES_CPP_NAMESPACE_QUALIFIER chPeriod, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; #endif XSECURIResolverGenericUnix::XSECURIResolverGenericUnix() : mp_baseURI(NULL) { }; XSECURIResolverGenericUnix::~XSECURIResolverGenericUnix() { if (mp_baseURI != NULL) delete[] mp_baseURI; } // ----------------------------------------------------------------------- // Resolve a URI that is passed in // ----------------------------------------------------------------------- BinInputStream * XSECURIResolverGenericUnix::resolveURI(const XMLCh * uri) { XSEC_USING_XERCES(BinInputStream); XSEC_USING_XERCES(XMLUri); XSEC_USING_XERCES(XMLUni); XSEC_USING_XERCES(Janitor); XSEC_USING_XERCES(BinFileInputStream); XMLUri * xmluri; if (uri == NULL) { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - anonymous references not supported in default URI Resolvers"); } // Create the appropriate XMLUri objects if (mp_baseURI != NULL) { XMLUri * turi; #if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3 // XMLUri relative paths are broken, so we need to strip out ".." XMLCh * b = XMLString::replicate(mp_baseURI); ArrayJanitor<XMLCh> j_b(b); XMLCh * r = XMLString::replicate(uri); ArrayJanitor<XMLCh> j_r(r); int index = 0; while (XMLString::startsWith(&(r[index]), DOTDOT_SLASH)) { // Strip the last segment of the base int lastIndex = XMLString::lastIndexOf(b, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash); if (lastIndex > 0) b[lastIndex] = 0; index += 3; } XSECnew(turi, XMLUri(b)); Janitor<XMLUri> j_turi(turi); XSECnew(xmluri, XMLUri(turi, &(r[index]))); #else XSECnew(turi, XMLUri(mp_baseURI)); Janitor<XMLUri> j_turi(turi); XSECnew(xmluri, XMLUri(turi, uri)); #endif } else { XSECnew(xmluri, XMLUri(uri)); } Janitor<XMLUri> j_xmluri(xmluri); // Determine what kind of URI this is and how to handle it. if (!XMLString::compareIString(xmluri->getScheme(), gFileScheme)) { // This is a file. We only really understand if this is localhost // XMLUri has already cleaned of escape characters (%xx) if (xmluri->getHost() == NULL || xmluri->getHost()[0] == chNull || !XMLString::compareIString(xmluri->getHost(), XMLUni::fgLocalHostString)) { // Localhost BinFileInputStream* retStrm = new BinFileInputStream(xmluri->getPath()); if (!retStrm->getIsOpen()) { delete retStrm; return 0; } return retStrm; } else { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - unable to open non-localhost file"); } } // Is the scheme a HTTP? if (!XMLString::compareIString(xmluri->getScheme(), gHttpScheme)) { // Pass straight to our local XSECBinHTTPUriInputStream XSECBinHTTPURIInputStream *ret; XSECnew(ret, XSECBinHTTPURIInputStream(*xmluri)); return ret; } throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - unknown URI scheme"); } // ----------------------------------------------------------------------- // Clone me // ----------------------------------------------------------------------- XSECURIResolver * XSECURIResolverGenericUnix::clone(void) { XSECURIResolverGenericUnix * ret; ret = new XSECURIResolverGenericUnix(); if (this->mp_baseURI != NULL) ret->mp_baseURI = XMLString::replicate(this->mp_baseURI); else ret->mp_baseURI = NULL; return ret; } // ----------------------------------------------------------------------- // Set a base URI to map any incoming files against // ----------------------------------------------------------------------- void XSECURIResolverGenericUnix::setBaseURI(const XMLCh * uri) { if (mp_baseURI != NULL) delete[] mp_baseURI; mp_baseURI = XMLString::replicate(uri); } <commit_msg>Add Space handling to UNIX URL handling<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2002-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "<WebSig>" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, Institute for * Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>. * The development of this software was partly funded by the European * Commission in the <WebSig> project in the ISIS Programme. * For more information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * XSEC * * XSECURIResolverGenericUnix := A URI Resolver that will work "out of * the box" with UNIX. Re-implements * much Xerces code, but allows us to * handle HTTP redirects as is required by * the DSIG Standard * * Author(s): Berin Lautenbach * * $Id$ * * $Log$ * Revision 1.7 2004/02/03 11:00:03 blautenb * Add Space handling to UNIX URL handling * * Revision 1.6 2004/01/26 00:29:48 blautenb * Check for Xerces new way of handling NULL hostnames in URIs * * Revision 1.5 2003/09/11 11:29:12 blautenb * Fix Xerces namespace usage in *NIX build * * Revision 1.4 2003/07/05 10:30:38 blautenb * Copyright update * * Revision 1.3 2003/05/10 07:23:36 blautenb * Updates to support anonymous references * * Revision 1.2 2003/02/20 10:35:10 blautenb * Fix for broken Xerces XMLUri * * Revision 1.1 2003/02/12 11:21:03 blautenb * UNIX generic URI resolver * * */ #include "XSECURIResolverGenericUnix.hpp" #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/XMLUri.hpp> #include <xercesc/util/XMLUni.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/BinFileInputStream.hpp> XERCES_CPP_NAMESPACE_USE #include <xsec/framework/XSECError.hpp> #include <xsec/utils/XSECDOMUtils.hpp> #include <xsec/utils/unixutils/XSECBinHTTPURIInputStream.hpp> static const XMLCh gFileScheme[] = { XERCES_CPP_NAMESPACE_QUALIFIER chLatin_f, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_i, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_l, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_e, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; static const XMLCh gHttpScheme[] = { XERCES_CPP_NAMESPACE_QUALIFIER chLatin_h, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_t, XERCES_CPP_NAMESPACE_QUALIFIER chLatin_p, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; #if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3 static const XMLCh DOTDOT_SLASH[] = { XERCES_CPP_NAMESPACE_QUALIFIER chPeriod, XERCES_CPP_NAMESPACE_QUALIFIER chPeriod, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash, XERCES_CPP_NAMESPACE_QUALIFIER chNull }; #endif XSECURIResolverGenericUnix::XSECURIResolverGenericUnix() : mp_baseURI(NULL) { }; XSECURIResolverGenericUnix::~XSECURIResolverGenericUnix() { if (mp_baseURI != NULL) delete[] mp_baseURI; } // ----------------------------------------------------------------------- // Resolve a URI that is passed in // ----------------------------------------------------------------------- BinInputStream * XSECURIResolverGenericUnix::resolveURI(const XMLCh * uri) { XSEC_USING_XERCES(BinInputStream); XSEC_USING_XERCES(XMLUri); XSEC_USING_XERCES(XMLUni); XSEC_USING_XERCES(Janitor); XSEC_USING_XERCES(BinFileInputStream); XMLUri * xmluri; if (uri == NULL) { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - anonymous references not supported in default URI Resolvers"); } // Create the appropriate XMLUri objects if (mp_baseURI != NULL) { XMLUri * turi; #if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3 // XMLUri relative paths are broken, so we need to strip out ".." XMLCh * b = XMLString::replicate(mp_baseURI); ArrayJanitor<XMLCh> j_b(b); XMLCh * r = XMLString::replicate(uri); ArrayJanitor<XMLCh> j_r(r); int index = 0; while (XMLString::startsWith(&(r[index]), DOTDOT_SLASH)) { // Strip the last segment of the base int lastIndex = XMLString::lastIndexOf(b, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash); if (lastIndex > 0) b[lastIndex] = 0; index += 3; } XSECnew(turi, XMLUri(b)); Janitor<XMLUri> j_turi(turi); XSECnew(xmluri, XMLUri(turi, &(r[index]))); #else XSECnew(turi, XMLUri(mp_baseURI)); Janitor<XMLUri> j_turi(turi); XSECnew(xmluri, XMLUri(turi, uri)); #endif } else { XSECnew(xmluri, XMLUri(uri)); } Janitor<XMLUri> j_xmluri(xmluri); // Determine what kind of URI this is and how to handle it. if (!XMLString::compareIString(xmluri->getScheme(), gFileScheme)) { // This is a file. We only really understand if this is localhost // XMLUri has already cleaned of escape characters (%xx) if (xmluri->getHost() == NULL || xmluri->getHost()[0] == chNull || !XMLString::compareIString(xmluri->getHost(), XMLUni::fgLocalHostString)) { // Clean hex escapes XMLCh * realPath = cleanURIEscapes(xmluri->getPath()); ArrayJanitor<XMLCh> j_realPath(realPath); // Localhost BinFileInputStream* retStrm = new BinFileInputStream(realPath); if (!retStrm->getIsOpen()) { delete retStrm; return 0; } return retStrm; } else { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - unable to open non-localhost file"); } } // Is the scheme a HTTP? if (!XMLString::compareIString(xmluri->getScheme(), gHttpScheme)) { // Pass straight to our local XSECBinHTTPUriInputStream XSECBinHTTPURIInputStream *ret; XSECnew(ret, XSECBinHTTPURIInputStream(*xmluri)); return ret; } throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericUnix - unknown URI scheme"); } // ----------------------------------------------------------------------- // Clone me // ----------------------------------------------------------------------- XSECURIResolver * XSECURIResolverGenericUnix::clone(void) { XSECURIResolverGenericUnix * ret; ret = new XSECURIResolverGenericUnix(); if (this->mp_baseURI != NULL) ret->mp_baseURI = XMLString::replicate(this->mp_baseURI); else ret->mp_baseURI = NULL; return ret; } // ----------------------------------------------------------------------- // Set a base URI to map any incoming files against // ----------------------------------------------------------------------- void XSECURIResolverGenericUnix::setBaseURI(const XMLCh * uri) { if (mp_baseURI != NULL) delete[] mp_baseURI; mp_baseURI = XMLString::replicate(uri); } <|endoftext|>
<commit_before>/* * Copyright 2002-2005 The Apache Software Foundation. * * 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. */ /* * XSEC * * XSECURIResolverGenericWin32 := A URI Resolver that will work "out of * the box" with Windows. Re-implements * much Xerces code, but allows us to * handle HTTP redirects as is required by * the DSIG Standard * * Author(s): Berin Lautenbach * * $Id$ * * $Log$ * Revision 1.11 2005/02/03 13:56:22 milan * Apache licence fix. * * Revision 1.10 2004/02/21 08:26:54 blautenb * Use XMLString::release rather than delete[] for all Xerces strings * * Revision 1.9 2004/02/08 10:25:40 blautenb * Convert to Apache 2.0 license * * Revision 1.8 2004/01/26 00:16:04 blautenb * Remove escapes from URI before retrieving a path on the file system * * Revision 1.7 2003/09/11 11:11:05 blautenb * Cleaned up usage of Xerces namespace - no longer inject into global namespace in headers * * Revision 1.6 2003/07/28 12:52:46 blautenb * Fixed a bug with DEBUG_NEW when compiling with Xalan 1.6 * * Revision 1.5 2003/07/05 10:30:38 blautenb * Copyright update * * Revision 1.4 2003/05/22 11:42:06 blautenb * Updates so Windows version will compile with Xerces 2.3 * * Revision 1.3 2003/05/10 07:23:36 blautenb * Updates to support anonymous references * * Revision 1.2 2003/02/17 11:21:45 blautenb * Work around for Xerces XMLUri bug * * Revision 1.1 2003/02/12 09:45:29 blautenb * Win32 Re-implementation of Xerces URIResolver to support re-directs * * */ #include "XSECURIResolverGenericWin32.hpp" #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/XMLUri.hpp> #include <xercesc/util/XMLUni.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/BinFileInputStream.hpp> XERCES_CPP_NAMESPACE_USE #include <xsec/framework/XSECError.hpp> #include <xsec/utils/winutils/XSECBinHTTPURIInputStream.hpp> #include <xsec/utils/XSECDOMUtils.hpp> static const XMLCh gFileScheme[] = { chLatin_f, chLatin_i, chLatin_l, chLatin_e, chNull }; static const XMLCh gHttpScheme[] = { chLatin_h, chLatin_t, chLatin_t, chLatin_p, chNull }; #if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3 static const XMLCh DOTDOT_SLASH[] = { chPeriod, chPeriod, chForwardSlash, chNull }; #endif XSECURIResolverGenericWin32::XSECURIResolverGenericWin32() : mp_baseURI(NULL) { }; XSECURIResolverGenericWin32::~XSECURIResolverGenericWin32() { if (mp_baseURI != NULL) XMLString::release(&mp_baseURI); } // ----------------------------------------------------------------------- // Resolve a URI that is passed in // ----------------------------------------------------------------------- BinInputStream * XSECURIResolverGenericWin32::resolveURI(const XMLCh * uri) { XSEC_USING_XERCES(BinInputStream); XSEC_USING_XERCES(XMLUri); XSEC_USING_XERCES(XMLUni); XSEC_USING_XERCES(Janitor); XSEC_USING_XERCES(BinFileInputStream); XMLUri * xmluri; if (uri == NULL) { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericWin32 - anonymous references not supported in default URI Resolvers"); } // Create the appropriate XMLUri objects if (mp_baseURI != NULL) { XMLUri * turi; #if defined(XSEC_XERCES_BROKEN_XMLURI) // XMLUri relative paths are broken, so we need to strip out ".." // Doesn't fix the whole problem, but gets us somewhere XMLCh * b = XMLString::replicate(mp_baseURI); ArrayJanitor<XMLCh> j_b(b); XMLCh * r = XMLString::replicate(uri); ArrayJanitor<XMLCh> j_r(r); int index = 0; while (XMLString::startsWith(&(r[index]), DOTDOT_SLASH)) { // Strip the last segment of the base int lastIndex = XMLString::lastIndexOf(b, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash); if (lastIndex > 0) b[lastIndex] = 0; index += 3; } XSECnew(turi, XMLUri(b)); Janitor<XMLUri> j_turi(turi); XSECnew(xmluri, XMLUri(turi, &(r[index]))); #else turi = new XMLUri(mp_baseURI); Janitor<XMLUri> j_turi(turi); xmluri = new XMLUri(turi, uri); #endif } else { xmluri = new XMLUri(uri); } Janitor<XMLUri> j_xmluri(xmluri); // Determine what kind of URI this is and how to handle it. if (!XMLString::compareIString(xmluri->getScheme(), gFileScheme)) { // This is a file. We only really understand if this is localhost if (xmluri->getHost() == NULL || xmluri->getHost()[0] == chNull || !XMLString::compareIString(xmluri->getHost(), XMLUni::fgLocalHostString)) { // Clean hex escapes XMLCh * realPath = cleanURIEscapes(xmluri->getPath()); ArrayJanitor<XMLCh> j_realPath(realPath); // Localhost BinFileInputStream* retStrm = new BinFileInputStream(realPath); if (!retStrm->getIsOpen()) { delete retStrm; return 0; } return retStrm; } else { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericWin32 - unable to open non-localhost file"); } } // Is the scheme a HTTP? if (!XMLString::compareIString(xmluri->getScheme(), gHttpScheme)) { // Pass straight to our local XSECBinHTTPUriInputStream XSECBinHTTPURIInputStream *ret; ret = new XSECBinHTTPURIInputStream(*xmluri); return ret; } throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericWin32 - unknown URI scheme"); } // ----------------------------------------------------------------------- // Clone me // ----------------------------------------------------------------------- XSECURIResolver * XSECURIResolverGenericWin32::clone(void) { XSECURIResolverGenericWin32 * ret; ret = new XSECURIResolverGenericWin32(); if (this->mp_baseURI != NULL) ret->mp_baseURI = XMLString::replicate(this->mp_baseURI); else ret->mp_baseURI = NULL; return ret; } // ----------------------------------------------------------------------- // Set a base URI to map any incoming files against // ----------------------------------------------------------------------- void XSECURIResolverGenericWin32::setBaseURI(const XMLCh * uri) { if (mp_baseURI != NULL) XMLString::release(&mp_baseURI); mp_baseURI = XMLString::replicate(uri); } <commit_msg>Update localhost check to include an empty hostname - reported by Vincent Finn <[email protected]> on security-dev@xml 27/5/2005<commit_after>/* * Copyright 2002-2005 The Apache Software Foundation. * * 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. */ /* * XSEC * * XSECURIResolverGenericWin32 := A URI Resolver that will work "out of * the box" with Windows. Re-implements * much Xerces code, but allows us to * handle HTTP redirects as is required by * the DSIG Standard * * Author(s): Berin Lautenbach * * $Id$ * * $Log$ * Revision 1.12 2005/05/29 00:06:55 blautenb * Update localhost check to include an empty hostname - reported by Vincent Finn <[email protected]> on security-dev@xml 27/5/2005 * * Revision 1.11 2005/02/03 13:56:22 milan * Apache licence fix. * * Revision 1.10 2004/02/21 08:26:54 blautenb * Use XMLString::release rather than delete[] for all Xerces strings * * Revision 1.9 2004/02/08 10:25:40 blautenb * Convert to Apache 2.0 license * * Revision 1.8 2004/01/26 00:16:04 blautenb * Remove escapes from URI before retrieving a path on the file system * * Revision 1.7 2003/09/11 11:11:05 blautenb * Cleaned up usage of Xerces namespace - no longer inject into global namespace in headers * * Revision 1.6 2003/07/28 12:52:46 blautenb * Fixed a bug with DEBUG_NEW when compiling with Xalan 1.6 * * Revision 1.5 2003/07/05 10:30:38 blautenb * Copyright update * * Revision 1.4 2003/05/22 11:42:06 blautenb * Updates so Windows version will compile with Xerces 2.3 * * Revision 1.3 2003/05/10 07:23:36 blautenb * Updates to support anonymous references * * Revision 1.2 2003/02/17 11:21:45 blautenb * Work around for Xerces XMLUri bug * * Revision 1.1 2003/02/12 09:45:29 blautenb * Win32 Re-implementation of Xerces URIResolver to support re-directs * * */ #include "XSECURIResolverGenericWin32.hpp" #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/XMLUri.hpp> #include <xercesc/util/XMLUni.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/BinFileInputStream.hpp> XERCES_CPP_NAMESPACE_USE #include <xsec/framework/XSECError.hpp> #include <xsec/utils/winutils/XSECBinHTTPURIInputStream.hpp> #include <xsec/utils/XSECDOMUtils.hpp> static const XMLCh gFileScheme[] = { chLatin_f, chLatin_i, chLatin_l, chLatin_e, chNull }; static const XMLCh gHttpScheme[] = { chLatin_h, chLatin_t, chLatin_t, chLatin_p, chNull }; #if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3 static const XMLCh DOTDOT_SLASH[] = { chPeriod, chPeriod, chForwardSlash, chNull }; #endif XSECURIResolverGenericWin32::XSECURIResolverGenericWin32() : mp_baseURI(NULL) { }; XSECURIResolverGenericWin32::~XSECURIResolverGenericWin32() { if (mp_baseURI != NULL) XMLString::release(&mp_baseURI); } // ----------------------------------------------------------------------- // Resolve a URI that is passed in // ----------------------------------------------------------------------- BinInputStream * XSECURIResolverGenericWin32::resolveURI(const XMLCh * uri) { XSEC_USING_XERCES(BinInputStream); XSEC_USING_XERCES(XMLUri); XSEC_USING_XERCES(XMLUni); XSEC_USING_XERCES(Janitor); XSEC_USING_XERCES(BinFileInputStream); XMLUri * xmluri; if (uri == NULL) { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericWin32 - anonymous references not supported in default URI Resolvers"); } // Create the appropriate XMLUri objects if (mp_baseURI != NULL) { XMLUri * turi; #if defined(XSEC_XERCES_BROKEN_XMLURI) // XMLUri relative paths are broken, so we need to strip out ".." // Doesn't fix the whole problem, but gets us somewhere XMLCh * b = XMLString::replicate(mp_baseURI); ArrayJanitor<XMLCh> j_b(b); XMLCh * r = XMLString::replicate(uri); ArrayJanitor<XMLCh> j_r(r); int index = 0; while (XMLString::startsWith(&(r[index]), DOTDOT_SLASH)) { // Strip the last segment of the base int lastIndex = XMLString::lastIndexOf(b, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash); if (lastIndex > 0) b[lastIndex] = 0; index += 3; } XSECnew(turi, XMLUri(b)); Janitor<XMLUri> j_turi(turi); XSECnew(xmluri, XMLUri(turi, &(r[index]))); #else turi = new XMLUri(mp_baseURI); Janitor<XMLUri> j_turi(turi); xmluri = new XMLUri(turi, uri); #endif } else { xmluri = new XMLUri(uri); } Janitor<XMLUri> j_xmluri(xmluri); // Determine what kind of URI this is and how to handle it. if (!XMLString::compareIString(xmluri->getScheme(), gFileScheme)) { // This is a file. We only really understand if this is localhost if (xmluri->getHost() == NULL || xmluri->getHost()[0] == chNull || !XMLString::compareIString(xmluri->getHost(), XMLUni::fgLocalHostString) || !XMLString::compareIString(xmluri->getHost(), XMLUni::fgEmptyString)) { // Clean hex escapes XMLCh * realPath = cleanURIEscapes(xmluri->getPath()); ArrayJanitor<XMLCh> j_realPath(realPath); // Localhost BinFileInputStream* retStrm = new BinFileInputStream(realPath); if (!retStrm->getIsOpen()) { delete retStrm; return 0; } return retStrm; } else { throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericWin32 - unable to open non-localhost file"); } } // Is the scheme a HTTP? if (!XMLString::compareIString(xmluri->getScheme(), gHttpScheme)) { // Pass straight to our local XSECBinHTTPUriInputStream XSECBinHTTPURIInputStream *ret; ret = new XSECBinHTTPURIInputStream(*xmluri); return ret; } throw XSECException(XSECException::ErrorOpeningURI, "XSECURIResolverGenericWin32 - unknown URI scheme"); } // ----------------------------------------------------------------------- // Clone me // ----------------------------------------------------------------------- XSECURIResolver * XSECURIResolverGenericWin32::clone(void) { XSECURIResolverGenericWin32 * ret; ret = new XSECURIResolverGenericWin32(); if (this->mp_baseURI != NULL) ret->mp_baseURI = XMLString::replicate(this->mp_baseURI); else ret->mp_baseURI = NULL; return ret; } // ----------------------------------------------------------------------- // Set a base URI to map any incoming files against // ----------------------------------------------------------------------- void XSECURIResolverGenericWin32::setBaseURI(const XMLCh * uri) { if (mp_baseURI != NULL) XMLString::release(&mp_baseURI); mp_baseURI = XMLString::replicate(uri); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUNCTOR_MAP_RECT_CONCURRENT_HPP #define STAN_MATH_PRIM_MAT_FUNCTOR_MAP_RECT_CONCURRENT_HPP #include <stan/math/prim/mat/fun/typedefs.hpp> #include <stan/math/prim/mat/functor/map_rect_reduce.hpp> #include <stan/math/prim/mat/functor/map_rect_combine.hpp> #include <boost/lexical_cast.hpp> #include <boost/throw_exception.hpp> #include <vector> #include <thread> #include <future> #include <cstdlib> namespace stan { namespace math { namespace internal { /** * Get number of threads to use for num_jobs jobs. The function uses * the environment variable STAN_NUM_THREADS and follows these * conventions: * * - STAN_NUM_THREADS is not defined => num_threads=1 * - STAN_NUM_THREADS is positive => num_threads is set to the * specified number * - STAN_NUM_THREADS is set to -1 => num_threads is the number of * available cores on the machine * - STAN_NUM_THREADS < -1, STAN_NUM_THREADS = 0 or STAN_NUM_THREADS is * not numeric => throws an exception * * Should num_threads exceed the number of jobs, then num_threads will * be set equal to the number of jobs. * * @param num_jobs number of jobs * @return number of threads to use * @throws */ inline int get_num_threads(int num_jobs) { int num_threads = 1; #ifdef STAN_THREADS const char* env_stan_num_threads = std::getenv("STAN_NUM_THREADS"); if (env_stan_num_threads != nullptr) { try { const int env_num_threads = boost::lexical_cast<int>(env_stan_num_threads); if (env_num_threads > 0) num_threads = env_num_threads; else if (env_num_threads == -1) num_threads = std::thread::hardware_concurrency(); else boost::throw_exception(std::runtime_error( "The STAN_NUM_THREADS environment variable must be positive or -1")); // anything else will use 1 thread. } catch (boost::bad_lexical_cast) { boost::throw_exception(std::runtime_error( "The STAN_NUM_THREADS environment variable is not numeric")); } } if (num_threads > num_jobs) num_threads = num_jobs; #endif return num_threads; } template <int call_id, typename F, typename T_shared_param, typename T_job_param> Eigen::Matrix<typename stan::return_type<T_shared_param, T_job_param>::type, Eigen::Dynamic, 1> map_rect_concurrent( const Eigen::Matrix<T_shared_param, Eigen::Dynamic, 1>& shared_params, const std::vector<Eigen::Matrix<T_job_param, Eigen::Dynamic, 1>>& job_params, const std::vector<std::vector<double>>& x_r, const std::vector<std::vector<int>>& x_i, std::ostream* msgs = nullptr) { typedef map_rect_reduce<F, T_shared_param, T_job_param> ReduceF; typedef map_rect_combine<F, T_shared_param, T_job_param> CombineF; const int num_jobs = job_params.size(); const vector_d shared_params_dbl = value_of(shared_params); std::vector<std::future<std::vector<matrix_d>>> futures; auto execute_chunk = [&](int start, int size) -> std::vector<matrix_d> { const int end = start + size; std::vector<matrix_d> chunk_f_out; chunk_f_out.reserve(size); for (int i = start; i != end; i++) chunk_f_out.push_back(ReduceF()( shared_params_dbl, value_of(job_params[i]), x_r[i], x_i[i], msgs)); return chunk_f_out; }; int num_threads = get_num_threads(num_jobs); int num_jobs_per_thread = num_jobs / num_threads; futures.emplace_back( std::async(std::launch::deferred, execute_chunk, 0, num_jobs_per_thread)); #ifdef STAN_THREADS if (num_threads > 1) { const int num_big_threads = (num_jobs - num_jobs_per_thread) % (num_threads - 1); const int first_big_thread = num_threads - num_big_threads; for (int i = 1, job_start = num_jobs_per_thread, job_size = 0; i < num_threads; ++i, job_start += job_size) { job_size = i >= first_big_thread ? num_jobs_per_thread + 1 : num_jobs_per_thread; futures.emplace_back( std::async(std::launch::async, execute_chunk, job_start, job_size)); } } #endif // collect results std::vector<int> world_f_out; world_f_out.reserve(num_jobs); matrix_d world_output(0, 0); int offset = 0; for (std::size_t i = 0; i < futures.size(); ++i) { const std::vector<matrix_d>& chunk_result = futures[i].get(); if (i == 0) world_output.resize(chunk_result[0].rows(), num_jobs * chunk_result[0].cols()); for (const auto& job_result : chunk_result) { const int num_job_outputs = job_result.cols(); world_f_out.push_back(num_job_outputs); if (world_output.cols() < offset + num_job_outputs) world_output.conservativeResize(Eigen::NoChange, 2 * (offset + num_job_outputs)); world_output.block(0, offset, world_output.rows(), num_job_outputs) = job_result; offset += num_job_outputs; } } CombineF combine(shared_params, job_params); return combine(world_output, world_f_out); } } // namespace internal } // namespace math } // namespace stan #endif <commit_msg>Fixed doxygen<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUNCTOR_MAP_RECT_CONCURRENT_HPP #define STAN_MATH_PRIM_MAT_FUNCTOR_MAP_RECT_CONCURRENT_HPP #include <stan/math/prim/mat/fun/typedefs.hpp> #include <stan/math/prim/mat/functor/map_rect_reduce.hpp> #include <stan/math/prim/mat/functor/map_rect_combine.hpp> #include <boost/lexical_cast.hpp> #include <boost/throw_exception.hpp> #include <vector> #include <thread> #include <future> #include <cstdlib> namespace stan { namespace math { namespace internal { /** * Get number of threads to use for num_jobs jobs. The function uses * the environment variable STAN_NUM_THREADS and follows these * conventions: * * - STAN_NUM_THREADS is not defined => num_threads=1 * - STAN_NUM_THREADS is positive => num_threads is set to the * specified number * - STAN_NUM_THREADS is set to -1 => num_threads is the number of * available cores on the machine * - STAN_NUM_THREADS < -1, STAN_NUM_THREADS = 0 or STAN_NUM_THREADS is * not numeric => throws an exception * * Should num_threads exceed the number of jobs, then num_threads will * be set equal to the number of jobs. * * @param num_jobs number of jobs * @return number of threads to use * @throws std::runtime_error if the value of STAN_NUM_THREADS env. variable * is invalid */ inline int get_num_threads(int num_jobs) { int num_threads = 1; #ifdef STAN_THREADS const char* env_stan_num_threads = std::getenv("STAN_NUM_THREADS"); if (env_stan_num_threads != nullptr) { try { const int env_num_threads = boost::lexical_cast<int>(env_stan_num_threads); if (env_num_threads > 0) num_threads = env_num_threads; else if (env_num_threads == -1) num_threads = std::thread::hardware_concurrency(); else boost::throw_exception(std::runtime_error( "The STAN_NUM_THREADS environment variable must be positive or -1")); // anything else will use 1 thread. } catch (boost::bad_lexical_cast) { boost::throw_exception(std::runtime_error( "The STAN_NUM_THREADS environment variable is not numeric")); } } if (num_threads > num_jobs) num_threads = num_jobs; #endif return num_threads; } template <int call_id, typename F, typename T_shared_param, typename T_job_param> Eigen::Matrix<typename stan::return_type<T_shared_param, T_job_param>::type, Eigen::Dynamic, 1> map_rect_concurrent( const Eigen::Matrix<T_shared_param, Eigen::Dynamic, 1>& shared_params, const std::vector<Eigen::Matrix<T_job_param, Eigen::Dynamic, 1>>& job_params, const std::vector<std::vector<double>>& x_r, const std::vector<std::vector<int>>& x_i, std::ostream* msgs = nullptr) { typedef map_rect_reduce<F, T_shared_param, T_job_param> ReduceF; typedef map_rect_combine<F, T_shared_param, T_job_param> CombineF; const int num_jobs = job_params.size(); const vector_d shared_params_dbl = value_of(shared_params); std::vector<std::future<std::vector<matrix_d>>> futures; auto execute_chunk = [&](int start, int size) -> std::vector<matrix_d> { const int end = start + size; std::vector<matrix_d> chunk_f_out; chunk_f_out.reserve(size); for (int i = start; i != end; i++) chunk_f_out.push_back(ReduceF()( shared_params_dbl, value_of(job_params[i]), x_r[i], x_i[i], msgs)); return chunk_f_out; }; int num_threads = get_num_threads(num_jobs); int num_jobs_per_thread = num_jobs / num_threads; futures.emplace_back( std::async(std::launch::deferred, execute_chunk, 0, num_jobs_per_thread)); #ifdef STAN_THREADS if (num_threads > 1) { const int num_big_threads = (num_jobs - num_jobs_per_thread) % (num_threads - 1); const int first_big_thread = num_threads - num_big_threads; for (int i = 1, job_start = num_jobs_per_thread, job_size = 0; i < num_threads; ++i, job_start += job_size) { job_size = i >= first_big_thread ? num_jobs_per_thread + 1 : num_jobs_per_thread; futures.emplace_back( std::async(std::launch::async, execute_chunk, job_start, job_size)); } } #endif // collect results std::vector<int> world_f_out; world_f_out.reserve(num_jobs); matrix_d world_output(0, 0); int offset = 0; for (std::size_t i = 0; i < futures.size(); ++i) { const std::vector<matrix_d>& chunk_result = futures[i].get(); if (i == 0) world_output.resize(chunk_result[0].rows(), num_jobs * chunk_result[0].cols()); for (const auto& job_result : chunk_result) { const int num_job_outputs = job_result.cols(); world_f_out.push_back(num_job_outputs); if (world_output.cols() < offset + num_job_outputs) world_output.conservativeResize(Eigen::NoChange, 2 * (offset + num_job_outputs)); world_output.block(0, offset, world_output.rows(), num_job_outputs) = job_result; offset += num_job_outputs; } } CombineF combine(shared_params, job_params); return combine(world_output, world_f_out); } } // namespace internal } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#include "TVirtualMCApplication.h" #include "Fdblprc.h" //(DBLPRC) fluka common // // #include "TCallf77.h" #ifndef WIN32 #define magfld magfld_ #define type_of_call #else #define magfld MAGFLD #define type_of_call _stdcall #endif extern "C" void type_of_call magfld(double& x, double& y, double& z, double& btx, double& bty, double& btz, double& b, int& /*nreg*/,int& idisc) { /* *----------------------------------------------------------------------* * * * * * Input variables: * * x,y,z = current position * * nreg = current region * * Output variables: * * btx,bty,btz = cosines of the magn. field vector * * B = magnetic field intensity (Tesla) * * idisc = set to 1 if the particle has to be discarded * * * *----------------------------------------------------------------------* */ idisc = 0; Double_t bc[3]; Double_t xc[3]; xc[1] = x; xc[0] = y; xc[2] = z; (TVirtualMCApplication::Instance())->Field(xc, bc); b = sqrt(bc[0] * bc[0] + bc[1] * bc[1] + bc[2] * bc[2]); if (b) { btx = bc[1]/b; bty = bc[0]/b; Double_t btt = btx * btx + bty * bty; if (btt >= (Double_t) 1.) { btx /= TMath::Sqrt(btt); bty /= TMath::Sqrt(btt); b /= TMath::Sqrt(btt); btz = (Double_t) 0.; } else { btz = TMath::Sqrt((Double_t) 1. - btt); } } else { btx = 0.; bty = 0.; btz = 1.; } // from kG to T b /= (Double_t) 10.; } <commit_msg>Bug in assignment of coordinates corrected.<commit_after>#include "TVirtualMCApplication.h" #include "Fdblprc.h" //(DBLPRC) fluka common // // #include "TCallf77.h" #ifndef WIN32 #define magfld magfld_ #define type_of_call #else #define magfld MAGFLD #define type_of_call _stdcall #endif extern "C" void type_of_call magfld(double& x, double& y, double& z, double& btx, double& bty, double& btz, double& b, int& /*nreg*/,int& idisc) { /* *----------------------------------------------------------------------* * * * * * Input variables: * * x,y,z = current position * * nreg = current region * * Output variables: * * btx,bty,btz = cosines of the magn. field vector * * B = magnetic field intensity (Tesla) * * idisc = set to 1 if the particle has to be discarded * * * *----------------------------------------------------------------------* */ idisc = 0; Double_t bc[3]; Double_t xc[3]; xc[0] = x; xc[1] = y; xc[2] = z; (TVirtualMCApplication::Instance())->Field(xc, bc); b = sqrt(bc[0] * bc[0] + bc[1] * bc[1] + bc[2] * bc[2]); if (b) { btx = bc[1]/b; bty = bc[0]/b; Double_t btt = btx * btx + bty * bty; if (btt >= (Double_t) 1.) { btx /= TMath::Sqrt(btt); bty /= TMath::Sqrt(btt); b /= TMath::Sqrt(btt); btz = (Double_t) 0.; } else { btz = TMath::Sqrt((Double_t) 1. - btt); } } else { btx = 0.; bty = 0.; btz = 1.; } // from kG to T b /= (Double_t) 10.; } <|endoftext|>
<commit_before>#include <Riostream.h> #include "AliRun.h" #include "TFluka.h" #ifndef WIN32 # define stupre stupre_ #else # define stupre STUPRE #endif // // Fluka include #include "Fdimpar.h" //(DIMPAR) fluka include // Fluka commons #include "Fdblprc.h" //(DBLPRC) fluka common #include "Femfstk.h" //(EMFSTK) fluka common #include "Fevtflg.h" //(EVTFLG) fluka common #include "Fpaprop.h" //(PAPROP) fluka common #include "Ftrackr.h" //(TRACKR) fluka common //Virtual MC #include "TFluka.h" #include "TVirtualMCStack.h" #include "TVirtualMCApplication.h" #include "TParticle.h" #include "TVector3.h" extern "C" { void stupre() { //*----------------------------------------------------------------------* //* * //* SeT User PRoperties for Emf particles * //* * //*----------------------------------------------------------------------* Int_t lbhabh = 0; if (EVTFLG.ldltry == 1) { if (EMFSTK.iq[EMFSTK.np-1] * EMFSTK.iq[EMFSTK.np-2] < 0) lbhabh = 1; } // mkbmx1 = dimension for kwb real spare array in fluka stack in DIMPAR // mkbmx2 = dimension for kwb int. spare array in fluka stack in DIMPAR // EMFSTK.espark = spare real variables available for // EMFSTK.iespak = spare integer variables available for // TRACKR.spausr = user defined spare variables for the current particle // TRACKR.ispusr = user defined spare flags for the current particle // EMFSTK.louemf = user flag // TRACKR.llouse = user defined flag for the current particle Int_t npnw, ispr; for (npnw=EMFSTK.npstrt-1; npnw<=EMFSTK.np-1; npnw++) { for (ispr=0; ispr<=mkbmx1-1; ispr++) EMFSTK.espark[npnw][ispr] = TRACKR.spausr[ispr]; for (ispr=0; ispr<=mkbmx2-1; ispr++) EMFSTK.iespak[npnw][ispr] = TRACKR.ispusr[ispr]; EMFSTK.louemf[npnw] = TRACKR.llouse; } // Get the pointer to the VMC TVirtualMC* fluka = TFluka::GetMC(); // Get the stack produced from the generator TVirtualMCStack* cppstack = fluka->GetStack(); // EVTFLG.ntrcks = track number // Increment the track number and put it into the last flag Int_t kp; for (kp = EMFSTK.npstrt-1; npnw <= EMFSTK.np-1; kp++) { //* save the parent track number and reset it at each loop Int_t done = 1; Int_t parent = TRACKR.ispusr[mkbmx2-1]; Int_t flukaid = 0; if (EMFSTK.iq[kp] == -1) flukaid = 3; else if (EMFSTK.iq[kp] == 0) flukaid = 7; else if (EMFSTK.iq[kp] == 0) flukaid = 4; Int_t pdg = fluka->PDGFromId(flukaid); Double_t e = EMFSTK.e[kp]*emvgev; Double_t p = sqrt(e*e - PAPROP.am[flukaid+6] * PAPROP.am[flukaid+6]); Double_t px = p * EMFSTK.u[kp]; Double_t pz = p * EMFSTK.v[kp]; Double_t py = p * EMFSTK.w[kp]; Double_t tof = EMFSTK.agemf[kp]; Double_t polx = EMFSTK.upol[kp]; Double_t poly = EMFSTK.vpol[kp]; Double_t polz = EMFSTK.wpol[kp]; Double_t vx = EMFSTK.x[kp]; Double_t vy = EMFSTK.y[kp]; Double_t vz = EMFSTK.z[kp]; Double_t weight = EMFSTK.wt[kp]; Int_t ntr; TMCProcess mech; Int_t is = 0; //* case of no parent left (pair, photoelectric, annihilation): //* all secondaries are true if ((EVTFLG.lpairp == 1) || (EVTFLG.lphoel == 1) || (EVTFLG.lannfl == 1) || (EVTFLG.lannrs == 1)) { if (EVTFLG.lpairp == 1) mech = kPPair; else if (EVTFLG.lphoel == 1) mech = kPPhotoelectric; else mech = kPAnnihilation; cppstack->SetTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof, polx, poly, polz, mech, ntr, weight, is); cout << endl << " !!! stupre: ntr=" << ntr << " parent=" << parent << endl; EMFSTK.iespak[kp][mkbmx2-1] = ntr; } // end of lpairp, lphoel, lannfl, lannrs //* Compton: secondary is true only if charged (e+, e-) else if ((EVTFLG.lcmptn == 1)) { if (EMFSTK.iq[kp] != 0) { mech = kPCompton; cppstack->SetTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof, polx, poly, polz, mech, ntr, weight, is); cout << endl << " !!! stupre: ntr=" << ntr << " parent=" << parent << endl; EMFSTK.iespak[kp][mkbmx2-1] = ntr; } } // end of lcmptn //* Bremsstrahlung: true secondary only if charge = 0 (photon) else if ((EVTFLG.lbrmsp == 1)) { if (EMFSTK.iq[kp] == 0) { mech = kPBrem; cppstack->SetTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof, polx, poly, polz, mech, ntr, weight, is); cout << endl << " !!! stupre: ntr=" << ntr << " parent=" << parent << endl; EMFSTK.iespak[kp][mkbmx2-1] = ntr; } } // end of lbrmsp //* Delta ray: If Bhabha, true secondary only if negative (electron) else if ((EVTFLG.ldltry == 1)) { if (lbhabh == 1) { if (EMFSTK.iq[kp] == 0) { mech = kPDeltaRay; cppstack->SetTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof, polx, poly, polz, mech, ntr, weight, is); EMFSTK.iespak[kp][mkbmx2-1] = ntr; } // end of Bhabha } //* Delta ray: Otherwise Moller: true secondary is the electron with //* lower energy, which has been put higher in the stack else if (kp == EMFSTK.np) { mech = kPDeltaRay; cppstack->SetTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof, polx, poly, polz, mech, ntr, weight, is); cout << endl << " !!! stupre: ntr=" << ntr << " parent=" << parent << endl; EMFSTK.iespak[kp][mkbmx2-1] = ntr; } // end of Delta ray } // end of ldltry } // end of loop // !!! TO BE CONFIRMED !!! EVTFLG.ntrcks = EMFSTK.iespak[EMFSTK.np-1][mkbmx2-1]; } // end of stupre } // end of extern "C" <commit_msg>Correct loop over secondaries.<commit_after>#include <Riostream.h> #include "AliRun.h" #include "TFluka.h" #ifndef WIN32 # define stupre stupre_ #else # define stupre STUPRE #endif // // Fluka include #include "Fdimpar.h" //(DIMPAR) fluka include // Fluka commons #include "Fdblprc.h" //(DBLPRC) fluka common #include "Femfstk.h" //(EMFSTK) fluka common #include "Fevtflg.h" //(EVTFLG) fluka common #include "Fpaprop.h" //(PAPROP) fluka common #include "Ftrackr.h" //(TRACKR) fluka common //Virtual MC #include "TFluka.h" #include "TVirtualMCStack.h" #include "TVirtualMCApplication.h" #include "TParticle.h" #include "TVector3.h" extern "C" { void stupre() { //*----------------------------------------------------------------------* //* * //* SeT User PRoperties for Emf particles * //* * //*----------------------------------------------------------------------* Int_t lbhabh = 0; if (EVTFLG.ldltry == 1) { if (EMFSTK.iq[EMFSTK.np-1] * EMFSTK.iq[EMFSTK.np-2] < 0) lbhabh = 1; } // mkbmx1 = dimension for kwb real spare array in fluka stack in DIMPAR // mkbmx2 = dimension for kwb int. spare array in fluka stack in DIMPAR // EMFSTK.espark = spare real variables available for // EMFSTK.iespak = spare integer variables available for // TRACKR.spausr = user defined spare variables for the current particle // TRACKR.ispusr = user defined spare flags for the current particle // EMFSTK.louemf = user flag // TRACKR.llouse = user defined flag for the current particle Int_t npnw, ispr; for (npnw=EMFSTK.npstrt-1; npnw<=EMFSTK.np-1; npnw++) { for (ispr=0; ispr<=mkbmx1-1; ispr++) EMFSTK.espark[npnw][ispr] = TRACKR.spausr[ispr]; for (ispr=0; ispr<=mkbmx2-1; ispr++) EMFSTK.iespak[npnw][ispr] = TRACKR.ispusr[ispr]; EMFSTK.louemf[npnw] = TRACKR.llouse; } // Get the pointer to the VMC TVirtualMC* fluka = TFluka::GetMC(); // Get the stack produced from the generator TVirtualMCStack* cppstack = fluka->GetStack(); // EVTFLG.ntrcks = track number // Increment the track number and put it into the last flag Int_t kp; for (kp = EMFSTK.npstrt - 1; kp <= EMFSTK.np - 1; kp++) { //* save the parent track number and reset it at each loop Int_t done = 1; Int_t parent = TRACKR.ispusr[mkbmx2-1]; Int_t flukaid = 0; if (EMFSTK.iq[kp] == -1) flukaid = 3; else if (EMFSTK.iq[kp] == 0) flukaid = 7; else if (EMFSTK.iq[kp] == 0) flukaid = 4; Int_t pdg = fluka->PDGFromId(flukaid); Double_t e = EMFSTK.e[kp] * emvgev; Double_t p = sqrt(e * e - PAPROP.am[flukaid+6] * PAPROP.am[flukaid+6]); Double_t px = p * EMFSTK.u[kp]; Double_t pz = p * EMFSTK.v[kp]; Double_t py = p * EMFSTK.w[kp]; Double_t tof = EMFSTK.agemf[kp]; Double_t polx = EMFSTK.upol[kp]; Double_t poly = EMFSTK.vpol[kp]; Double_t polz = EMFSTK.wpol[kp]; Double_t vx = EMFSTK.x[kp]; Double_t vy = EMFSTK.y[kp]; Double_t vz = EMFSTK.z[kp]; Double_t weight = EMFSTK.wt[kp]; Int_t ntr; TMCProcess mech; Int_t is = 0; //* case of no parent left (pair, photoelectric, annihilation): //* all secondaries are true if ((EVTFLG.lpairp == 1) || (EVTFLG.lphoel == 1) || (EVTFLG.lannfl == 1) || (EVTFLG.lannrs == 1)) { if (EVTFLG.lpairp == 1) mech = kPPair; else if (EVTFLG.lphoel == 1) mech = kPPhotoelectric; else mech = kPAnnihilation; cppstack->SetTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof, polx, poly, polz, mech, ntr, weight, is); cout << endl << " !!! stupre (PAIR, ..) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl; EMFSTK.iespak[kp][mkbmx2-1] = ntr; } // end of lpairp, lphoel, lannfl, lannrs //* Compton: secondary is true only if charged (e+, e-) else if ((EVTFLG.lcmptn == 1)) { if (EMFSTK.iq[kp] != 0) { mech = kPCompton; cppstack->SetTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof, polx, poly, polz, mech, ntr, weight, is); cout << endl << " !!! stupre (COMPTON) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl; EMFSTK.iespak[kp][mkbmx2-1] = ntr; } } // end of lcmptn //* Bremsstrahlung: true secondary only if charge = 0 (photon) else if ((EVTFLG.lbrmsp == 1)) { if (EMFSTK.iq[kp] == 0) { mech = kPBrem; cppstack->SetTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof, polx, poly, polz, mech, ntr, weight, is); cout << endl << " !!! stupre (BREMS) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl; EMFSTK.iespak[kp][mkbmx2-1] = ntr; } } // end of lbrmsp //* Delta ray: If Bhabha, true secondary only if negative (electron) else if ((EVTFLG.ldltry == 1)) { if (lbhabh == 1) { if (EMFSTK.iq[kp] == -1) { mech = kPDeltaRay; cppstack->SetTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof, polx, poly, polz, mech, ntr, weight, is); EMFSTK.iespak[kp][mkbmx2-1] = ntr; cout << endl << " !!! stupre (BHABA) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl; } // end of Bhabha } // lbhabh == 1 //* Delta ray: Otherwise Moller: true secondary is the electron with //* lower energy, which has been put higher in the stack else if (kp == EMFSTK.np-1) { mech = kPDeltaRay; cppstack->SetTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof, polx, poly, polz, mech, ntr, weight, is); cout << endl << " !!! stupre (Moller) : ntr=" << ntr << "pdg " << pdg << " parent=" << parent << endl; EMFSTK.iespak[kp][mkbmx2-1] = ntr; } // end of Delta ray } // end of ldltry } // end of loop // !!! TO BE CONFIRMED !!! // EVTFLG.ntrcks = EMFSTK.iespak[EMFSTK.np-1][mkbmx2-1]; } // end of stupre } // end of extern "C" <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions Inc. 1990-2013. All rights reserved */ // TEST Foundation::Containers::SortedSet // STATUS PRELIMINARY #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #include "Stroika/Foundation/Containers/SortedSet.h" #include "Stroika/Foundation/Containers/Concrete/SortedSet_stdset.h" #include "Stroika/Foundation/Debug/Assertions.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Memory/Optional.h" #include "../TestCommon/CommonTests_Set.h" #include "../TestHarness/SimpleClass.h" #include "../TestHarness/TestHarness.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using Concrete::SortedSet_stdset; namespace { template <typename CONTAINER_OF_T> void Check_ (const CONTAINER_OF_T& s) { typedef typename CONTAINER_OF_T::ElementType T; // verify in sorted order Memory::Optional<T> last; for (T i : s) { if (last.IsPresent ()) { VerifyTestResult (typename CONTAINER_OF_T::TraitsType::WellOrderCompareFunctionType::Compare (*last, i) <= 0); //VerifyTestResult (*last < i or (*last == i)); } last = i; } } void DoRegressionTests_ () { using namespace CommonTests::SetTests; #if 0 typedef typename CONCRETE_CONTAINER::ElementType T; typedef typename CONCRETE_CONTAINER::TraitsType TraitsType; #endif auto testFunc1 = [] (const SortedSet<size_t>& s) { Check_ (s); }; auto testFunc2 = [] (const SortedSet<SimpleClass>& s) { Check_ (s); }; Test_All_For_Type<SortedSet_stdset<size_t>, SortedSet<size_t>> (testFunc1); Test_All_For_Type<SortedSet_stdset<SimpleClass>, SortedSet<SimpleClass>> (testFunc2); Test_All_For_Type<SortedSet<size_t>, SortedSet<size_t>> (testFunc1); Test_All_For_Type<SortedSet<SimpleClass>, SortedSet<SimpleClass>> (testFunc2); } } int main (int argc, const char* argv[]) { Stroika::TestHarness::Setup (); Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); return EXIT_SUCCESS; } <commit_msg>minor tweaks (gcc compat) for sortedset regtest<commit_after>/* * Copyright(c) Sophist Solutions Inc. 1990-2013. All rights reserved */ // TEST Foundation::Containers::SortedSet // STATUS PRELIMINARY #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #include "Stroika/Foundation/Containers/SortedSet.h" #include "Stroika/Foundation/Containers/Concrete/SortedSet_stdset.h" #include "Stroika/Foundation/Debug/Assertions.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Memory/Optional.h" #include "../TestCommon/CommonTests_Set.h" #include "../TestHarness/SimpleClass.h" #include "../TestHarness/TestHarness.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using Concrete::SortedSet_stdset; namespace { template <typename CONTAINER_OF_T> void Check_ (const CONTAINER_OF_T& s) { typedef typename CONTAINER_OF_T::ElementType T; // verify in sorted order Memory::Optional<T> last; for (T i : s) { if (last.IsPresent ()) { VerifyTestResult (CONTAINER_OF_T::TraitsType::WellOrderCompareFunctionType::Compare (*last, i) <= 0); //VerifyTestResult (*last < i or (*last == i)); } last = i; } } void DoRegressionTests_ () { using namespace CommonTests::SetTests; #if 0 typedef typename CONCRETE_CONTAINER::ElementType T; typedef typename CONCRETE_CONTAINER::TraitsType TraitsType; #endif auto testFunc1 = [] (const SortedSet<size_t>& s) { Check_ (s); }; auto testFunc2 = [] (const SortedSet<SimpleClass>& s) { Check_ (s); }; Test_All_For_Type<SortedSet_stdset<size_t>, SortedSet<size_t>> (testFunc1); Test_All_For_Type<SortedSet_stdset<SimpleClass>, SortedSet<SimpleClass>> (testFunc2); Test_All_For_Type<SortedSet<size_t>, SortedSet<size_t>> (testFunc1); Test_All_For_Type<SortedSet<SimpleClass>, SortedSet<SimpleClass>> (testFunc2); } } int main (int argc, const char* argv[]) { Stroika::TestHarness::Setup (); Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015-present ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/test/unit_test.hpp> #include <seastar/testing/test_case.hh> #include <seastar/testing/thread_test_case.hh> #include "test/boost/sstable_test.hh" #include <seastar/core/thread.hh> #include "sstables/sstables.hh" #include "test/lib/mutation_source_test.hh" #include "test/lib/sstable_utils.hh" #include "row_cache.hh" #include "test/lib/simple_schema.hh" #include "partition_slice_builder.hh" #include "test/lib/flat_mutation_reader_assertions.hh" #include "test/lib/random_utils.hh" #include "test/lib/random_schema.hh" using namespace sstables; using namespace std::chrono_literals; static mutation_source make_sstable_mutation_source(sstables::test_env& env, schema_ptr s, sstring dir, std::vector<mutation> mutations, sstable_writer_config cfg, sstables::sstable::version_types version, gc_clock::time_point query_time = gc_clock::now()) { return as_mutation_source(make_sstable(env, s, dir, std::move(mutations), cfg, version, query_time)); } static void consume_all(flat_mutation_reader& rd) { while (auto mfopt = rd().get0()) {} } // It is assumed that src won't change. static snapshot_source snapshot_source_from_snapshot(mutation_source src) { return snapshot_source([src = std::move(src)] { return src; }); } static void test_cache_population_with_range_tombstone_adjacent_to_population_range(populate_fn_ex populate) { simple_schema s; tests::reader_concurrency_semaphore_wrapper semaphore; auto cache_mt = make_lw_shared<memtable>(s.schema()); auto pkey = s.make_pkey(); // underlying should not be empty, otherwise cache will make the whole range continuous mutation m1(s.schema(), pkey); s.add_row(m1, s.make_ckey(0), "v1"); s.add_row(m1, s.make_ckey(1), "v2"); s.add_row(m1, s.make_ckey(2), "v3"); s.delete_range(m1, s.make_ckey_range(2, 100)); cache_mt->apply(m1); cache_tracker tracker; auto ms = populate(s.schema(), std::vector<mutation>({m1}), gc_clock::now()); row_cache cache(s.schema(), snapshot_source_from_snapshot(std::move(ms)), tracker); auto pr = dht::partition_range::make_singular(pkey); auto populate_range = [&] (int start) { auto slice = partition_slice_builder(*s.schema()) .with_range(query::clustering_range::make_singular(s.make_ckey(start))) .build(); auto rd = cache.make_reader(s.schema(), semaphore.make_permit(), pr, slice); auto close_rd = deferred_close(rd); consume_all(rd); }; populate_range(2); // The cache now has only row with ckey 2 populated and the rest is discontinuous. // Populating reader which stops populating at entry with ckey 2 should not forget // to emit range_tombstone which starts at before(2). assert_that(cache.make_reader(s.schema(), semaphore.make_permit())) .produces(m1) .produces_end_of_stream(); } static future<> test_sstable_conforms_to_mutation_source(sstable_version_types version, int index_block_size) { return sstables::test_env::do_with_async([version, index_block_size] (sstables::test_env& env) { sstable_writer_config cfg = env.manager().configure_writer(); cfg.promoted_index_block_size = index_block_size; std::vector<tmpdir> dirs; auto populate = [&env, &dirs, &cfg, version] (schema_ptr s, const std::vector<mutation>& partitions, gc_clock::time_point query_time) -> mutation_source { dirs.emplace_back(); return make_sstable_mutation_source(env, s, dirs.back().path().string(), partitions, cfg, version, query_time); }; run_mutation_source_tests(populate); if (index_block_size == 1) { // The tests below are not sensitive to index bock size so run once. test_cache_population_with_range_tombstone_adjacent_to_population_range(populate); } }); } static constexpr std::array<int, 3> block_sizes = { 1, 128, 64 * 1024 }; // Split for better parallelizm SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_tiny) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[0]); } SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_medium) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[1]); } SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_large) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[2]); } SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_tiny) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[0]); } SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_medium) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[1]); } SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_large) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[2]); } // This assert makes sure we don't miss writable vertions static_assert(writable_sstable_versions.size() == 2); // TODO: could probably be placed in random_utils/random_schema after some tuning static std::vector<query::clustering_range> random_ranges(const std::vector<clustering_key> keys, const schema& s, std::mt19937& engine) { std::vector<clustering_key_prefix> ckp_sample; for (auto& k: keys) { auto exploded = k.explode(s); auto key_size = tests::random::get_int<size_t>(1, exploded.size(), engine); ckp_sample.push_back(clustering_key_prefix::from_exploded(s, std::vector<bytes>{exploded.begin(), exploded.begin() + key_size})); } auto subset_size = tests::random::get_int<size_t>(0, ckp_sample.size(), engine); ckp_sample = tests::random::random_subset<clustering_key_prefix>(std::move(ckp_sample), subset_size, engine); std::sort(ckp_sample.begin(), ckp_sample.end(), clustering_key_prefix::less_compare(s)); std::vector<query::clustering_range> ranges; // (-inf, ... if (!ckp_sample.empty() && tests::random::get_bool(engine)) { ranges.emplace_back( std::nullopt, query::clustering_range::bound{ckp_sample.front(), tests::random::get_bool(engine)}); std::swap(ckp_sample.front(), ckp_sample.back()); ckp_sample.pop_back(); } // ..., +inf) std::optional<query::clustering_range> last_range; if (!ckp_sample.empty() && tests::random::get_bool(engine)) { last_range.emplace( query::clustering_range::bound{ckp_sample.back(), tests::random::get_bool(engine)}, std::nullopt); ckp_sample.pop_back(); } for (int i = 0; i + 1 < ckp_sample.size(); i += 2) { ranges.emplace_back( query::clustering_range::bound{ckp_sample[i], tests::random::get_bool(engine)}, query::clustering_range::bound{ckp_sample[i+1], tests::random::get_bool(engine)}); } if (last_range) { ranges.push_back(std::move(*last_range)); } if (ranges.empty()) { // no keys sampled, return (-inf, +inf) ranges.push_back(query::clustering_range::make_open_ended_both_sides()); } return ranges; } SEASTAR_THREAD_TEST_CASE(test_sstable_reversing_reader_random_schema) { // Create two sources: one by creating an sstable from a set of mutations, // and one by creating an sstable from the same set of mutations but reversed. // We query the first source in forward mode and the second in reversed mode. // The two queries should return the same result. auto random_spec = tests::make_random_schema_specification(get_name()); auto random_schema = tests::random_schema{tests::random::get_int<uint32_t>(), *random_spec}; testlog.debug("Random schema:\n{}", random_schema.cql()); auto muts = tests::generate_random_mutations(random_schema).get(); std::vector<mutation> reversed_muts; for (auto& m : muts) { reversed_muts.push_back(reverse(m)); } // FIXME: workaround for #9352. The index pages for reversed source would sometimes be different // from the forward source, causing one source to hit the bug from #9352 but not the other. muts.erase(std::remove_if(muts.begin(), muts.end(), [] (auto& m) { return m.decorated_key().token() == dht::token::from_int64(0); })); sstables::test_env::do_with([ s = random_schema.schema(), muts = std::move(muts), reversed_muts = std::move(reversed_muts), version = writable_sstable_versions[1]] (sstables::test_env& env) { std::vector<tmpdir> dirs; sstable_writer_config cfg = env.manager().configure_writer(); for (auto index_block_size: block_sizes) { cfg.promoted_index_block_size = index_block_size; dirs.emplace_back(); auto source = make_sstable_mutation_source(env, s, dirs.back().path().string(), muts, cfg, version); dirs.emplace_back(); auto rev_source = make_sstable_mutation_source(env, s->make_reversed(), dirs.back().path().string(), reversed_muts, cfg, version); tests::reader_concurrency_semaphore_wrapper semaphore; std::mt19937 engine{tests::random::get_int<uint32_t>()}; std::vector<clustering_key> keys; for (const auto& m: muts) { for (auto& r: m.partition().clustered_rows()) { keys.push_back(r.key()); } } auto slice = partition_slice_builder(*s) .with_ranges(random_ranges(keys, *s, engine)) .build(); testlog.trace("Slice: {}", slice); for (const auto& m: muts) { auto prange = dht::partition_range::make_singular(m.decorated_key()); auto r1 = source.make_reader(s, semaphore.make_permit(), prange, slice, default_priority_class(), nullptr, streamed_mutation::forwarding::no, mutation_reader::forwarding::no); auto close_r1 = deferred_action([&r1] { r1.close().get(); }); auto rev_slice = native_reverse_slice_to_legacy_reverse_slice(*s, slice); rev_slice.options.set(query::partition_slice::option::reversed); auto r2 = rev_source.make_reader(s, semaphore.make_permit(), prange, rev_slice, default_priority_class(), nullptr, streamed_mutation::forwarding::no, mutation_reader::forwarding::no); close_r1.cancel(); compare_readers(*s, std::move(r1), std::move(r2)); } } }).get(); } <commit_msg>test: test_sstable_reversing_reader_random_schema: fix the workaround for #9352<commit_after>/* * Copyright (C) 2015-present ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/test/unit_test.hpp> #include <seastar/testing/test_case.hh> #include <seastar/testing/thread_test_case.hh> #include "test/boost/sstable_test.hh" #include <seastar/core/thread.hh> #include "sstables/sstables.hh" #include "test/lib/mutation_source_test.hh" #include "test/lib/sstable_utils.hh" #include "row_cache.hh" #include "test/lib/simple_schema.hh" #include "partition_slice_builder.hh" #include "test/lib/flat_mutation_reader_assertions.hh" #include "test/lib/random_utils.hh" #include "test/lib/random_schema.hh" using namespace sstables; using namespace std::chrono_literals; static mutation_source make_sstable_mutation_source(sstables::test_env& env, schema_ptr s, sstring dir, std::vector<mutation> mutations, sstable_writer_config cfg, sstables::sstable::version_types version, gc_clock::time_point query_time = gc_clock::now()) { return as_mutation_source(make_sstable(env, s, dir, std::move(mutations), cfg, version, query_time)); } static void consume_all(flat_mutation_reader& rd) { while (auto mfopt = rd().get0()) {} } // It is assumed that src won't change. static snapshot_source snapshot_source_from_snapshot(mutation_source src) { return snapshot_source([src = std::move(src)] { return src; }); } static void test_cache_population_with_range_tombstone_adjacent_to_population_range(populate_fn_ex populate) { simple_schema s; tests::reader_concurrency_semaphore_wrapper semaphore; auto cache_mt = make_lw_shared<memtable>(s.schema()); auto pkey = s.make_pkey(); // underlying should not be empty, otherwise cache will make the whole range continuous mutation m1(s.schema(), pkey); s.add_row(m1, s.make_ckey(0), "v1"); s.add_row(m1, s.make_ckey(1), "v2"); s.add_row(m1, s.make_ckey(2), "v3"); s.delete_range(m1, s.make_ckey_range(2, 100)); cache_mt->apply(m1); cache_tracker tracker; auto ms = populate(s.schema(), std::vector<mutation>({m1}), gc_clock::now()); row_cache cache(s.schema(), snapshot_source_from_snapshot(std::move(ms)), tracker); auto pr = dht::partition_range::make_singular(pkey); auto populate_range = [&] (int start) { auto slice = partition_slice_builder(*s.schema()) .with_range(query::clustering_range::make_singular(s.make_ckey(start))) .build(); auto rd = cache.make_reader(s.schema(), semaphore.make_permit(), pr, slice); auto close_rd = deferred_close(rd); consume_all(rd); }; populate_range(2); // The cache now has only row with ckey 2 populated and the rest is discontinuous. // Populating reader which stops populating at entry with ckey 2 should not forget // to emit range_tombstone which starts at before(2). assert_that(cache.make_reader(s.schema(), semaphore.make_permit())) .produces(m1) .produces_end_of_stream(); } static future<> test_sstable_conforms_to_mutation_source(sstable_version_types version, int index_block_size) { return sstables::test_env::do_with_async([version, index_block_size] (sstables::test_env& env) { sstable_writer_config cfg = env.manager().configure_writer(); cfg.promoted_index_block_size = index_block_size; std::vector<tmpdir> dirs; auto populate = [&env, &dirs, &cfg, version] (schema_ptr s, const std::vector<mutation>& partitions, gc_clock::time_point query_time) -> mutation_source { dirs.emplace_back(); return make_sstable_mutation_source(env, s, dirs.back().path().string(), partitions, cfg, version, query_time); }; run_mutation_source_tests(populate); if (index_block_size == 1) { // The tests below are not sensitive to index bock size so run once. test_cache_population_with_range_tombstone_adjacent_to_population_range(populate); } }); } static constexpr std::array<int, 3> block_sizes = { 1, 128, 64 * 1024 }; // Split for better parallelizm SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_tiny) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[0]); } SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_medium) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[1]); } SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_large) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[2]); } SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_tiny) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[0]); } SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_medium) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[1]); } SEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_large) { return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[2]); } // This assert makes sure we don't miss writable vertions static_assert(writable_sstable_versions.size() == 2); // TODO: could probably be placed in random_utils/random_schema after some tuning static std::vector<query::clustering_range> random_ranges(const std::vector<clustering_key> keys, const schema& s, std::mt19937& engine) { std::vector<clustering_key_prefix> ckp_sample; for (auto& k: keys) { auto exploded = k.explode(s); auto key_size = tests::random::get_int<size_t>(1, exploded.size(), engine); ckp_sample.push_back(clustering_key_prefix::from_exploded(s, std::vector<bytes>{exploded.begin(), exploded.begin() + key_size})); } auto subset_size = tests::random::get_int<size_t>(0, ckp_sample.size(), engine); ckp_sample = tests::random::random_subset<clustering_key_prefix>(std::move(ckp_sample), subset_size, engine); std::sort(ckp_sample.begin(), ckp_sample.end(), clustering_key_prefix::less_compare(s)); std::vector<query::clustering_range> ranges; // (-inf, ... if (!ckp_sample.empty() && tests::random::get_bool(engine)) { ranges.emplace_back( std::nullopt, query::clustering_range::bound{ckp_sample.front(), tests::random::get_bool(engine)}); std::swap(ckp_sample.front(), ckp_sample.back()); ckp_sample.pop_back(); } // ..., +inf) std::optional<query::clustering_range> last_range; if (!ckp_sample.empty() && tests::random::get_bool(engine)) { last_range.emplace( query::clustering_range::bound{ckp_sample.back(), tests::random::get_bool(engine)}, std::nullopt); ckp_sample.pop_back(); } for (int i = 0; i + 1 < ckp_sample.size(); i += 2) { ranges.emplace_back( query::clustering_range::bound{ckp_sample[i], tests::random::get_bool(engine)}, query::clustering_range::bound{ckp_sample[i+1], tests::random::get_bool(engine)}); } if (last_range) { ranges.push_back(std::move(*last_range)); } if (ranges.empty()) { // no keys sampled, return (-inf, +inf) ranges.push_back(query::clustering_range::make_open_ended_both_sides()); } return ranges; } SEASTAR_THREAD_TEST_CASE(test_sstable_reversing_reader_random_schema) { // Create two sources: one by creating an sstable from a set of mutations, // and one by creating an sstable from the same set of mutations but reversed. // We query the first source in forward mode and the second in reversed mode. // The two queries should return the same result. auto random_spec = tests::make_random_schema_specification(get_name()); auto random_schema = tests::random_schema{tests::random::get_int<uint32_t>(), *random_spec}; testlog.debug("Random schema:\n{}", random_schema.cql()); auto muts = tests::generate_random_mutations(random_schema).get(); // FIXME: workaround for #9352. The index pages for reversed source would sometimes be different // from the forward source, causing one source to hit the bug from #9352 but not the other. muts.erase(std::remove_if(muts.begin(), muts.end(), [] (auto& m) { return m.decorated_key().token() == dht::token::from_int64(0); })); std::vector<mutation> reversed_muts; for (auto& m : muts) { reversed_muts.push_back(reverse(m)); } sstables::test_env::do_with([ s = random_schema.schema(), muts = std::move(muts), reversed_muts = std::move(reversed_muts), version = writable_sstable_versions[1]] (sstables::test_env& env) { std::vector<tmpdir> dirs; sstable_writer_config cfg = env.manager().configure_writer(); for (auto index_block_size: block_sizes) { cfg.promoted_index_block_size = index_block_size; dirs.emplace_back(); auto source = make_sstable_mutation_source(env, s, dirs.back().path().string(), muts, cfg, version); dirs.emplace_back(); auto rev_source = make_sstable_mutation_source(env, s->make_reversed(), dirs.back().path().string(), reversed_muts, cfg, version); tests::reader_concurrency_semaphore_wrapper semaphore; std::mt19937 engine{tests::random::get_int<uint32_t>()}; std::vector<clustering_key> keys; for (const auto& m: muts) { for (auto& r: m.partition().clustered_rows()) { keys.push_back(r.key()); } } auto slice = partition_slice_builder(*s) .with_ranges(random_ranges(keys, *s, engine)) .build(); testlog.trace("Slice: {}", slice); for (const auto& m: muts) { auto prange = dht::partition_range::make_singular(m.decorated_key()); auto r1 = source.make_reader(s, semaphore.make_permit(), prange, slice, default_priority_class(), nullptr, streamed_mutation::forwarding::no, mutation_reader::forwarding::no); auto close_r1 = deferred_action([&r1] { r1.close().get(); }); auto rev_slice = native_reverse_slice_to_legacy_reverse_slice(*s, slice); rev_slice.options.set(query::partition_slice::option::reversed); auto r2 = rev_source.make_reader(s, semaphore.make_permit(), prange, rev_slice, default_priority_class(), nullptr, streamed_mutation::forwarding::no, mutation_reader::forwarding::no); close_r1.cancel(); compare_readers(*s, std::move(r1), std::move(r2)); } } }).get(); } <|endoftext|>
<commit_before>#include <iostream> #include <ctime> #include <fstream> #include <Windows.h> #include <string> #include "..\include\Game.h" #include "..\include\Common.h" #include "..\include\PlayerTypes\PlayerTypes.h" #include "..\include\EnemyTypes\EnemyTypes.h" using namespace std; using namespace Common; // To avoid conflict with numeric_limits<streamsize>::max used in Game::GetChoice() #ifdef max #undef max #endif void Game::MainMenu(){ // Main menu. Loops until you start // a game or quit. for (int choice=0; choice!=3;){ choice = GetChoice(MenuType::eMain); switch(choice){ case 1: StartGame(); break; case 2: HowToPlay(); break; case 3: break; } } } string Game::InitializePlayerName() { ClearScreen(); string name; cout << "What is your name?" << endl << endl << "> "; cin.ignore(); getline(cin,name); // Change to full name return name; } int Game::InitializePlayerClass() { // Initializes the player's class through user choice. int player_class = 0; player_class = GetChoice(MenuType::ePlayerClass); SetPlayerClass(player_class); return player_class; } void Game::SetPlayerClass(int player_class) { // Sets the Player class according to player code given. switch (player_class) { case 1: // Player's class is a warrior. _Player = new Warrior; break; case 2: // Player's class is a rogue. _Player = new Rogue; break; case 3: // Player's class is a healer. _Player = new Healer; break; case 4: // Player's class is a debugger. // Used to easily defeat enemies. Only for development purposes. _Player = new Debugger; break; case 5: // You are Saitama. // Do I have to explain?? _Player = new Saitama; break; default: // If input does not equal any of the cases, the default class is a warrior. _Player = new Warrior; break; } } void Game::SetPlayerData(){ /* Data initialized in order of: * class code * name * level * experience * health * arrows * bombs * potions * whetstones * weaponstrength * coins */ ifstream ReadData; ReadData.open("data.txt"); // Runs if user has never played the game before or data is not found. if (!ReadData) { ReadData.close(); ofstream WriteData; WriteData.open("data.txt"); WriteData << InitializePlayerClass() << endl << InitializePlayerName() << endl << 1 << endl << 0 << endl << 100 << endl << 10 << endl << 1 << endl << 1 << endl << 1 << endl << 100 << endl << 0; WriteData.close(); } else { // Initializes player type from class code given in data.txt int player_class; ReadData >> player_class; SetPlayerClass(player_class); ReadData.close(); } } void Game::SetEnemy(){ // Generates a random integer to determine class of the enemy. // The abstract class Enemy is morphed with one of its child classes. EnemyType selector = rand()%etNumEnemyTypes; switch(selector){ case etCrab: // Enemy is a crab. _Enemy = new Crab; break; case etGiantCrab: // Enemy is a giant crab. _Enemy = new GiantCrab; break; case etSquid: // Enemy is a squid. _Enemy = new Squid; break; case etGiantSquid: // Enemy is a giant squid. _Enemy = new GiantSquid; break; case etLich: // Enemy is a Lich _Enemy = new Lich; break; case etVampire: // Enemy is a Vampire _Enemy = new Vampire; break; case etWerewolf: // Enemy is a Werewolf _Enemy = new Werewolf; break; case etGoblin: // Enemy is a Goblin _Enemy = new Goblin; break; case etGargoyle: // Enemy is a Goblin _Enemy = new Gargoyle; break; default: // If the above cases do not match the selector for any reason, // the enemy defaults on the crab class. _Enemy = new Crab; break; } // Simply prints that the enemy's class was encountered. ColourPrint(_Enemy->GetName(), DARK_GREY); cout << " encountered!" << endl << endl; Sleep(SLEEP_MS); } bool Game::PlayAgain(){ // Returns a bool value to determine if the player wants to play again. char choice; cout << "Keep going? (y/n)" << endl << endl; choice = (char)input(); // Returns true if the player says yes (Y, y, 1). if (choice == 'y' || choice == 'Y' || choice == '1') return true; // Returns false otherwise, regardless of choice=='n'. return false; } void Game::Intermission(){ // Saves game in case player unexpectedly quits (uses X instead of // in-game quit. _Player->SaveGame(); // Loops until the player starts another battle or they quit (IsPlaying=false). for (int choice=0; IsPlaying;){ ClearScreen(); cout << "*--------- Intermission ----------* " << endl << endl; _Player->DisplayInventory(); cout << "1) Start battle" << endl; cout << "2) Store" << endl; cout << "3) Gamble" << endl; cout << "4) Use Item" << endl; cout << "5) Quit" << endl << endl; choice = input(); switch(choice){ case 1: // Returns to StartGame()'s loop, calling Battle(). return; case 2: // Goes to the store where the player can buy items. /// Currently in working progress. _Store.StoreFront(_Player); break; case 3: // Goes to the gambling arena. // _Player is passed in to add items won to the player inventory. _Gambling.Gamble(_Player); break; case 4: _Player->UseItem(); _Player->SaveGame(); break; case 5: // Breaks the loop in StartGame(), going back to MainMenu(). IsPlaying=false; break; } } } void Game::StartGame(){ // Starts the game by initializing values for a new game. // Seeds the random number generator for pseudo-random numbers. srand((unsigned int)time(NULL)); IsPlaying=true; // SetPlayerData() initializes the variables in this end. ClearScreen(); SetPlayerData(); // This initializes the variables on the Player end. ClearScreen(); _Player->SetPlayerData(); // Loops while the game is still playing. // Alternates between battles and intermission (gambling, store, et) while(IsPlaying){ Intermission(); if (!IsPlaying) break; Battle(); } // Saves the player's data to an external file before quitting. _Player->SaveGame(); } void Game::Battle(){ ClearScreen(); // Uses random integers to determine class of the enemy. SetEnemy(); // Loops the actual battle while playing. while(IsPlaying){ ClearScreen(); // Displays the name and health bar of the player and enemy. // The Enemy* argument is to display the enemy's // name. Explained more in _Player->DisplayHealthBar(). _Player->DisplayHUD(_Enemy); _Enemy->DisplayHUD(); // Player's turn to attack Enemy. _Enemy->TakeDamage(_Player->Attack()); // Pauses console and ignores user input for SLEEP_MS milliseconds. Sleep(SLEEP_MS); // Leaves battle if player chooses to. if (!IsPlaying){ IsPlaying = true; return; } // Executes when the enemy's health is 0 or below. if (_Enemy->IsDead()){ // Adds drops to player's inventory from defeated enemy. _Player->AddToInventory(_Enemy->GetDrops()); // Adds points to player's experience. _Player->AddExperience(_Enemy->ReturnExperience()); // Replenishes player's health for the next round. _Player->ReplenishHealth(); // If player wants to battle again, it breaks the loop and uses tail recursion to play again. if (PlayAgain()) break; // Returns to StartGame()'s loop, and executes Intermission(). return; } // Enemy's turn to attack player. _Player->TakeDamage(_Enemy->Attack()); Sleep(SLEEP_MS); // Executes when player's health is 0 or below. if (_Player->IsDead()){ // Player loses the amount of experience points gained when you defeat the enemy. _Player->LoseExperience(_Enemy->ReturnExperience()); // Replenishes player's health for the next round. _Player->ReplenishHealth(); if (PlayAgain()) break; return; } } Battle(); } void Game::HowToPlay() { GetChoice(MenuType::eHowToPlay); } int Game::GetChoice(MenuType menuType) { DisplayMenu(menuType); int choice = -1; while (!(cin >> choice)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid input. Please try again."; Sleep(SLEEP_MS); DisplayMenu(menuType); } return choice; } void Game::DisplayMenu(MenuType menuType) { ClearScreen(); switch (menuType) { case Game::eMain: cout << "========== TURN-BASED FIGHTING GAME ==========" << endl << endl << "1) Start Game" << endl << "2) How to play" << endl << "3) Exit" << endl << endl << "> "; break; case Game::ePlayerClass: cout << endl << "Which class do you want to play as?" << endl << "1) Warrior (high damage, low healing capabilities)" << endl << "2) Rogue (moderate damage, moderate healing capabilities)" << endl << "3) Healer (low damage, high healing capabilities)" << endl << "4) Debugger (INFINITE DAMAGE!!!!)" << endl << "5) Saitama (self-explanatory)" << endl << endl << endl << "> "; break; case Game::eHowToPlay: cout << "============== HOW TO PLAY ==============" << endl << endl << "Turn is a turn-based RPG game." << endl << "Create your character and start playing." << endl << "For playing you have to choose what to do by typing" << endl << "the corresponding number." << endl << "You can perform actions and use items." << endl << endl << "-- Actions --" << endl << "Attack: Regular attack" << endl << "Risk Attack: Attack deals more damage, but with a chance of missing" << endl << "Heal: Restore an amount of your HP" << endl << "Flee: Run away from battle" << endl << endl << "-- Items --" << endl << "Bombs: Deals 50HP to your opponent with no chance of missing" << endl << "Arrows: Deals 10-15HP to your opponent with no chance of missing" << endl << "Potion: Replenishes your HP to 100" << endl << "Whetstone: Restores your weapon's sharpness." << endl << endl << "Good luck and have fun!" << endl << endl << "1) Quit" << endl << endl << "> "; break; default: break; } } <commit_msg>Fix build error.<commit_after>#include <iostream> #include <ctime> #include <fstream> #include <Windows.h> #include <string> #include "..\include\Game.h" #include "..\include\Common.h" #include "..\include\PlayerTypes\PlayerTypes.h" #include "..\include\EnemyTypes\EnemyTypes.h" using namespace std; using namespace Common; // To avoid conflict with numeric_limits<streamsize>::max used in Game::GetChoice() #ifdef max #undef max #endif void Game::MainMenu(){ // Main menu. Loops until you start // a game or quit. for (int choice=0; choice!=3;){ choice = GetChoice(MenuType::eMain); switch(choice){ case 1: StartGame(); break; case 2: HowToPlay(); break; case 3: break; } } } string Game::InitializePlayerName() { ClearScreen(); string name; cout << "What is your name?" << endl << endl << "> "; cin.ignore(); getline(cin,name); // Change to full name return name; } int Game::InitializePlayerClass() { // Initializes the player's class through user choice. int player_class = 0; player_class = GetChoice(MenuType::ePlayerClass); SetPlayerClass(player_class); return player_class; } void Game::SetPlayerClass(int player_class) { // Sets the Player class according to player code given. switch (player_class) { case 1: // Player's class is a warrior. _Player = new Warrior; break; case 2: // Player's class is a rogue. _Player = new Rogue; break; case 3: // Player's class is a healer. _Player = new Healer; break; case 4: // Player's class is a debugger. // Used to easily defeat enemies. Only for development purposes. _Player = new Debugger; break; case 5: // You are Saitama. // Do I have to explain?? _Player = new Saitama; break; default: // If input does not equal any of the cases, the default class is a warrior. _Player = new Warrior; break; } } void Game::SetPlayerData(){ /* Data initialized in order of: * class code * name * level * experience * health * arrows * bombs * potions * whetstones * weaponstrength * coins */ ifstream ReadData; ReadData.open("data.txt"); // Runs if user has never played the game before or data is not found. if (!ReadData) { ReadData.close(); ofstream WriteData; WriteData.open("data.txt"); WriteData << InitializePlayerClass() << endl << InitializePlayerName() << endl << 1 << endl << 0 << endl << 100 << endl << 10 << endl << 1 << endl << 1 << endl << 1 << endl << 100 << endl << 0; WriteData.close(); } else { // Initializes player type from class code given in data.txt int player_class; ReadData >> player_class; SetPlayerClass(player_class); ReadData.close(); } } void Game::SetEnemy(){ // Generates a random integer to determine class of the enemy. // The abstract class Enemy is morphed with one of its child classes. EnemyType selector = EnemyType(rand()%etNumEnemyTypes); switch(selector){ case etCrab: // Enemy is a crab. _Enemy = new Crab; break; case etGiantCrab: // Enemy is a giant crab. _Enemy = new GiantCrab; break; case etSquid: // Enemy is a squid. _Enemy = new Squid; break; case etGiantSquid: // Enemy is a giant squid. _Enemy = new GiantSquid; break; case etLich: // Enemy is a Lich _Enemy = new Lich; break; case etVampire: // Enemy is a Vampire _Enemy = new Vampire; break; case etWerewolf: // Enemy is a Werewolf _Enemy = new Werewolf; break; case etGoblin: // Enemy is a Goblin _Enemy = new Goblin; break; case etGargoyle: // Enemy is a Goblin _Enemy = new Gargoyle; break; default: // If the above cases do not match the selector for any reason, // the enemy defaults on the crab class. _Enemy = new Crab; break; } // Simply prints that the enemy's class was encountered. ColourPrint(_Enemy->GetName(), DARK_GREY); cout << " encountered!" << endl << endl; Sleep(SLEEP_MS); } bool Game::PlayAgain(){ // Returns a bool value to determine if the player wants to play again. char choice; cout << "Keep going? (y/n)" << endl << endl; choice = (char)input(); // Returns true if the player says yes (Y, y, 1). if (choice == 'y' || choice == 'Y' || choice == '1') return true; // Returns false otherwise, regardless of choice=='n'. return false; } void Game::Intermission(){ // Saves game in case player unexpectedly quits (uses X instead of // in-game quit. _Player->SaveGame(); // Loops until the player starts another battle or they quit (IsPlaying=false). for (int choice=0; IsPlaying;){ ClearScreen(); cout << "*--------- Intermission ----------* " << endl << endl; _Player->DisplayInventory(); cout << "1) Start battle" << endl; cout << "2) Store" << endl; cout << "3) Gamble" << endl; cout << "4) Use Item" << endl; cout << "5) Quit" << endl << endl; choice = input(); switch(choice){ case 1: // Returns to StartGame()'s loop, calling Battle(). return; case 2: // Goes to the store where the player can buy items. /// Currently in working progress. _Store.StoreFront(_Player); break; case 3: // Goes to the gambling arena. // _Player is passed in to add items won to the player inventory. _Gambling.Gamble(_Player); break; case 4: _Player->UseItem(); _Player->SaveGame(); break; case 5: // Breaks the loop in StartGame(), going back to MainMenu(). IsPlaying=false; break; } } } void Game::StartGame(){ // Starts the game by initializing values for a new game. // Seeds the random number generator for pseudo-random numbers. srand((unsigned int)time(NULL)); IsPlaying=true; // SetPlayerData() initializes the variables in this end. ClearScreen(); SetPlayerData(); // This initializes the variables on the Player end. ClearScreen(); _Player->SetPlayerData(); // Loops while the game is still playing. // Alternates between battles and intermission (gambling, store, et) while(IsPlaying){ Intermission(); if (!IsPlaying) break; Battle(); } // Saves the player's data to an external file before quitting. _Player->SaveGame(); } void Game::Battle(){ ClearScreen(); // Uses random integers to determine class of the enemy. SetEnemy(); // Loops the actual battle while playing. while(IsPlaying){ ClearScreen(); // Displays the name and health bar of the player and enemy. // The Enemy* argument is to display the enemy's // name. Explained more in _Player->DisplayHealthBar(). _Player->DisplayHUD(_Enemy); _Enemy->DisplayHUD(); // Player's turn to attack Enemy. _Enemy->TakeDamage(_Player->Attack()); // Pauses console and ignores user input for SLEEP_MS milliseconds. Sleep(SLEEP_MS); // Leaves battle if player chooses to. if (!IsPlaying){ IsPlaying = true; return; } // Executes when the enemy's health is 0 or below. if (_Enemy->IsDead()){ // Adds drops to player's inventory from defeated enemy. _Player->AddToInventory(_Enemy->GetDrops()); // Adds points to player's experience. _Player->AddExperience(_Enemy->ReturnExperience()); // Replenishes player's health for the next round. _Player->ReplenishHealth(); // If player wants to battle again, it breaks the loop and uses tail recursion to play again. if (PlayAgain()) break; // Returns to StartGame()'s loop, and executes Intermission(). return; } // Enemy's turn to attack player. _Player->TakeDamage(_Enemy->Attack()); Sleep(SLEEP_MS); // Executes when player's health is 0 or below. if (_Player->IsDead()){ // Player loses the amount of experience points gained when you defeat the enemy. _Player->LoseExperience(_Enemy->ReturnExperience()); // Replenishes player's health for the next round. _Player->ReplenishHealth(); if (PlayAgain()) break; return; } } Battle(); } void Game::HowToPlay() { GetChoice(MenuType::eHowToPlay); } int Game::GetChoice(MenuType menuType) { DisplayMenu(menuType); int choice = -1; while (!(cin >> choice)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid input. Please try again."; Sleep(SLEEP_MS); DisplayMenu(menuType); } return choice; } void Game::DisplayMenu(MenuType menuType) { ClearScreen(); switch (menuType) { case Game::eMain: cout << "========== TURN-BASED FIGHTING GAME ==========" << endl << endl << "1) Start Game" << endl << "2) How to play" << endl << "3) Exit" << endl << endl << "> "; break; case Game::ePlayerClass: cout << endl << "Which class do you want to play as?" << endl << "1) Warrior (high damage, low healing capabilities)" << endl << "2) Rogue (moderate damage, moderate healing capabilities)" << endl << "3) Healer (low damage, high healing capabilities)" << endl << "4) Debugger (INFINITE DAMAGE!!!!)" << endl << "5) Saitama (self-explanatory)" << endl << endl << endl << "> "; break; case Game::eHowToPlay: cout << "============== HOW TO PLAY ==============" << endl << endl << "Turn is a turn-based RPG game." << endl << "Create your character and start playing." << endl << "For playing you have to choose what to do by typing" << endl << "the corresponding number." << endl << "You can perform actions and use items." << endl << endl << "-- Actions --" << endl << "Attack: Regular attack" << endl << "Risk Attack: Attack deals more damage, but with a chance of missing" << endl << "Heal: Restore an amount of your HP" << endl << "Flee: Run away from battle" << endl << endl << "-- Items --" << endl << "Bombs: Deals 50HP to your opponent with no chance of missing" << endl << "Arrows: Deals 10-15HP to your opponent with no chance of missing" << endl << "Potion: Replenishes your HP to 100" << endl << "Whetstone: Restores your weapon's sharpness." << endl << endl << "Good luck and have fun!" << endl << endl << "1) Quit" << endl << endl << "> "; break; default: break; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QDeclarativeEngine> #include <QDeclarativeComponent> #include <private/qdeclarativemetatype_p.h> #include <QDebug> #include <QGraphicsScene> #include <QGraphicsItem> #include <QDeclarativeItem> #include <QDeclarativeContext> #include <private/qobject_p.h> #ifdef Q_OS_SYMBIAN // In Symbian OS test data is located in applications private dir // Application private dir is default serach path for files, so SRCDIR can be set to empty #define SRCDIR "" #endif class tst_creation : public QObject { Q_OBJECT public: tst_creation() {} private slots: void qobject_cpp(); void qobject_qml(); void qobject_qmltype(); void qobject_alloc(); void qdeclarativecontext(); void objects_qmltype_data(); void objects_qmltype(); void qgraphicsitem(); void qgraphicsobject(); void qgraphicsitem14(); void qgraphicsitem_tree14(); void itemtree_notree_cpp(); void itemtree_objtree_cpp(); void itemtree_cpp(); void itemtree_data_cpp(); void itemtree_qml(); void itemtree_scene_cpp(); private: QDeclarativeEngine engine; }; inline QUrl TEST_FILE(const QString &filename) { return QUrl::fromLocalFile(QLatin1String(SRCDIR) + QLatin1String("/data/") + filename); } void tst_creation::qobject_cpp() { QBENCHMARK { QObject *obj = new QObject; delete obj; } } void tst_creation::qobject_qml() { QDeclarativeComponent component(&engine, TEST_FILE("qobject.qml")); QObject *obj = component.create(); delete obj; QBENCHMARK { QObject *obj = component.create(); delete obj; } } void tst_creation::qobject_qmltype() { QDeclarativeType *t = QDeclarativeMetaType::qmlType("Qt/QtObject", 4, 6); QBENCHMARK { QObject *obj = t->create(); delete obj; } } struct QObjectFakeData { char data[sizeof(QObjectPrivate)]; }; struct QObjectFake { QObjectFake(); virtual ~QObjectFake(); private: QObjectFakeData *d; }; QObjectFake::QObjectFake() { d = new QObjectFakeData; } QObjectFake::~QObjectFake() { delete d; } void tst_creation::qobject_alloc() { QBENCHMARK { QObjectFake *obj = new QObjectFake; delete obj; } } void tst_creation::qdeclarativecontext() { QBENCHMARK { QDeclarativeContext *ctxt = new QDeclarativeContext(&engine); delete ctxt; } } void tst_creation::objects_qmltype_data() { QTest::addColumn<QByteArray>("type"); QList<QByteArray> types = QDeclarativeMetaType::qmlTypeNames(); foreach (QByteArray type, types) QTest::newRow(type.constData()) << type; } void tst_creation::objects_qmltype() { QFETCH(QByteArray, type); QDeclarativeType *t = QDeclarativeMetaType::qmlType(type, 4, 6); if (!t || !t->isCreatable()) QSKIP("Non-creatable type", SkipSingle); QBENCHMARK { QObject *obj = t->create(); delete obj; } } class QGraphicsItemDummy : public QGraphicsItem { public: virtual QRectF boundingRect() const { return QRectF(); } virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} }; class QGraphicsObjectDummy : public QGraphicsObject { public: virtual QRectF boundingRect() const { return QRectF(); } virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} }; void tst_creation::qgraphicsitem() { QBENCHMARK { QGraphicsItemDummy *i = new QGraphicsItemDummy(); delete i; } } void tst_creation::qgraphicsobject() { QBENCHMARK { QGraphicsObjectDummy *i = new QGraphicsObjectDummy(); delete i; } } void tst_creation::qgraphicsitem14() { QBENCHMARK { QGraphicsItemDummy *i1 = new QGraphicsItemDummy(); QGraphicsItemDummy *i2 = new QGraphicsItemDummy(); QGraphicsItemDummy *i3 = new QGraphicsItemDummy(); QGraphicsItemDummy *i4 = new QGraphicsItemDummy(); QGraphicsItemDummy *i5 = new QGraphicsItemDummy(); QGraphicsItemDummy *i6 = new QGraphicsItemDummy(); QGraphicsItemDummy *i7 = new QGraphicsItemDummy(); QGraphicsItemDummy *i8 = new QGraphicsItemDummy(); QGraphicsItemDummy *i9 = new QGraphicsItemDummy(); QGraphicsItemDummy *i10 = new QGraphicsItemDummy(); QGraphicsItemDummy *i11 = new QGraphicsItemDummy(); QGraphicsItemDummy *i12 = new QGraphicsItemDummy(); QGraphicsItemDummy *i13 = new QGraphicsItemDummy(); QGraphicsItemDummy *i14 = new QGraphicsItemDummy(); delete i1; delete i2; delete i3; delete i4; delete i5; delete i6; delete i7; delete i8; delete i9; delete i10; delete i11; delete i12; delete i13; delete i14; } } void tst_creation::qgraphicsitem_tree14() { QBENCHMARK { // i1 // +-------------------------+ // i2 i3 // +-----------+ +-----+-----+ // i4 i5 i6 i7 // +----+ +--+ +--+--+ +----+ // i8 i9 i10 i11 i12 i13 i14 QGraphicsItemDummy *i1 = new QGraphicsItemDummy(); QGraphicsItemDummy *i2 = new QGraphicsItemDummy(); QGraphicsItemDummy *i3 = new QGraphicsItemDummy(); QGraphicsItemDummy *i4 = new QGraphicsItemDummy(); QGraphicsItemDummy *i5 = new QGraphicsItemDummy(); QGraphicsItemDummy *i6 = new QGraphicsItemDummy(); QGraphicsItemDummy *i7 = new QGraphicsItemDummy(); QGraphicsItemDummy *i8 = new QGraphicsItemDummy(); QGraphicsItemDummy *i9 = new QGraphicsItemDummy(); QGraphicsItemDummy *i10 = new QGraphicsItemDummy(); QGraphicsItemDummy *i11 = new QGraphicsItemDummy(); QGraphicsItemDummy *i12 = new QGraphicsItemDummy(); QGraphicsItemDummy *i13 = new QGraphicsItemDummy(); QGraphicsItemDummy *i14 = new QGraphicsItemDummy(); i14->setParentItem(i7); i13->setParentItem(i7); i12->setParentItem(i6); i11->setParentItem(i6); i10->setParentItem(i5); i9->setParentItem(i4); i8->setParentItem(i4); i7->setParentItem(i3); i6->setParentItem(i3); i5->setParentItem(i2); i4->setParentItem(i2); i3->setParentItem(i1); i2->setParentItem(i1); delete i1; } } struct QDeclarativeGraphics_DerivedObject : public QObject { void setParent_noEvent(QObject *parent) { bool sce = d_ptr->sendChildEvents; d_ptr->sendChildEvents = false; setParent(parent); d_ptr->sendChildEvents = sce; } }; inline void QDeclarativeGraphics_setParent_noEvent(QObject *object, QObject *parent) { static_cast<QDeclarativeGraphics_DerivedObject *>(object)->setParent_noEvent(parent); } void tst_creation::itemtree_notree_cpp() { QBENCHMARK { QDeclarativeItem *item = new QDeclarativeItem; for (int i = 0; i < 30; ++i) { QDeclarativeItem *child = new QDeclarativeItem; } delete item; } } void tst_creation::itemtree_objtree_cpp() { QBENCHMARK { QDeclarativeItem *item = new QDeclarativeItem; for (int i = 0; i < 30; ++i) { QDeclarativeItem *child = new QDeclarativeItem; QDeclarativeGraphics_setParent_noEvent(child,item); } delete item; } } void tst_creation::itemtree_cpp() { QBENCHMARK { QDeclarativeItem *item = new QDeclarativeItem; for (int i = 0; i < 30; ++i) { QDeclarativeItem *child = new QDeclarativeItem; QDeclarativeGraphics_setParent_noEvent(child,item); child->setParentItem(item); } delete item; } } void tst_creation::itemtree_data_cpp() { QBENCHMARK { QDeclarativeItem *item = new QDeclarativeItem; for (int i = 0; i < 30; ++i) { QDeclarativeItem *child = new QDeclarativeItem; QDeclarativeGraphics_setParent_noEvent(child,item); QDeclarativeListReference ref(item, "data"); ref.append(child); } delete item; } } void tst_creation::itemtree_qml() { QDeclarativeComponent component(&engine, TEST_FILE("item.qml")); QObject *obj = component.create(); delete obj; QBENCHMARK { QObject *obj = component.create(); delete obj; } } void tst_creation::itemtree_scene_cpp() { QGraphicsScene scene; QDeclarativeItem *root = new QDeclarativeItem; scene.addItem(root); QBENCHMARK { QDeclarativeItem *item = new QDeclarativeItem; for (int i = 0; i < 30; ++i) { QDeclarativeItem *child = new QDeclarativeItem; QDeclarativeGraphics_setParent_noEvent(child,item); child->setParentItem(item); } item->setParentItem(root); delete item; } delete root; } QTEST_MAIN(tst_creation) #include "tst_creation.moc" <commit_msg>Tweak benchmark<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QDeclarativeEngine> #include <QDeclarativeComponent> #include <private/qdeclarativemetatype_p.h> #include <QDebug> #include <QGraphicsScene> #include <QGraphicsItem> #include <QDeclarativeItem> #include <QDeclarativeContext> #include <private/qobject_p.h> #ifdef Q_OS_SYMBIAN // In Symbian OS test data is located in applications private dir // Application private dir is default serach path for files, so SRCDIR can be set to empty #define SRCDIR "" #endif class tst_creation : public QObject { Q_OBJECT public: tst_creation() {} private slots: void qobject_cpp(); void qobject_qml(); void qobject_qmltype(); void qobject_alloc(); void qdeclarativecontext(); void objects_qmltype_data(); void objects_qmltype(); void qgraphicsitem(); void qgraphicsobject(); void qgraphicsitem14(); void qgraphicsitem_tree14(); void itemtree_notree_cpp(); void itemtree_objtree_cpp(); void itemtree_cpp(); void itemtree_data_cpp(); void itemtree_qml(); void itemtree_scene_cpp(); private: QDeclarativeEngine engine; }; inline QUrl TEST_FILE(const QString &filename) { return QUrl::fromLocalFile(QLatin1String(SRCDIR) + QLatin1String("/data/") + filename); } void tst_creation::qobject_cpp() { QBENCHMARK { QObject *obj = new QObject; delete obj; } } void tst_creation::qobject_qml() { QDeclarativeComponent component(&engine); component.setData("import Qt 4.6\nQtObject {}", QUrl()); QObject *obj = component.create(); delete obj; QBENCHMARK { QObject *obj = component.create(); delete obj; } } void tst_creation::qobject_qmltype() { QDeclarativeType *t = QDeclarativeMetaType::qmlType("Qt/QtObject", 4, 6); QBENCHMARK { QObject *obj = t->create(); delete obj; } } struct QObjectFakeData { char data[sizeof(QObjectPrivate)]; }; struct QObjectFake { QObjectFake(); virtual ~QObjectFake(); private: QObjectFakeData *d; }; QObjectFake::QObjectFake() { d = new QObjectFakeData; } QObjectFake::~QObjectFake() { delete d; } void tst_creation::qobject_alloc() { QBENCHMARK { QObjectFake *obj = new QObjectFake; delete obj; } } void tst_creation::qdeclarativecontext() { QBENCHMARK { QDeclarativeContext *ctxt = new QDeclarativeContext(&engine); delete ctxt; } } void tst_creation::objects_qmltype_data() { QTest::addColumn<QByteArray>("type"); QList<QByteArray> types = QDeclarativeMetaType::qmlTypeNames(); foreach (QByteArray type, types) QTest::newRow(type.constData()) << type; } void tst_creation::objects_qmltype() { QFETCH(QByteArray, type); QDeclarativeType *t = QDeclarativeMetaType::qmlType(type, 4, 6); if (!t || !t->isCreatable()) QSKIP("Non-creatable type", SkipSingle); QBENCHMARK { QObject *obj = t->create(); delete obj; } } class QGraphicsItemDummy : public QGraphicsItem { public: virtual QRectF boundingRect() const { return QRectF(); } virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} }; class QGraphicsObjectDummy : public QGraphicsObject { public: virtual QRectF boundingRect() const { return QRectF(); } virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} }; void tst_creation::qgraphicsitem() { QBENCHMARK { QGraphicsItemDummy *i = new QGraphicsItemDummy(); delete i; } } void tst_creation::qgraphicsobject() { QBENCHMARK { QGraphicsObjectDummy *i = new QGraphicsObjectDummy(); delete i; } } void tst_creation::qgraphicsitem14() { QBENCHMARK { QGraphicsItemDummy *i1 = new QGraphicsItemDummy(); QGraphicsItemDummy *i2 = new QGraphicsItemDummy(); QGraphicsItemDummy *i3 = new QGraphicsItemDummy(); QGraphicsItemDummy *i4 = new QGraphicsItemDummy(); QGraphicsItemDummy *i5 = new QGraphicsItemDummy(); QGraphicsItemDummy *i6 = new QGraphicsItemDummy(); QGraphicsItemDummy *i7 = new QGraphicsItemDummy(); QGraphicsItemDummy *i8 = new QGraphicsItemDummy(); QGraphicsItemDummy *i9 = new QGraphicsItemDummy(); QGraphicsItemDummy *i10 = new QGraphicsItemDummy(); QGraphicsItemDummy *i11 = new QGraphicsItemDummy(); QGraphicsItemDummy *i12 = new QGraphicsItemDummy(); QGraphicsItemDummy *i13 = new QGraphicsItemDummy(); QGraphicsItemDummy *i14 = new QGraphicsItemDummy(); delete i1; delete i2; delete i3; delete i4; delete i5; delete i6; delete i7; delete i8; delete i9; delete i10; delete i11; delete i12; delete i13; delete i14; } } void tst_creation::qgraphicsitem_tree14() { QBENCHMARK { // i1 // +-------------------------+ // i2 i3 // +-----------+ +-----+-----+ // i4 i5 i6 i7 // +----+ +--+ +--+--+ +----+ // i8 i9 i10 i11 i12 i13 i14 QGraphicsItemDummy *i1 = new QGraphicsItemDummy(); QGraphicsItemDummy *i2 = new QGraphicsItemDummy(); QGraphicsItemDummy *i3 = new QGraphicsItemDummy(); QGraphicsItemDummy *i4 = new QGraphicsItemDummy(); QGraphicsItemDummy *i5 = new QGraphicsItemDummy(); QGraphicsItemDummy *i6 = new QGraphicsItemDummy(); QGraphicsItemDummy *i7 = new QGraphicsItemDummy(); QGraphicsItemDummy *i8 = new QGraphicsItemDummy(); QGraphicsItemDummy *i9 = new QGraphicsItemDummy(); QGraphicsItemDummy *i10 = new QGraphicsItemDummy(); QGraphicsItemDummy *i11 = new QGraphicsItemDummy(); QGraphicsItemDummy *i12 = new QGraphicsItemDummy(); QGraphicsItemDummy *i13 = new QGraphicsItemDummy(); QGraphicsItemDummy *i14 = new QGraphicsItemDummy(); i14->setParentItem(i7); i13->setParentItem(i7); i12->setParentItem(i6); i11->setParentItem(i6); i10->setParentItem(i5); i9->setParentItem(i4); i8->setParentItem(i4); i7->setParentItem(i3); i6->setParentItem(i3); i5->setParentItem(i2); i4->setParentItem(i2); i3->setParentItem(i1); i2->setParentItem(i1); delete i1; } } struct QDeclarativeGraphics_DerivedObject : public QObject { void setParent_noEvent(QObject *parent) { bool sce = d_ptr->sendChildEvents; d_ptr->sendChildEvents = false; setParent(parent); d_ptr->sendChildEvents = sce; } }; inline void QDeclarativeGraphics_setParent_noEvent(QObject *object, QObject *parent) { static_cast<QDeclarativeGraphics_DerivedObject *>(object)->setParent_noEvent(parent); } void tst_creation::itemtree_notree_cpp() { QBENCHMARK { QDeclarativeItem *item = new QDeclarativeItem; for (int i = 0; i < 30; ++i) { QDeclarativeItem *child = new QDeclarativeItem; } delete item; } } void tst_creation::itemtree_objtree_cpp() { QBENCHMARK { QDeclarativeItem *item = new QDeclarativeItem; for (int i = 0; i < 30; ++i) { QDeclarativeItem *child = new QDeclarativeItem; QDeclarativeGraphics_setParent_noEvent(child,item); } delete item; } } void tst_creation::itemtree_cpp() { QBENCHMARK { QDeclarativeItem *item = new QDeclarativeItem; for (int i = 0; i < 30; ++i) { QDeclarativeItem *child = new QDeclarativeItem; QDeclarativeGraphics_setParent_noEvent(child,item); child->setParentItem(item); } delete item; } } void tst_creation::itemtree_data_cpp() { QBENCHMARK { QDeclarativeItem *item = new QDeclarativeItem; for (int i = 0; i < 30; ++i) { QDeclarativeItem *child = new QDeclarativeItem; QDeclarativeGraphics_setParent_noEvent(child,item); QDeclarativeListReference ref(item, "data"); ref.append(child); } delete item; } } void tst_creation::itemtree_qml() { QDeclarativeComponent component(&engine, TEST_FILE("item.qml")); QObject *obj = component.create(); delete obj; QBENCHMARK { QObject *obj = component.create(); delete obj; } } void tst_creation::itemtree_scene_cpp() { QGraphicsScene scene; QDeclarativeItem *root = new QDeclarativeItem; scene.addItem(root); QBENCHMARK { QDeclarativeItem *item = new QDeclarativeItem; for (int i = 0; i < 30; ++i) { QDeclarativeItem *child = new QDeclarativeItem; QDeclarativeGraphics_setParent_noEvent(child,item); child->setParentItem(item); } item->setParentItem(root); delete item; } delete root; } QTEST_MAIN(tst_creation) #include "tst_creation.moc" <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP #define STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP #include <stan/math/rev/core/chainablestack.hpp> namespace stan { namespace math { namespace { ChainableStack global_stack_instance_init; } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>#ifndef STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP #define STAN_MATH_REV_CORE_INIT_CHAINABLESTACK_HPP #include <stan/math/rev/core/chainablestack.hpp> namespace stan { namespace math { namespace { ChainableStack global_stack_instance_init; } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <hw/apic.hpp> #include <hw/ioport.hpp> #include <utility/membitmap.hpp> #define LAPIC_ID 0x20 #define LAPIC_VER 0x30 #define LAPIC_TPR 0x80 #define LAPIC_EOI 0x0B0 #define LAPIC_LDR 0x0D0 #define LAPIC_DFR 0x0E0 #define LAPIC_SPURIOUS 0x0F0 #define LAPIC_ESR 0x280 #define LAPIC_ICRL 0x300 #define LAPIC_ICRH 0x310 #define LAPIC_LVT_TMR 0x320 #define LAPIC_LVT_PERF 0x340 #define LAPIC_LVT_LINT0 0x350 #define LAPIC_LVT_LINT1 0x360 #define LAPIC_LVT_ERR 0x370 #define LAPIC_TMRINITCNT 0x380 #define LAPIC_TMRCURRCNT 0x390 #define LAPIC_TMRDIV 0x3E0 #define LAPIC_LAST 0x38F #define LAPIC_DISABLE 0x10000 #define LAPIC_SW_ENABLE 0x100 #define LAPIC_CPUFOCUS 0x200 #define LAPIC_NMI (4<<8) #define TMR_PERIODIC 0x20000 #define TMR_BASEDIV (1<<20) extern "C" { void apic_enable(); } namespace hw { static const uintptr_t IA32_APIC_BASE = 0x1B; uint64_t RDMSR(uint32_t addr) { uint32_t EAX = 0, EDX = 0; asm volatile("rdmsr": "=a" (EAX),"=d"(EDX) : "c" (addr)); return ((uint64_t)EDX << 32) | EAX; } // a single 16-byte aligned APIC register typedef uint32_t apic_reg; struct apic { apic(uintptr_t addr) : base_addr(addr) {} bool x2apic() const noexcept { return false; } apic_reg get_id() const noexcept { return (read(LAPIC_ID) >> 24) & 0xFF; } uint32_t read(apic_reg reg) const noexcept { auto volatile* addr = (uint32_t volatile*) base_addr; addr[0] = reg & 0xff; return addr[4]; } void write(apic_reg reg, uint32_t value) { auto volatile* addr = (uint32_t volatile*) base_addr; addr[0] = reg & 0xff; addr[4] = value; } uintptr_t base_addr; }; static apic lapic; void APIC::init() { const uint64_t APIC_BASE_MSR = RDMSR(IA32_APIC_BASE); // find the LAPICs base address const uintptr_t APIC_BASE_ADDR = APIC_BASE_MSR & 0xFFFFF000; printf("APIC base addr: 0x%x\n", APIC_BASE_ADDR); // acquire infos lapic = apic(APIC_BASE_ADDR); printf("LAPIC id: 0x%x\n", lapic.get_id()); apic_enable(); } } <commit_msg>apic: Fix construction<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <hw/apic.hpp> #include <hw/ioport.hpp> #include <utility/membitmap.hpp> #define LAPIC_ID 0x20 #define LAPIC_VER 0x30 #define LAPIC_TPR 0x80 #define LAPIC_EOI 0x0B0 #define LAPIC_LDR 0x0D0 #define LAPIC_DFR 0x0E0 #define LAPIC_SPURIOUS 0x0F0 #define LAPIC_ESR 0x280 #define LAPIC_ICRL 0x300 #define LAPIC_ICRH 0x310 #define LAPIC_LVT_TMR 0x320 #define LAPIC_LVT_PERF 0x340 #define LAPIC_LVT_LINT0 0x350 #define LAPIC_LVT_LINT1 0x360 #define LAPIC_LVT_ERR 0x370 #define LAPIC_TMRINITCNT 0x380 #define LAPIC_TMRCURRCNT 0x390 #define LAPIC_TMRDIV 0x3E0 #define LAPIC_LAST 0x38F #define LAPIC_DISABLE 0x10000 #define LAPIC_SW_ENABLE 0x100 #define LAPIC_CPUFOCUS 0x200 #define LAPIC_NMI (4<<8) #define TMR_PERIODIC 0x20000 #define TMR_BASEDIV (1<<20) extern "C" { void apic_enable(); } namespace hw { static const uintptr_t IA32_APIC_BASE = 0x1B; uint64_t RDMSR(uint32_t addr) { uint32_t EAX = 0, EDX = 0; asm volatile("rdmsr": "=a" (EAX),"=d"(EDX) : "c" (addr)); return ((uint64_t)EDX << 32) | EAX; } // a single 16-byte aligned APIC register typedef uint32_t apic_reg; struct apic { apic(uintptr_t addr) : base_addr(addr) {} bool x2apic() const noexcept { return false; } apic_reg get_id() const noexcept { return (read(LAPIC_ID) >> 24) & 0xFF; } uint32_t read(apic_reg reg) const noexcept { auto volatile* addr = (uint32_t volatile*) base_addr; addr[0] = reg & 0xff; return addr[4]; } void write(apic_reg reg, uint32_t value) { auto volatile* addr = (uint32_t volatile*) base_addr; addr[0] = reg & 0xff; addr[4] = value; } uintptr_t base_addr; }; //static apic lapic; void APIC::init() { const uint64_t APIC_BASE_MSR = RDMSR(IA32_APIC_BASE); // find the LAPICs base address const uintptr_t APIC_BASE_ADDR = APIC_BASE_MSR & 0xFFFFF000; printf("APIC base addr: 0x%x\n", APIC_BASE_ADDR); // acquire infos apic lapic = apic(APIC_BASE_ADDR); printf("LAPIC id: 0x%x\n", lapic.get_id()); apic_enable(); } } <|endoftext|>
<commit_before>/*The following code implements the Knuth-Fisher-Yates linear time shuffling algorithm.*/ #include <iostream> #include <random> #include <ctime> void swap(int &, int &); int* shuffle(int*, int); int main() { int size = 0; char ch; std::cout << "Enter the size of the list." << std::endl; std::cin >> size; int *input = new int[size]; std::cout << "Enter the numbers." << std::endl; for(int i = 0; i < size; i++) std::cin >> input[i]; std::cout<<"Enter s to shuffle the list, q to quit."<< std::endl; while(1) { std::cin >> ch; if(ch != 's') // shuffles the list every time the user enters s break; int *result = shuffle(input, size); for(int i = 0; i < size; i++) std::cout << result[i] << " "; std::cout << "\n"; delete [] result; } std::cout << "Thank you."; delete [] input; } void swap(int &a, int &b) { int tmp = a; a = b; b = tmp; } int* shuffle(int *input, int size) { int range = size - 1, i = 0, j = size - 1, index = 0; int *output = new int[size]; std::mt19937 rand(time(0)); while(i != size) { std::uniform_int_distribution<int> roll(0, range); index = roll(rand); output[i] = input[index]; swap(input[index], input[j]); i++; range--; j--; } return output; }<commit_msg>Update<commit_after>/*The following code implements the Knuth-Fisher-Yates linear time shuffling algorithm.*/ #include <iostream> #include <random> #include <ctime> void swap(int &, int &); int* shuffle(int*, int); int main() { int size = 0; char ch; std::cout << "Enter the size of the list." << std::endl; std::cin >> size; int *input = new int[size]; std::cout << "Enter the numbers." << std::endl; for(int i = 0; i < size; i++) std::cin >> input[i]; std::cout<<"Enter s to shuffle the list, q to quit."<< std::endl; while(1) { std::cin >> ch; if(ch != 's') // shuffles the list every time the user enters s break; int *result = shuffle(input, size); for(int i = 0; i < size; i++) std::cout << result[i] << " "; std::cout << "\n"; delete [] result; } std::cout << "Thank you." << std::endl; delete [] input; } void swap(int &a, int &b) { int tmp = a; a = b; b = tmp; } int* shuffle(int *input, int size) { int range = size - 1, i = 0, j = size - 1, index = 0; int *output = new int[size]; std::mt19937 rand(time(0)); while(i != size) { std::uniform_int_distribution<int> roll(0, range); index = roll(rand); output[i] = input[index]; swap(input[index], input[j]); i++; range--; j--; } return output; }<|endoftext|>
<commit_before><commit_msg>Modified updateRowNumbers to use for loop<commit_after><|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS tbe11 (1.5.10); FILE MERGED 2004/07/15 17:47:18 tbe 1.5.10.4: #i31315# Rework Basic IDE Macro Chooser and Macro Organizer 2004/07/09 15:50:11 tbe 1.5.10.3: #i31315# Rework Basic IDE Macro Chooser and Macro Organizer 2004/06/23 08:33:32 tbe 1.5.10.2: #99468# Basic IDE cannot handle libraries, which contain dialogs only 2004/06/21 11:21:59 tbe 1.5.10.1: #99468# Basic IDE cannot handle libraries, which contain dialogs only<commit_after><|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE engine_tests #define BOOST_TEST_MAIN #define BOOST_TEST_LOG_LEVEL all #include <boost/test/unit_test.hpp> #include <iostream> #include <string> #include <vector> #include "../Source/UCI.hpp" #include "../Source/Search.hpp" #include "../Source/Board.hpp" #include "../Source/Evaluation.hpp" #include "../Source/MoveList.hpp" #include "../Source/TranspositionTables.hpp" using namespace std; void initMasks(); BOOST_AUTO_TEST_CASE(UCI_sentPosition) { initMasks(); Evaluation::initpopCountOfByte(); TranspositionTables::initZobrist(); cout << "Testing sentPosition function" << endl; BOOST_CHECK(UCI::sentPosition("position startpos moves e3e2") == false); BOOST_CHECK(UCI::sentPosition("position startpos moves e2e4") == true); BOOST_CHECK(UCI::sentPosition("position startpos") == false); BOOST_CHECK(UCI::sentPosition("position fen not a fen") == false); } BOOST_AUTO_TEST_CASE(evaluation_evaluateBoard) { cout << "Testing evaluateBoard function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); BOOST_CHECK(Evaluation::evaluateBoard(testBoard) == 0); //evaluation should be 0 for initial board testBoard = Board("7k/8/8/8/8/8/8/7K w - - 0 1"); BOOST_CHECK(Evaluation::evaluateBoard(testBoard) == 0); //no piece difference, symmetrical position } BOOST_AUTO_TEST_CASE(evaluation_CheckForDoublePawns) { Evaluation::initpopCountOfByte(); //initialising look-up table cout << "Testing CheckForDoublePawns function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 0); //No double pawns for white BOOST_CHECK(Evaluation::CheckForDoublePawns(7, testBoard) == 0); //No double pawns for black testBoard = Board("8/8/4kP2/8/5P2/PP1P2P1/PPP1P2P/3K4 w - - 0 1"); BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 3); //3 sets of white double pawns testBoard = Board("8/8/4kP2/8/5P2/PPPPP1PP/PPP1P2P/3K4 w - - 0 1"); BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 6); //6 sets of white double pawns testBoard = Board("4k3/pppppppp/pppppppp/2b2b2/P5P1/P1qK1PP1/P4PP1/6q1 w - - 0 1"); BOOST_CHECK(Evaluation::CheckForDoublePawns(7, testBoard) == 8); //8 sets of black double pawns } BOOST_AUTO_TEST_CASE(evaluation_rooksOnOpenFile) { cout << "Testing rooksOnOpenFile function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); int temp = Evaluation::CheckForDoublePawns(6, testBoard); //check for double pawns initialises array of open files temp = Evaluation::CheckForDoublePawns(7, testBoard); BOOST_CHECK(Evaluation::rooksOnOpenFile(6, testBoard) == 0); //no rooks on open file for white BOOST_CHECK(Evaluation::rooksOnOpenFile(7, testBoard) == 0); //no rooks on open file for black testBoard = Board("r2k1r2/pp2p1pp/8/5P2/7P/8/1P6/RRRKRRRR w - - 0 1"); temp = Evaluation::CheckForDoublePawns(6, testBoard); temp = Evaluation::CheckForDoublePawns(7, testBoard); BOOST_CHECK(Evaluation::rooksOnOpenFile(6, testBoard) == 4); //4 rooks on open file for white BOOST_CHECK(Evaluation::rooksOnOpenFile(7, testBoard) == 1); //1 rook on open file for black } BOOST_AUTO_TEST_CASE(board_inCheck) { cout << "Testing inCheck function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); BOOST_CHECK(testBoard.inCheck(6) == false); //white isn't in check BOOST_CHECK(testBoard.inCheck(7) == false); //black isn't in check testBoard = Board("4k3/8/4r3/8/8/8/8/4K3 w - - 0 1"); BOOST_CHECK(testBoard.inCheck(6) == true); //white is in check BOOST_CHECK(testBoard.inCheck(7) == false); //black isn't in check testBoard = Board("k1r5/8/1N6/8/8/8/8/4K3 w - - 0 1"); BOOST_CHECK(testBoard.inCheck(7) == true); //black is in check BOOST_CHECK(testBoard.inCheck(6) == false); //white isn't in check } BOOST_AUTO_TEST_CASE(board_simpleMakeMove) { cout << "Testing simpleMakeMove function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); pair<int, int> startPosition = make_pair('e' - 'a', '2' - '1'); pair<int, int> endPosition = make_pair('e' - 'a', '4' - '1'); testBoard.simpleMakeMove(startPosition, endPosition, ' '); BOOST_CHECK(testBoard.getPieceFromPos(3*8 + (7 - 4)) == 0); //pawn at e4 } BOOST_AUTO_TEST_CASE(board_takePiece) { cout << "Testing takePiece function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); testBoard.takePiece(make_pair(0, 0)); BOOST_CHECK(testBoard.getPieceFromPos(7) == -1); //piece has been removed } BOOST_AUTO_TEST_CASE(board_getPieceCode) { cout << "Testing getPieceCode function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); BOOST_CHECK(testBoard.getPieceCode('p') == 0); //pawn BOOST_CHECK(testBoard.getPieceCode('P') == 0); //pawn BOOST_CHECK(testBoard.getPieceCode('r') == 1); //rook BOOST_CHECK(testBoard.getPieceCode('R') == 1); //rook BOOST_CHECK(testBoard.getPieceCode('n') == 2); //knight BOOST_CHECK(testBoard.getPieceCode('N') == 2); //knight BOOST_CHECK(testBoard.getPieceCode('b') == 3); //bishop BOOST_CHECK(testBoard.getPieceCode('B') == 3); //bishop BOOST_CHECK(testBoard.getPieceCode('q') == 4); //queen BOOST_CHECK(testBoard.getPieceCode('Q') == 4); //queen BOOST_CHECK(testBoard.getPieceCode('k') == 5); //king BOOST_CHECK(testBoard.getPieceCode('K') == 5); //king } int getLegalMoves(Board testBoard, int playerColor) { MoveList possibleMoves = MoveList(testBoard, ((playerColor == 1) ? 6 : 7), u64(0)); u64 castle = testBoard.getCastleOrEnpasent(); u64 lastHash = testBoard.getZorHash(); int enpasCol = testBoard.getEnpasentCol(); int halfMoveNumber = testBoard.halfMoveClock; int legalMoves = 0; while (true) { u64 theMove = possibleMoves.getNextMove(); if (theMove) { testBoard.makeMov(theMove); if (testBoard.inCheck(((playerColor == 1) ? 6 : 7)) == false) { legalMoves++; } testBoard.unMakeMov(theMove, castle, enpasCol, lastHash, halfMoveNumber); } else { break; } } return legalMoves; } BOOST_AUTO_TEST_CASE(MoveList_generateMoves) { cout << "Testing MoveList class" << endl; Board testBoard = Board("k5R1/7R/8/8/8/8/8/K7 b - - 0 1"); BOOST_CHECK(getLegalMoves(testBoard, -1) == 0); //black is check mated testBoard = Board("k7/8/8/8/8/8/8/K7 w - - 0 1"); BOOST_CHECK(getLegalMoves(testBoard, 1) == 3); //only piece is king in corner testBoard = Board("k7/8/8/8/4K3/8/8/8 w - - 0 1"); BOOST_CHECK(getLegalMoves(testBoard, 1) == 8); //only piece is king in center } BOOST_AUTO_TEST_CASE(search_RootAlphaBeta) { cout << "Testing search" << endl; Board testBoard = Board("k7/pppp4/8/8/8/8/8/K4R2 w - - 0 1"); testBoard.setEvaluation(Evaluation::evaluateBoard(testBoard)); testBoard.stageOfGame = Evaluation::stageOfGame(testBoard); testBoard.setZorHash(TranspositionTables::getBoardHash(testBoard, 6)); vector<string> searchMoves; BOOST_CHECK(Search::RootAlphaBeta(testBoard, 1, 4, searchMoves).first == "f1f8"); //it should find the checkmate for white } //Perft is good for verifying the correctness of the move generation, generate all the leaf nodes at a given depth from a known position. //This also shows how fast the move generation works in relation to other engines (slow, magic bitboards would speed up move generation) u64 Perft(int depth, Board& gameBoard, int playerColor) { if (depth == 0) { if (gameBoard.inCheck(((playerColor == 1) ? 7 : 6)) == true) { return 0; } return 1; } u64 nodes = 0; u64 castle = gameBoard.getCastleOrEnpasent(); u64 lastHash = gameBoard.getZorHash(); int enpasCol = gameBoard.getEnpasentCol(); int halfMoveNumber = gameBoard.halfMoveClock; MoveList possibleMoves(gameBoard, ((playerColor == 1) ? 6 : 7), true); if (possibleMoves.kingTake) { return 0; } int movNumber = possibleMoves.getMoveNumber(); for (int i = 0; i < movNumber; i++) { u64 theMove = possibleMoves.getMovN(i); gameBoard.makeMov(theMove); //if (gameBoard.inCheck(((playerColor == 1) ? 6 : 7)) == false) { nodes += Perft(depth - 1, gameBoard, playerColor*-1); //} gameBoard.unMakeMov(theMove, castle, enpasCol, lastHash, halfMoveNumber); } return nodes; } BOOST_AUTO_TEST_CASE(perft_Test) { cout << "Testing move generation (perft), this is slow" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); //initial position BOOST_CHECK(Perft(4, testBoard, 1) == 197281); //Known value from the chess programming wiki http://chessprogramming.wikispaces.com/Perft+Results testBoard = Board("r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -"); BOOST_CHECK(Perft(4, testBoard, 1) == 4085603); testBoard = Board("8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -"); BOOST_CHECK(Perft(5, testBoard, 1) == 674624); testBoard = Board("r2q1rk1/pP1p2pp/Q4n2/bbp1p3/Np6/1B3NBn/pPPP1PPP/R3K2R b KQ - 0 1"); BOOST_CHECK(Perft(4, testBoard, -1) == 422333); testBoard = Board("rnbqkb1r/pp1p1ppp/2p5/4P3/2B5/8/PPP1NnPP/RNBQK2R w KQkq - 0 6"); BOOST_CHECK(Perft(3, testBoard, 1) == 53392); testBoard = Board("r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10"); BOOST_CHECK(Perft(4, testBoard, 1) == 3894594); } <commit_msg>Fixed Perft unit test<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE engine_tests #define BOOST_TEST_MAIN #define BOOST_TEST_LOG_LEVEL all #include <boost/test/unit_test.hpp> #include <iostream> #include <string> #include <vector> #include "../Source/UCI.hpp" #include "../Source/Search.hpp" #include "../Source/Board.hpp" #include "../Source/Evaluation.hpp" #include "../Source/MoveList.hpp" #include "../Source/TranspositionTables.hpp" using namespace std; void initMasks(); BOOST_AUTO_TEST_CASE(UCI_sentPosition) { //Initialising things initMasks(); Evaluation::initpopCountOfByte(); TranspositionTables::initZobrist(); cout << "Testing sentPosition function" << endl; BOOST_CHECK(UCI::sentPosition("position startpos moves e3e2") == false); BOOST_CHECK(UCI::sentPosition("position startpos moves e2e4") == true); BOOST_CHECK(UCI::sentPosition("position startpos") == false); BOOST_CHECK(UCI::sentPosition("position fen not a fen") == false); } BOOST_AUTO_TEST_CASE(evaluation_evaluateBoard) { cout << "Testing evaluateBoard function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); BOOST_CHECK(Evaluation::evaluateBoard(testBoard) == 0); //evaluation should be 0 for initial board testBoard = Board("7k/8/8/8/8/8/8/7K w - - 0 1"); BOOST_CHECK(Evaluation::evaluateBoard(testBoard) == 0); //no piece difference, symmetrical position } BOOST_AUTO_TEST_CASE(evaluation_CheckForDoublePawns) { cout << "Testing CheckForDoublePawns function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 0); //No double pawns for white BOOST_CHECK(Evaluation::CheckForDoublePawns(7, testBoard) == 0); //No double pawns for black testBoard = Board("8/8/4kP2/8/5P2/PP1P2P1/PPP1P2P/3K4 w - - 0 1"); BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 3); //3 sets of white double pawns testBoard = Board("8/8/4kP2/8/5P2/PPPPP1PP/PPP1P2P/3K4 w - - 0 1"); BOOST_CHECK(Evaluation::CheckForDoublePawns(6, testBoard) == 6); //6 sets of white double pawns testBoard = Board("4k3/pppppppp/pppppppp/2b2b2/P5P1/P1qK1PP1/P4PP1/6q1 w - - 0 1"); BOOST_CHECK(Evaluation::CheckForDoublePawns(7, testBoard) == 8); //8 sets of black double pawns } BOOST_AUTO_TEST_CASE(evaluation_rooksOnOpenFile) { cout << "Testing rooksOnOpenFile function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); int temp = Evaluation::CheckForDoublePawns(6, testBoard); //check for double pawns initialises array of open files temp = Evaluation::CheckForDoublePawns(7, testBoard); BOOST_CHECK(Evaluation::rooksOnOpenFile(6, testBoard) == 0); //no rooks on open file for white BOOST_CHECK(Evaluation::rooksOnOpenFile(7, testBoard) == 0); //no rooks on open file for black testBoard = Board("r2k1r2/pp2p1pp/8/5P2/7P/8/1P6/RRRKRRRR w - - 0 1"); temp = Evaluation::CheckForDoublePawns(6, testBoard); temp = Evaluation::CheckForDoublePawns(7, testBoard); BOOST_CHECK(Evaluation::rooksOnOpenFile(6, testBoard) == 4); //4 rooks on open file for white BOOST_CHECK(Evaluation::rooksOnOpenFile(7, testBoard) == 1); //1 rook on open file for black } BOOST_AUTO_TEST_CASE(board_inCheck) { cout << "Testing inCheck function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); BOOST_CHECK(testBoard.inCheck(6) == false); //white isn't in check BOOST_CHECK(testBoard.inCheck(7) == false); //black isn't in check testBoard = Board("4k3/8/4r3/8/8/8/8/4K3 w - - 0 1"); BOOST_CHECK(testBoard.inCheck(6) == true); //white is in check BOOST_CHECK(testBoard.inCheck(7) == false); //black isn't in check testBoard = Board("k1r5/8/1N6/8/8/8/8/4K3 w - - 0 1"); BOOST_CHECK(testBoard.inCheck(7) == true); //black is in check BOOST_CHECK(testBoard.inCheck(6) == false); //white isn't in check } BOOST_AUTO_TEST_CASE(board_simpleMakeMove) { cout << "Testing simpleMakeMove function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); pair<int, int> startPosition = make_pair('e' - 'a', '2' - '1'); pair<int, int> endPosition = make_pair('e' - 'a', '4' - '1'); testBoard.simpleMakeMove(startPosition, endPosition, ' '); BOOST_CHECK(testBoard.getPieceFromPos(3*8 + (7 - 4)) == 0); //pawn at e4 } BOOST_AUTO_TEST_CASE(board_takePiece) { cout << "Testing takePiece function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); testBoard.takePiece(make_pair(0, 0)); BOOST_CHECK(testBoard.getPieceFromPos(7) == -1); //piece has been removed } BOOST_AUTO_TEST_CASE(board_getPieceCode) { cout << "Testing getPieceCode function" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); BOOST_CHECK(testBoard.getPieceCode('p') == 0); //pawn BOOST_CHECK(testBoard.getPieceCode('P') == 0); //pawn BOOST_CHECK(testBoard.getPieceCode('r') == 1); //rook BOOST_CHECK(testBoard.getPieceCode('R') == 1); //rook BOOST_CHECK(testBoard.getPieceCode('n') == 2); //knight BOOST_CHECK(testBoard.getPieceCode('N') == 2); //knight BOOST_CHECK(testBoard.getPieceCode('b') == 3); //bishop BOOST_CHECK(testBoard.getPieceCode('B') == 3); //bishop BOOST_CHECK(testBoard.getPieceCode('q') == 4); //queen BOOST_CHECK(testBoard.getPieceCode('Q') == 4); //queen BOOST_CHECK(testBoard.getPieceCode('k') == 5); //king BOOST_CHECK(testBoard.getPieceCode('K') == 5); //king } int getLegalMoves(Board testBoard, int playerColor) { MoveList possibleMoves = MoveList(testBoard, ((playerColor == 1) ? 6 : 7), u64(0)); u64 castle = testBoard.getCastleOrEnpasent(); u64 lastHash = testBoard.getZorHash(); int enpasCol = testBoard.getEnpasentCol(); int halfMoveNumber = testBoard.halfMoveClock; int legalMoves = 0; while (true) { u64 theMove = possibleMoves.getNextMove(); if (theMove) { testBoard.makeMov(theMove); if (testBoard.inCheck(((playerColor == 1) ? 6 : 7)) == false) { legalMoves++; } testBoard.unMakeMov(theMove, castle, enpasCol, lastHash, halfMoveNumber); } else { break; } } return legalMoves; } BOOST_AUTO_TEST_CASE(MoveList_generateMoves) { cout << "Testing MoveList class" << endl; Board testBoard = Board("k5R1/7R/8/8/8/8/8/K7 b - - 0 1"); BOOST_CHECK(getLegalMoves(testBoard, -1) == 0); //black is check mated testBoard = Board("k7/8/8/8/8/8/8/K7 w - - 0 1"); BOOST_CHECK(getLegalMoves(testBoard, 1) == 3); //only piece is king in corner testBoard = Board("k7/8/8/8/4K3/8/8/8 w - - 0 1"); BOOST_CHECK(getLegalMoves(testBoard, 1) == 8); //only piece is king in center } BOOST_AUTO_TEST_CASE(search_RootAlphaBeta) { cout << "Testing search" << endl; Board testBoard = Board("k7/pppp4/8/8/8/8/8/K4R2 w - - 0 1"); testBoard.setEvaluation(Evaluation::evaluateBoard(testBoard)); testBoard.stageOfGame = Evaluation::stageOfGame(testBoard); testBoard.setZorHash(TranspositionTables::getBoardHash(testBoard, 6)); vector<string> searchMoves; BOOST_CHECK(Search::RootAlphaBeta(testBoard, 1, 4, searchMoves).first == "f1f8"); //it should find the checkmate for white } //Perft is good for verifying the correctness of the move generation, generate all the leaf nodes at a given depth from a known position. //This also shows how fast the move generation works in relation to other engines (slow, magic bitboards would speed up move generation) u64 Perft(int depth, Board& gameBoard, int playerColor) { if (depth == 0) { if (gameBoard.inCheck(((playerColor == 1) ? 7 : 6)) == true) { return 0; } return 1; } u64 nodes = 0; u64 castle = gameBoard.getCastleOrEnpasent(); u64 lastHash = gameBoard.getZorHash(); int enpasCol = gameBoard.getEnpasentCol(); int halfMoveNumber = gameBoard.halfMoveClock; MoveList possibleMoves(gameBoard, ((playerColor == 1) ? 6 : 7), true); if (possibleMoves.kingTake) { return 0; } int movNumber = possibleMoves.getMoveNumber(); for (int i = 0; i < movNumber; i++) { u64 theMove = possibleMoves.getMovN(i); gameBoard.makeMov(theMove); //if (gameBoard.inCheck(((playerColor == 1) ? 6 : 7)) == false) { nodes += Perft(depth - 1, gameBoard, playerColor*-1); //} gameBoard.unMakeMov(theMove, castle, enpasCol, lastHash, halfMoveNumber); } return nodes; } void setUpForPerft(Board& testBoard) { testBoard.setEvaluation(Evaluation::evaluateBoard(testBoard)); testBoard.stageOfGame = Evaluation::stageOfGame(testBoard); testBoard.setZorHash(TranspositionTables::getBoardHash(testBoard, WHITE_CODE)); } BOOST_AUTO_TEST_CASE(perft_Test) { cout << "Testing move generation (perft), this is slow" << endl; Board testBoard = Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); //initial position setUpForPerft(testBoard); BOOST_CHECK(Perft(4, testBoard, 1) == 197281); //Known value from the chess programming wiki http://chessprogramming.wikispaces.com/Perft+Results setUpForPerft(testBoard); testBoard = Board("r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -"); setUpForPerft(testBoard); BOOST_CHECK(Perft(4, testBoard, 1) == 4085603); testBoard = Board("8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -"); setUpForPerft(testBoard); BOOST_CHECK(Perft(5, testBoard, 1) == 674624); testBoard = Board("r2q1rk1/pP1p2pp/Q4n2/bbp1p3/Np6/1B3NBn/pPPP1PPP/R3K2R b KQ - 0 1"); setUpForPerft(testBoard); BOOST_CHECK(Perft(4, testBoard, -1) == 422333); testBoard = Board("rnbqkb1r/pp1p1ppp/2p5/4P3/2B5/8/PPP1NnPP/RNBQK2R w KQkq - 0 6"); setUpForPerft(testBoard); BOOST_CHECK(Perft(3, testBoard, 1) == 53392); testBoard = Board("r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10"); setUpForPerft(testBoard); BOOST_CHECK(Perft(4, testBoard, 1) == 3894594); } <|endoftext|>
<commit_before>#include <iostream> #include "occa.hpp" int main(int argc, char **argv){ occa::printAvailableDevices(); int entries = 5; float *a = new float[entries]; float *b = new float[entries]; float *ab = new float[entries]; for(int i = 0; i < entries; ++i){ a[i] = i; b[i] = 1 - i; ab[i] = 0; } occa::device device; occa::kernel addVectors; occa::memory o_a, o_b, o_ab; //---[ Device setup with string flags ]------------------- device.setup("mode = Serial"); // device.setup("mode = OpenMP , schedule = compact, chunk = 10"); // device.setup("mode = OpenCL , platformID = 0, deviceID = 1"); // device.setup("mode = CUDA , deviceID = 0"); // device.setup("mode = Pthreads, threadCount = 4, schedule = compact, pinnedCores = [0, 0, 1, 1]"); // device.setup("mode = COI , deviceID = 0"); //======================================================== //---[ Device setup with Python-like arguments ]---------- // device.setup("OpenMP", // occa::schedule = "compact", // occa::chunk = 10); // // device.setup("OpenCL", // occa::platformID = 0, // occa::deviceID = 0); // // device.setup("CUDA", // occa::deviceID = 0); // // device.setup("Pthreads", // occa::threadCount = 4, // occa::schedule = "compact", // occa::pinnedCores = "[0, 0, 1, 1]"); // // device.setup("COI", // occa::deviceID = 0); //======================================================== o_a = device.malloc(entries*sizeof(float)); o_b = device.malloc(entries*sizeof(float)); o_ab = device.malloc(entries*sizeof(float)); // OKL: OCCA Kernel Language addVectors = device.buildKernelFromSource("[test]/addVectors.okl", "addVectors"); // OFL: OCCA Fortran Language // addVectors = device.buildKernelFromSource("addVectors.ofl", // "addVectors"); //---[ Don't need to set these up when using OKL/OFL ]---- // int dims = 1; // int itemsPerGroup(16); // int groups((entries + itemsPerGroup - 1)/itemsPerGroup); // addVectors.setWorkingDims(dims, itemsPerGroup, groups); //======================================================== o_a.copyFrom(a); o_b.copyFrom(b); addVectors(entries, o_a, o_b, o_ab); o_ab.copyTo(ab); for(int i = 0; i < 5; ++i) std::cout << i << ": " << ab[i] << '\n'; for(int i = 0; i < entries; ++i){ if(ab[i] != (a[i] + b[i])) throw 1; } delete [] a; delete [] b; delete [] ab; addVectors.free(); o_a.free(); o_b.free(); o_ab.free(); device.free(); return 0; } <commit_msg>[addVectors] Forgot to revert main.cpp<commit_after>#include <iostream> #include "occa.hpp" int main(int argc, char **argv){ occa::printAvailableDevices(); int entries = 5; float *a = new float[entries]; float *b = new float[entries]; float *ab = new float[entries]; for(int i = 0; i < entries; ++i){ a[i] = i; b[i] = 1 - i; ab[i] = 0; } occa::device device; occa::kernel addVectors; occa::memory o_a, o_b, o_ab; //---[ Device setup with string flags ]------------------- device.setup("mode = Serial"); // device.setup("mode = OpenMP , schedule = compact, chunk = 10"); // device.setup("mode = OpenCL , platformID = 0, deviceID = 1"); // device.setup("mode = CUDA , deviceID = 0"); // device.setup("mode = Pthreads, threadCount = 4, schedule = compact, pinnedCores = [0, 0, 1, 1]"); // device.setup("mode = COI , deviceID = 0"); //======================================================== //---[ Device setup with Python-like arguments ]---------- // device.setup("OpenMP", // occa::schedule = "compact", // occa::chunk = 10); // // device.setup("OpenCL", // occa::platformID = 0, // occa::deviceID = 0); // // device.setup("CUDA", // occa::deviceID = 0); // // device.setup("Pthreads", // occa::threadCount = 4, // occa::schedule = "compact", // occa::pinnedCores = "[0, 0, 1, 1]"); // // device.setup("COI", // occa::deviceID = 0); //======================================================== o_a = device.malloc(entries*sizeof(float)); o_b = device.malloc(entries*sizeof(float)); o_ab = device.malloc(entries*sizeof(float)); // OKL: OCCA Kernel Language addVectors = device.buildKernelFromSource("addVectors.okl", "addVectors"); // OFL: OCCA Fortran Language // addVectors = device.buildKernelFromSource("addVectors.ofl", // "addVectors"); //---[ Don't need to set these up when using OKL/OFL ]---- // int dims = 1; // int itemsPerGroup(16); // int groups((entries + itemsPerGroup - 1)/itemsPerGroup); // addVectors.setWorkingDims(dims, itemsPerGroup, groups); //======================================================== o_a.copyFrom(a); o_b.copyFrom(b); addVectors(entries, o_a, o_b, o_ab); o_ab.copyTo(ab); for(int i = 0; i < 5; ++i) std::cout << i << ": " << ab[i] << '\n'; for(int i = 0; i < entries; ++i){ if(ab[i] != (a[i] + b[i])) throw 1; } delete [] a; delete [] b; delete [] ab; addVectors.free(); o_a.free(); o_b.free(); o_ab.free(); device.free(); return 0; } <|endoftext|>
<commit_before>#include <mpi.h> #include <cmath> #include <ctime> #include <fstream> #include <iostream> #include <algorithm> #include <petscksp.h> #include <petscis.h> #include <petsclog.h> #include "par.h" #include "mpi_range.h" #include "get_cluster.h" #include "get_buffer.h" #include "get_trunc.h" #include "get_vorticity.h" #include "matmult.h" #include "vorticity_evaluation.cxx" #include "rbf_interpolation.cxx" int main(int argc,char **argv) { int i,its,nsigma_box,sigma_buffer,sigma_trunc,nx,ny,nz,ni,nj,ista,iend,nlocal; double sigma,overlap,h,xmin,xmax,ymin,ymax,zmin,zmax,xd,yd,zd,gd,ed,wd,t,err,errd; clock_t tic,toc; tic = std::clock(); std::ofstream fid0,fid1; PARAMETER parameter; MPI2 mpi; PetscErrorCode ierr; Vec x,y,z,g,e,w; PetscInitialize(&argc,&argv,PETSC_NULL,PETSC_NULL); MPI_Comm_size(PETSC_COMM_WORLD,&mpi.nprocs); MPI_Comm_rank(PETSC_COMM_WORLD,&mpi.myrank); /* physical parameters */ parameter.vis = 0.1; parameter.t = 1; /* particle parameters */ sigma = 0.1; overlap = atof(argv[1]); h = overlap*sigma; xmin = -1; xmax = 1; ymin = -1; ymax = 1; zmin = -1; zmax = 1; /* cluster parameters */ nsigma_box = atoi(argv[2]); sigma_buffer = (int)nsigma_box*atof(argv[3]); if (overlap < 0.8+epsf) { sigma_trunc = nsigma_box+6; } else { sigma_trunc = nsigma_box+4; } /* calculate problem size */ nx = (int)floor((xmax-xmin+epsf)/h)+1; ny = (int)floor((ymax-ymin+epsf)/h)+1; nz = (int)floor((zmax-zmin+epsf)/h)+1; ni = nx*ny*nz; if(mpi.myrank==0) { printf("||---------------------------------------\n"); printf("|| number of particles : %d \n",ni); printf("|| std of Gaussian (sigma) : %f \n",sigma); printf("|| overlap ratio (h/sigma) : %f \n",overlap); printf("|| non-overlapping subdomain : %d sigma\n",nsigma_box); printf("|| overlapping subdomain : %d sigma\n",(int)fmin(sigma_buffer,floor(2/sigma))); printf("|| entire domain : %d sigma\n",(int)floor(2/sigma)); printf("||---------------------------------------\n"); } nj = ni; /* generate particles */ ierr = VecCreate(PETSC_COMM_WORLD,&x);CHKERRQ(ierr); ierr = VecSetSizes(x,PETSC_DECIDE,ni);CHKERRQ(ierr); ierr = VecSetFromOptions(x);CHKERRQ(ierr); ierr = VecDuplicate(x,&y);CHKERRQ(ierr); ierr = VecDuplicate(x,&z);CHKERRQ(ierr); ierr = VecDuplicate(x,&g);CHKERRQ(ierr); ierr = VecDuplicate(x,&e);CHKERRQ(ierr); ierr = VecDuplicate(x,&w);CHKERRQ(ierr); ierr = VecGetOwnershipRange(x,&ista,&iend);CHKERRQ(ierr); nlocal = iend-ista; for(i=ista; i<iend; i++) { xd = xmin+floor((i%(nx*ny))/ny)*h; yd = ymin+(i%ny)*h; zd = zmin+floor(i/(nx*ny))*h; // ed = (float)rand()/RAND_MAX; // xd = xd*nx/(nx+1)+ed*h/2; // ed = (float)rand()/RAND_MAX; // yd = yd*ny/(ny+1)+ed*h/2; ed = exp(-(xd*xd+yd*yd+zd*zd)/(4*parameter.vis*parameter.t))/(M_PI*4*parameter.vis*parameter.t); wd = ed; gd = ed*h*h; ierr = VecSetValues(x,1,&i,&xd,INSERT_VALUES);CHKERRQ(ierr); ierr = VecSetValues(y,1,&i,&yd,INSERT_VALUES);CHKERRQ(ierr); ierr = VecSetValues(z,1,&i,&zd,INSERT_VALUES);CHKERRQ(ierr); ierr = VecSetValues(g,1,&i,&gd,INSERT_VALUES);CHKERRQ(ierr); ierr = VecSetValues(e,1,&i,&ed,INSERT_VALUES);CHKERRQ(ierr); ierr = VecSetValues(w,1,&i,&wd,INSERT_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(x);CHKERRQ(ierr); ierr = VecAssemblyEnd(x);CHKERRQ(ierr); ierr = VecAssemblyBegin(y);CHKERRQ(ierr); ierr = VecAssemblyEnd(y);CHKERRQ(ierr); ierr = VecAssemblyBegin(z);CHKERRQ(ierr); ierr = VecAssemblyEnd(z);CHKERRQ(ierr); ierr = VecAssemblyBegin(g);CHKERRQ(ierr); ierr = VecAssemblyEnd(g);CHKERRQ(ierr); ierr = VecAssemblyBegin(e);CHKERRQ(ierr); ierr = VecAssemblyEnd(e);CHKERRQ(ierr); ierr = VecAssemblyBegin(w);CHKERRQ(ierr); ierr = VecAssemblyEnd(w);CHKERRQ(ierr); vorticity_evaluation(x,y,z,w,x,y,z,g,sigma,nsigma_box,sigma_buffer,sigma_trunc,&its); rbf_interpolation(x,y,z,g,e,w,sigma,nsigma_box,sigma_buffer,sigma_trunc,&its); vorticity_evaluation(x,y,z,w,x,y,z,g,sigma,nsigma_box,sigma_buffer,sigma_trunc,&its); /* calculate the L2 norm error */ ierr = VecAXPY(w,-1,e);CHKERRQ(ierr); ierr = VecNorm(e,NORM_2,&err);CHKERRQ(ierr); ierr = VecNorm(w,NORM_2,&errd);CHKERRQ(ierr); err = log(errd/err)/log(10.0); toc = std::clock(); t = (double)(toc-tic)/ (double)CLOCKS_PER_SEC; if (mpi.myrank == 0) { char file[13]; if (1.0-overlap < epsf) { // sprintf(file,"%s-%s-%s.dat",argv[1],argv[2],argv[3]); } else { // sprintf(file,"0%s-%s-%s.dat",argv[1],argv[2],argv[3]); } sprintf(file,"%d.dat",mpi.nprocs); fid0.open(file); fid0 << t << std::endl << its; fid0.close(); printf("error : %g\n",err); printf("time : %g\n",t); } PetscFinalize(); } <commit_msg>minor bugfix in 3D rbf test driver<commit_after>#include <mpi.h> #include <cmath> #include <ctime> #include <fstream> #include <iostream> #include <algorithm> #include <petscksp.h> #include <petscis.h> #include <petsclog.h> #include "par.h" #include "mpi_range.h" #include "get_cluster.h" #include "get_buffer.h" #include "get_trunc.h" #include "get_vorticity.h" #include "matmult.h" #include "vorticity_evaluation.cxx" #include "rbf_interpolation.cxx" int main(int argc,char **argv) { int i,its,nsigma_box,sigma_buffer,sigma_trunc,nx,ny,nz,ni,nj,ista,iend,nlocal; double sigma,overlap,h,xmin,xmax,ymin,ymax,zmin,zmax,xd,yd,zd,gd,ed,wd,t,err,errd; clock_t tic,toc; tic = std::clock(); std::ofstream fid0,fid1; PARAMETER parameter; MPI2 mpi; PetscErrorCode ierr; Vec x,y,z,g,e,w; PetscInitialize(&argc,&argv,PETSC_NULL,PETSC_NULL); MPI_Comm_size(PETSC_COMM_WORLD,&mpi.nprocs); MPI_Comm_rank(PETSC_COMM_WORLD,&mpi.myrank); /* physical parameters */ parameter.vis = 0.1; parameter.t = 1; /* particle parameters */ sigma = 0.1; overlap = atof(argv[1]); h = overlap*sigma; xmin = -1; xmax = 1; ymin = -1; ymax = 1; zmin = -1; zmax = 1; /* cluster parameters */ nsigma_box = atoi(argv[2]); sigma_buffer = (int)nsigma_box*atof(argv[3]); if (overlap < 0.8+epsf) { sigma_trunc = nsigma_box+6; } else { sigma_trunc = nsigma_box+4; } /* calculate problem size */ nx = (int)floor((xmax-xmin+epsf)/h)+1; ny = (int)floor((ymax-ymin+epsf)/h)+1; nz = (int)floor((zmax-zmin+epsf)/h)+1; ni = nx*ny*nz; if(mpi.myrank==0) { printf("||---------------------------------------\n"); printf("|| number of particles : %d \n",ni); printf("|| std of Gaussian (sigma) : %f \n",sigma); printf("|| overlap ratio (h/sigma) : %f \n",overlap); printf("|| non-overlapping subdomain : %d sigma\n",nsigma_box); printf("|| overlapping subdomain : %d sigma\n",(int)fmin(sigma_buffer,floor(2/sigma))); printf("|| entire domain : %d sigma\n",(int)floor(2/sigma)); printf("||---------------------------------------\n"); } nj = ni; /* generate particles */ ierr = VecCreate(PETSC_COMM_WORLD,&x);CHKERRQ(ierr); ierr = VecSetSizes(x,PETSC_DECIDE,ni);CHKERRQ(ierr); ierr = VecSetFromOptions(x);CHKERRQ(ierr); ierr = VecDuplicate(x,&y);CHKERRQ(ierr); ierr = VecDuplicate(x,&z);CHKERRQ(ierr); ierr = VecDuplicate(x,&g);CHKERRQ(ierr); ierr = VecDuplicate(x,&e);CHKERRQ(ierr); ierr = VecDuplicate(x,&w);CHKERRQ(ierr); ierr = VecGetOwnershipRange(x,&ista,&iend);CHKERRQ(ierr); nlocal = iend-ista; for(i=ista; i<iend; i++) { xd = xmin+floor((i%(nx*ny))/ny)*h; yd = ymin+(i%ny)*h; zd = zmin+floor(i/(nx*ny))*h; // ed = (float)rand()/RAND_MAX; // xd = xd*nx/(nx+1)+ed*h/2; // ed = (float)rand()/RAND_MAX; // yd = yd*ny/(ny+1)+ed*h/2; ed = exp(-(xd*xd+yd*yd+zd*zd)/(4*parameter.vis*parameter.t))/(M_PI*4*parameter.vis*parameter.t); wd = ed; gd = ed*h*h*h; ierr = VecSetValues(x,1,&i,&xd,INSERT_VALUES);CHKERRQ(ierr); ierr = VecSetValues(y,1,&i,&yd,INSERT_VALUES);CHKERRQ(ierr); ierr = VecSetValues(z,1,&i,&zd,INSERT_VALUES);CHKERRQ(ierr); ierr = VecSetValues(g,1,&i,&gd,INSERT_VALUES);CHKERRQ(ierr); ierr = VecSetValues(e,1,&i,&ed,INSERT_VALUES);CHKERRQ(ierr); ierr = VecSetValues(w,1,&i,&wd,INSERT_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(x);CHKERRQ(ierr); ierr = VecAssemblyEnd(x);CHKERRQ(ierr); ierr = VecAssemblyBegin(y);CHKERRQ(ierr); ierr = VecAssemblyEnd(y);CHKERRQ(ierr); ierr = VecAssemblyBegin(z);CHKERRQ(ierr); ierr = VecAssemblyEnd(z);CHKERRQ(ierr); ierr = VecAssemblyBegin(g);CHKERRQ(ierr); ierr = VecAssemblyEnd(g);CHKERRQ(ierr); ierr = VecAssemblyBegin(e);CHKERRQ(ierr); ierr = VecAssemblyEnd(e);CHKERRQ(ierr); ierr = VecAssemblyBegin(w);CHKERRQ(ierr); ierr = VecAssemblyEnd(w);CHKERRQ(ierr); vorticity_evaluation(x,y,z,w,x,y,z,g,sigma,nsigma_box,sigma_buffer,sigma_trunc,&its); rbf_interpolation(x,y,z,g,e,w,sigma,nsigma_box,sigma_buffer,sigma_trunc,&its); vorticity_evaluation(x,y,z,w,x,y,z,g,sigma,nsigma_box,sigma_buffer,sigma_trunc,&its); /* calculate the L2 norm error */ ierr = VecAXPY(w,-1,e);CHKERRQ(ierr); ierr = VecNorm(e,NORM_2,&err);CHKERRQ(ierr); ierr = VecNorm(w,NORM_2,&errd);CHKERRQ(ierr); err = log(errd/err)/log(10.0); toc = std::clock(); t = (double)(toc-tic)/ (double)CLOCKS_PER_SEC; if (mpi.myrank == 0) { char file[13]; if (1.0-overlap < epsf) { // sprintf(file,"%s-%s-%s.dat",argv[1],argv[2],argv[3]); } else { // sprintf(file,"0%s-%s-%s.dat",argv[1],argv[2],argv[3]); } sprintf(file,"%d.dat",mpi.nprocs); fid0.open(file); fid0 << t << std::endl << its; fid0.close(); printf("error : %g\n",err); printf("time : %g\n",t); } PetscFinalize(); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_fbc_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_fbc_utils.H /// @brief Fabric library functions/constants (FAPI2) /// /// @author Joe McGill <[email protected]> /// @author Christy Graves <[email protected]> /// // // *HWP HWP Owner: Joe McGill <[email protected]> // *HWP FW Owner: Thi Tran <[email protected]> // *HWP Team: Nest // *HWP Level: 3 // *HWP Consumed by: SBE,HB,FSP // #ifndef _P9_FBC_UTILS_H_ #define _P9_FBC_UTILS_H_ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <fapi2.H> //------------------------------------------------------------------------------ // Structure definitions //------------------------------------------------------------------------------ enum p9_fbc_utils_addr_mode_t { EFF_FBC_GRP_CHIP_IDS, // effective FBC group/chip ID attributes EFF_FBC_GRP_ID_ONLY, // effective FBC group ID attribute (chip ID=0) ABS_FBC_GRP_CHIP_IDS // absolute FBC group/chip ID attributes }; //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ // address range definitions const uint64_t P9_FBC_UTILS_FBC_MAX_ADDRESS = ((1ULL << 56) - 1ULL); const uint64_t P9_FBC_UTILS_CACHELINE_MASK = 0x7FULL; const uint64_t P9_FBC_UTILS_LAST_ADDR_IN_CACHELINE = 0x78ULL; // cacheline size = 128B const uint64_t FABRIC_CACHELINE_SIZE = 0x80; //------------------------------------------------------------------------------ // Function prototypes //------------------------------------------------------------------------------ /// /// @brief Read FBC/ADU registers to determine state of fabric init and stop /// control signals /// /// @param[in] i_target Reference to processor chip target /// @param[out] o_is_initialized State of fabric init signal /// @param[out] o_is_running State of fabric pervasive stop control /// @return fapi::ReturnCode, FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p9_fbc_utils_get_fbc_state( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, bool& o_is_initialized, bool& o_is_running); /// /// @brief Use ADU pMisc Mode register to clear fabric stop signal, overriding /// a stop condition caused by a checkstop /// /// @param[in] i_target Reference to processor chip target /// @return fapi::ReturnCode, FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p9_fbc_utils_override_fbc_stop( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); /// /// @brief Return base address origin (non-mirrored/mirrored/MMIO) for this chip /// /// @param[in] i_target Reference to processor chip target /// @param[in] i_addr_mode Specifies mode for chip base/origin address calculations /// @param[out] o_base_address_nm0 Non-mirrored base address (range 0) for this chip /// @param[out] o_base_address_nm1 Non-mirrored base address (range 1) for this chip /// @param[out] o_base_address_m Mirrored base address for this chip /// @param[out] o_base_address_mmio MMIO base address for this chip /// @return fapi::ReturnCode, FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p9_fbc_utils_get_chip_base_address( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p9_fbc_utils_addr_mode_t i_addr_mode, uint64_t& o_base_address_nm0, uint64_t& o_base_address_nm1, uint64_t& o_base_address_m, uint64_t& o_base_address_mmio); #endif // _P9_FBC_UTILS_H_ <commit_msg>update owner comments in ADU, PBA, TOD HWPs<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_fbc_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_fbc_utils.H /// @brief Fabric library functions/constants (FAPI2) /// /// @author Joe McGill <[email protected]> /// // // *HWP HWP Owner: Joe McGill <[email protected]> // *HWP FW Owner: Thi Tran <[email protected]> // *HWP Team: Nest // *HWP Level: 3 // *HWP Consumed by: SBE,HB,FSP // #ifndef _P9_FBC_UTILS_H_ #define _P9_FBC_UTILS_H_ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <fapi2.H> //------------------------------------------------------------------------------ // Structure definitions //------------------------------------------------------------------------------ enum p9_fbc_utils_addr_mode_t { EFF_FBC_GRP_CHIP_IDS, // effective FBC group/chip ID attributes EFF_FBC_GRP_ID_ONLY, // effective FBC group ID attribute (chip ID=0) ABS_FBC_GRP_CHIP_IDS // absolute FBC group/chip ID attributes }; //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ // address range definitions const uint64_t P9_FBC_UTILS_FBC_MAX_ADDRESS = ((1ULL << 56) - 1ULL); const uint64_t P9_FBC_UTILS_CACHELINE_MASK = 0x7FULL; const uint64_t P9_FBC_UTILS_LAST_ADDR_IN_CACHELINE = 0x78ULL; // cacheline size = 128B const uint64_t FABRIC_CACHELINE_SIZE = 0x80; //------------------------------------------------------------------------------ // Function prototypes //------------------------------------------------------------------------------ /// /// @brief Read FBC/ADU registers to determine state of fabric init and stop /// control signals /// /// @param[in] i_target Reference to processor chip target /// @param[out] o_is_initialized State of fabric init signal /// @param[out] o_is_running State of fabric pervasive stop control /// @return fapi::ReturnCode, FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p9_fbc_utils_get_fbc_state( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, bool& o_is_initialized, bool& o_is_running); /// /// @brief Use ADU pMisc Mode register to clear fabric stop signal, overriding /// a stop condition caused by a checkstop /// /// @param[in] i_target Reference to processor chip target /// @return fapi::ReturnCode, FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p9_fbc_utils_override_fbc_stop( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); /// /// @brief Return base address origin (non-mirrored/mirrored/MMIO) for this chip /// /// @param[in] i_target Reference to processor chip target /// @param[in] i_addr_mode Specifies mode for chip base/origin address calculations /// @param[out] o_base_address_nm0 Non-mirrored base address (range 0) for this chip /// @param[out] o_base_address_nm1 Non-mirrored base address (range 1) for this chip /// @param[out] o_base_address_m Mirrored base address for this chip /// @param[out] o_base_address_mmio MMIO base address for this chip /// @return fapi::ReturnCode, FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p9_fbc_utils_get_chip_base_address( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p9_fbc_utils_addr_mode_t i_addr_mode, uint64_t& o_base_address_nm0, uint64_t& o_base_address_nm1, uint64_t& o_base_address_m, uint64_t& o_base_address_mmio); #endif // _P9_FBC_UTILS_H_ <|endoftext|>
<commit_before>#include <iostream> #include "ros/ros.h" #include "sensor_msgs/PointCloud2.h" #include "sensor_msgs/NavSatFix.h" #include "sensor_msgs/Imu.h" #include "nav_msgs/Odometry.h" #include "laser_transform_core.h" using std::string; int main (int argc, char **argv) { ros::init(argc, argv, "laser_transform"); ros::NodeHandle n; // Declare variables thar can be modified by launch file or command line. int rate; int imu_convergence_speed; bool imu_msgs; bool gps_msgs; string pcl_in_topic; string pcl_out_topic; string imu_topic; string gps_topic; //string odo_topic; // Create a new LaserTransformer object. LaserTransform *node_lt = new LaserTransform(); node_lt->init(); // while using different parameters. ros::NodeHandle private_node_handle_("~"); private_node_handle_.param("rate", rate, int(10)); private_node_handle_.param("imu_msgs", imu_msgs, bool(true)); private_node_handle_.param("gps_msgs", gps_msgs, bool(false)); private_node_handle_.param("pcl_in_topic", pcl_in_topic, string("/cloud")); private_node_handle_.param("pcl_out_topic", pcl_out_topic, string("/cloud_world")); private_node_handle_.param("imu_topic", imu_topic, string("/imu/data")); private_node_handle_.param("gps_topic", gps_topic, string("/gps/fix")); private_node_handle_.param("imu_convergence_speed", imu_convergence_speed, int(20)); // Create a subscriber ros::Subscriber sub_message = n.subscribe(pcl_in_topic.c_str(), 1000, &LaserTransform::pclCallback, node_lt); // Create odometry subscriber ros::Subscriber sub_odometry = n.subscribe("/odometry/filtered", 50, &LaserTransform::odometryCallback, node_lt); // Create a publisher and name the topic ros::Publisher pub_message = n.advertise<sensor_msgs::PointCloud2>(pcl_out_topic.c_str(), 50); // Create a publisher for IMU msgs ros::Publisher imu_pub = n.advertise<sensor_msgs::Imu>(imu_topic.c_str(), 50); // Create a publisher for GPS msgs ros::Publisher gps_pub = n.advertise<sensor_msgs::NavSatFix>(gps_topic.c_str(), 50); ros::Rate r(rate); while (n.ok()) { node_lt->publishPclMessage(&pub_message); if (imu_msgs) node_lt->publishImuMessage(&imu_pub); if (gps_msgs) node_lt->publishNavSatFixMessage(&gps_pub); ros::spinOnce(); r.sleep(); } return 0; // end main } <commit_msg>add magnetic field publisher<commit_after>#include <iostream> #include "ros/ros.h" #include "sensor_msgs/PointCloud2.h" #include "sensor_msgs/NavSatFix.h" #include "sensor_msgs/MagneticField.h" #include "sensor_msgs/Imu.h" #include "nav_msgs/Odometry.h" #include "laser_transform_core.h" using std::string; int main (int argc, char **argv) { ros::init(argc, argv, "laser_transform"); ros::NodeHandle n; // Declare variables thar can be modified by launch file or command line. int rate; int imu_convergence_speed; bool imu_msgs; bool mf_msgs; bool gps_msgs; string pcl_in_topic; string pcl_out_topic; string mf_topic; string imu_topic; string gps_topic; //string odo_topic; // Create a new LaserTransformer object. LaserTransform *node_lt = new LaserTransform(); node_lt->init(); // while using different parameters. ros::NodeHandle private_node_handle_("~"); private_node_handle_.param("rate", rate, int(10)); private_node_handle_.param("mf_msgs", mf_msgs, bool(true)); private_node_handle_.param("imu_msgs", imu_msgs, bool(true)); private_node_handle_.param("gps_msgs", gps_msgs, bool(false)); private_node_handle_.param("pcl_in_topic", pcl_in_topic, string("/cloud")); private_node_handle_.param("pcl_out_topic", pcl_out_topic, string("/cloud_world")); private_node_handle_.param("mf_topic", mf_topic, string("magnetic/data")); private_node_handle_.param("imu_topic", imu_topic, string("/imu/data")); private_node_handle_.param("gps_topic", gps_topic, string("/gps/fix")); private_node_handle_.param("imu_convergence_speed", imu_convergence_speed, int(20)); // Create a subscriber for laser scanner plc data ros::Subscriber sub_message = n.subscribe(pcl_in_topic.c_str(), 1000, &LaserTransform::pclCallback, node_lt); // Create a publisher for transformed plc msgs ros::Publisher pub_message = n.advertise<sensor_msgs::PointCloud2>(pcl_out_topic.c_str(), 50); // Create a publisher for magnetic field msgs ros::Publisher mf_pub = n.advertise<sensor_msgs::MagneticField>(mf_topic.c_str(), 50); // Create a publisher for IMU msgs ros::Publisher imu_pub = n.advertise<sensor_msgs::Imu>(imu_topic.c_str(), 50); // Create a publisher for GPS msgs ros::Publisher gps_pub = n.advertise<sensor_msgs::NavSatFix>(gps_topic.c_str(), 50); ros::Rate r(rate); while (n.ok()) { node_lt->publishPclMessage(&pub_message); if (imu_msgs) node_lt->publishImuMessage(&imu_pub); if (gps_msgs) node_lt->publishNavSatFixMessage(&gps_pub); if (mf_msgs) node_lt->publishMagneticFieldMessage(&mf_pub); ros::spinOnce(); r.sleep(); } return 0; // end main } <|endoftext|>
<commit_before>#include "ui/ui_root.h" #include "ui/ui_widget.h" #include "api/audio_api.h" #include "ui/ui_painter.h" using namespace Halley; UIRoot* UIRoot::getRoot() { return this; } UIRoot::UIRoot(AudioAPI* audio) : dummyInput(std::make_shared<InputButtonBase>(4)) , audio(audio) { } void UIRoot::update(Time t, UIInputType activeInputType, spInputDevice mouse, spInputDevice manual, Vector2f uiOffset) { // Update input updateTabbing(manual); updateMouse(mouse, uiOffset); // Update children { bool allowInput = true; auto& cs = getChildren(); for (int i = int(cs.size()); --i >= 0; ) { cs[i]->doUpdate(t, activeInputType, allowInput ? *manual : *dummyInput); if (cs[i]->isMouseBlocker()) { allowInput = false; } } } // Layout all widgets runLayout(); // Remove dead removeDeadChildren(); bool added = addNewChildren(activeInputType); // Update new windows if (topChildChanged) { topChildChanged = false; if (activeInputType == UIInputType::Mouse) { lastMousePos = Vector2f(-100, -100); } else { //mouseOverNext(); } } // Update again, to reflect what happened >_> runLayout(); for (auto& c: getChildren()) { c->doUpdate(0, activeInputType, *dummyInput); } } void UIRoot::updateMouse(spInputDevice mouse, Vector2f uiOffset) { // Check where we should be mouse overing. // If the mouse hasn't moved, keep the last one. std::shared_ptr<UIWidget> underMouse; Vector2f mousePos = mouse->getPosition() + uiOffset; if ((mousePos - lastMousePos).squaredLength() > 0.01f) { // Go through all root-level widgets and find the actual widget under the mouse underMouse = getWidgetUnderMouse(mousePos); lastMousePos = mousePos; } else { underMouse = currentMouseOver.lock(); } // Click if (mouse->isButtonPressed(0)) { mouseHeld = true; setFocus(underMouse); if (underMouse) { underMouse->pressMouse(mousePos, 0); } } // Release click auto focus = currentFocus.lock(); if (mouse->isButtonReleased(0)) { mouseHeld = false; if (focus) { focus->releaseMouse(mousePos, 0); } } // Mouse wheel int wheelDelta = mouse->getWheelMove(); if (wheelDelta != 0 && underMouse) { underMouse->sendEvent(UIEvent(UIEventType::MouseWheel, "mouse", wheelDelta)); } // If the mouse is held, but it's over a different component from the focused one, don't mouse over anything auto activeMouseOver = underMouse; if (mouseHeld && focus && focus != underMouse) { activeMouseOver.reset(); } updateMouseOver(activeMouseOver); } void UIRoot::updateTabbing(spInputDevice manual) { int x = manual->getAxisRepeat(0); int y = manual->getAxisRepeat(1); /* if (x > 0 || y > 0) { mouseOverNext(true); } else if (x < 0 || y < 0) { mouseOverNext(false); } */ } void UIRoot::mouseOverNext(bool forward) { auto widgets = collectWidgets(); if (widgets.empty()) { return; } size_t nextIdx = 0; auto current = currentMouseOver.lock(); if (current) { auto i = std::find(widgets.begin(), widgets.end(), current); if (i != widgets.end()) { nextIdx = ((i - widgets.begin()) + widgets.size() + (forward ? 1 : -1)) % widgets.size(); } } updateMouseOver(widgets[nextIdx]); } void UIRoot::runLayout() { for (auto& c: getChildren()) { c->layout(); } } void UIRoot::setFocus(std::shared_ptr<UIWidget> focus) { auto curFocus = currentFocus.lock(); if (curFocus != focus) { if (curFocus) { curFocus->setFocused(false, focus.get()); } currentFocus = focus; if (focus) { focus->setFocused(true, focus.get()); } } } void UIRoot::updateMouseOver(const std::shared_ptr<UIWidget>& underMouse) { auto curMouseOver = currentMouseOver.lock(); if (curMouseOver != underMouse) { if (curMouseOver) { curMouseOver->setMouseOver(false); } if (underMouse) { underMouse->setMouseOver(true); } currentMouseOver = underMouse; } } std::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouse(Vector2f mousePos) { auto& cs = getChildren(); for (int i = int(cs.size()); --i >= 0; ) { auto widget = getWidgetUnderMouse(cs[i], mousePos); if (widget) { return widget; } else { if (cs[i]->isMouseBlocker()) { return {}; } } } return {}; } std::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouse(const std::shared_ptr<UIWidget>& start, Vector2f mousePos) { // Depth first for (auto& c: start->getChildren()) { auto result = getWidgetUnderMouse(c, mousePos); if (result) { return result; } } auto rect = start->getMouseRect(); if (start->canInteractWithMouse() && rect.contains(mousePos)) { return start; } else { return {}; } } std::vector<std::shared_ptr<UIWidget>> UIRoot::collectWidgets() { std::vector<std::shared_ptr<UIWidget>> output; if (getChildren().empty()) { return {}; } collectWidgets(getChildren().back(), output); return output; } void UIRoot::collectWidgets(const std::shared_ptr<UIWidget>& start, std::vector<std::shared_ptr<UIWidget>>& output) { for (auto& c: start->getChildren()) { collectWidgets(c, output); } if (start->canInteractWithMouse()) { output.push_back(start); } } void UIRoot::draw(SpritePainter& painter, int mask, int layer) { UIPainter p(painter, mask, layer); for (auto& c: getChildren()) { c->doDraw(p); } } void UIRoot::playSound(const std::shared_ptr<const AudioClip>& clip) { if (audio && clip) { audio->playUI(clip); } } void UIRoot::sendEvent(UIEvent&&) const { // Unhandled event } bool UIRoot::hasModalUI() const { for (auto& c: getChildren()) { if (c->isModal()) { return true; } } return false; } bool UIRoot::isMouseOverUI() const { return static_cast<bool>(currentMouseOver.lock()); } UIWidget* UIRoot::getCurrentFocus() const { return currentFocus.lock().get(); } <commit_msg>"Fix" mouse highlighting.<commit_after>#include "ui/ui_root.h" #include "ui/ui_widget.h" #include "api/audio_api.h" #include "ui/ui_painter.h" using namespace Halley; UIRoot* UIRoot::getRoot() { return this; } UIRoot::UIRoot(AudioAPI* audio) : dummyInput(std::make_shared<InputButtonBase>(4)) , audio(audio) { } void UIRoot::update(Time t, UIInputType activeInputType, spInputDevice mouse, spInputDevice manual, Vector2f uiOffset) { // Update input updateTabbing(manual); updateMouse(mouse, uiOffset); // Update children { bool allowInput = true; auto& cs = getChildren(); for (int i = int(cs.size()); --i >= 0; ) { cs[i]->doUpdate(t, activeInputType, allowInput ? *manual : *dummyInput); if (cs[i]->isMouseBlocker()) { allowInput = false; } } } // Layout all widgets runLayout(); // Remove dead removeDeadChildren(); bool added = addNewChildren(activeInputType); // Update new windows if (topChildChanged) { topChildChanged = false; if (activeInputType == UIInputType::Mouse) { lastMousePos = Vector2f(-100, -100); } else { //mouseOverNext(); } } // Update again, to reflect what happened >_> runLayout(); for (auto& c: getChildren()) { c->doUpdate(0, activeInputType, *dummyInput); } } void UIRoot::updateMouse(spInputDevice mouse, Vector2f uiOffset) { // Check where we should be mouse overing. // If the mouse hasn't moved, keep the last one. std::shared_ptr<UIWidget> underMouse; Vector2f mousePos = mouse->getPosition() + uiOffset; if (true || (mousePos - lastMousePos).squaredLength() > 0.01f) { // Go through all root-level widgets and find the actual widget under the mouse underMouse = getWidgetUnderMouse(mousePos); lastMousePos = mousePos; } else { underMouse = currentMouseOver.lock(); } // Click if (mouse->isButtonPressed(0)) { mouseHeld = true; setFocus(underMouse); if (underMouse) { underMouse->pressMouse(mousePos, 0); } } // Release click auto focus = currentFocus.lock(); if (mouse->isButtonReleased(0)) { mouseHeld = false; if (focus) { focus->releaseMouse(mousePos, 0); } } // Mouse wheel int wheelDelta = mouse->getWheelMove(); if (wheelDelta != 0 && underMouse) { underMouse->sendEvent(UIEvent(UIEventType::MouseWheel, "mouse", wheelDelta)); } // If the mouse is held, but it's over a different component from the focused one, don't mouse over anything auto activeMouseOver = underMouse; if (mouseHeld && focus && focus != underMouse) { activeMouseOver.reset(); } updateMouseOver(activeMouseOver); } void UIRoot::updateTabbing(spInputDevice manual) { int x = manual->getAxisRepeat(0); int y = manual->getAxisRepeat(1); /* if (x > 0 || y > 0) { mouseOverNext(true); } else if (x < 0 || y < 0) { mouseOverNext(false); } */ } void UIRoot::mouseOverNext(bool forward) { auto widgets = collectWidgets(); if (widgets.empty()) { return; } size_t nextIdx = 0; auto current = currentMouseOver.lock(); if (current) { auto i = std::find(widgets.begin(), widgets.end(), current); if (i != widgets.end()) { nextIdx = ((i - widgets.begin()) + widgets.size() + (forward ? 1 : -1)) % widgets.size(); } } updateMouseOver(widgets[nextIdx]); } void UIRoot::runLayout() { for (auto& c: getChildren()) { c->layout(); } } void UIRoot::setFocus(std::shared_ptr<UIWidget> focus) { auto curFocus = currentFocus.lock(); if (curFocus != focus) { if (curFocus) { curFocus->setFocused(false, focus.get()); } currentFocus = focus; if (focus) { focus->setFocused(true, focus.get()); } } } void UIRoot::updateMouseOver(const std::shared_ptr<UIWidget>& underMouse) { auto curMouseOver = currentMouseOver.lock(); if (curMouseOver != underMouse) { if (curMouseOver) { curMouseOver->setMouseOver(false); } if (underMouse) { underMouse->setMouseOver(true); } currentMouseOver = underMouse; } } std::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouse(Vector2f mousePos) { auto& cs = getChildren(); for (int i = int(cs.size()); --i >= 0; ) { auto widget = getWidgetUnderMouse(cs[i], mousePos); if (widget) { return widget; } else { if (cs[i]->isMouseBlocker()) { return {}; } } } return {}; } std::shared_ptr<UIWidget> UIRoot::getWidgetUnderMouse(const std::shared_ptr<UIWidget>& start, Vector2f mousePos) { // Depth first for (auto& c: start->getChildren()) { auto result = getWidgetUnderMouse(c, mousePos); if (result) { return result; } } auto rect = start->getMouseRect(); if (start->canInteractWithMouse() && rect.contains(mousePos)) { return start; } else { return {}; } } std::vector<std::shared_ptr<UIWidget>> UIRoot::collectWidgets() { std::vector<std::shared_ptr<UIWidget>> output; if (getChildren().empty()) { return {}; } collectWidgets(getChildren().back(), output); return output; } void UIRoot::collectWidgets(const std::shared_ptr<UIWidget>& start, std::vector<std::shared_ptr<UIWidget>>& output) { for (auto& c: start->getChildren()) { collectWidgets(c, output); } if (start->canInteractWithMouse()) { output.push_back(start); } } void UIRoot::draw(SpritePainter& painter, int mask, int layer) { UIPainter p(painter, mask, layer); for (auto& c: getChildren()) { c->doDraw(p); } } void UIRoot::playSound(const std::shared_ptr<const AudioClip>& clip) { if (audio && clip) { audio->playUI(clip); } } void UIRoot::sendEvent(UIEvent&&) const { // Unhandled event } bool UIRoot::hasModalUI() const { for (auto& c: getChildren()) { if (c->isModal()) { return true; } } return false; } bool UIRoot::isMouseOverUI() const { return static_cast<bool>(currentMouseOver.lock()); } UIWidget* UIRoot::getCurrentFocus() const { return currentFocus.lock().get(); } <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 "drivers/QSPI.h" #include "platform/mbed_critical.h" #if DEVICE_QSPI namespace mbed { QSPI* QSPI::_owner = NULL; SingletonPtr<PlatformMutex> QSPI::_mutex; QSPI::QSPI(PinName io0, PinName io1, PinName io2, PinName io3, PinName sclk, PinName ssel) : _qspi() { _qspi_io0 = io0; _qspi_io1 = io1; _qspi_io2 = io2; _qspi_io3 = io3; _qspi_clk = sclk; _qspi_cs = ssel; _inst_width = QSPI_CFG_BUS_SINGLE; _address_width = QSPI_CFG_BUS_SINGLE; _address_size = QSPI_CFG_ADDR_SIZE_24; _alt_width = QSPI_CFG_BUS_SINGLE; _alt_size = QSPI_CFG_ALT_SIZE_NONE; _data_width = QSPI_CFG_BUS_SINGLE; _num_dummy_cycles = 0; _mode = 0; _hz = ONE_MHZ; _initialized = false; //Go ahead init the device here with the default config _initialize(); } qspi_status_t QSPI::configure_format(qspi_bus_width_t inst_width, qspi_bus_width_t address_width, qspi_address_size_t address_size, qspi_bus_width_t alt_width, qspi_alt_size_t alt_size, qspi_bus_width_t data_width, int dummy_cycles, int mode ) { qspi_status_t ret_status = QSPI_STATUS_OK; if (mode != 0 && mode != 1) return QSPI_STATUS_INVALID_PARAMETER; lock(); _inst_width = inst_width; _address_width = address_width; _address_size = address_size; _alt_width = alt_width; _alt_size = alt_size; _data_width = data_width; _num_dummy_cycles = dummy_cycles; _mode = mode; //Re-init the device, as the mode might have changed if ( !_initialize() ) { ret_status = QSPI_STATUS_ERROR; } unlock(); return ret_status; } qspi_status_t QSPI::set_frequency(int hz) { qspi_status_t ret_status = QSPI_STATUS_OK; if (_initialized) { lock(); _hz = hz; //If the same owner, just change freq. //Otherwise we may have to change mode as well, so call _acquire if (_owner == this) { if (QSPI_STATUS_OK != qspi_frequency(&_qspi, _hz)) { ret_status = QSPI_STATUS_ERROR; } } else { _acquire(); } unlock(); } else { ret_status = QSPI_STATUS_ERROR; } return ret_status; } qspi_status_t QSPI::read(unsigned int address, char *rx_buffer, size_t *rx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ((rx_length != NULL) && (rx_buffer != NULL)) { if (*rx_length != 0) { lock(); if (true == _acquire()) { _build_qspi_command(-1, address, -1); if (QSPI_STATUS_OK == qspi_read(&_qspi, &_qspi_command, rx_buffer, rx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::write(unsigned int address, const char *tx_buffer, size_t *tx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ((tx_length != NULL) && (tx_buffer != NULL)) { if (*tx_length != 0) { lock(); if (true == _acquire()) { _build_qspi_command(-1, address, -1); if (QSPI_STATUS_OK == qspi_write(&_qspi, &_qspi_command, tx_buffer, tx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::read(unsigned int instruction, unsigned int alt, unsigned int address, char *rx_buffer, size_t *rx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ( (rx_length != NULL) && (rx_buffer != NULL) ) { if (*rx_length != 0) { lock(); if ( true == _acquire()) { _build_qspi_command(instruction, address, alt); if (QSPI_STATUS_OK == qspi_read(&_qspi, &_qspi_command, rx_buffer, rx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::write(unsigned int instruction, unsigned int alt, unsigned int address, const char *tx_buffer, size_t *tx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ( (tx_length != NULL) && (tx_buffer != NULL) ) { if (*tx_length != 0) { lock(); if (true == _acquire()) { _build_qspi_command(instruction, address, alt); if (QSPI_STATUS_OK == qspi_write(&_qspi, &_qspi_command, tx_buffer, tx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::command_transfer(unsigned int instruction, const char *tx_buffer, size_t tx_length, const char *rx_buffer, size_t rx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { lock(); if (true == _acquire()) { _build_qspi_command(instruction, -1, -1); //We just need the command if (QSPI_STATUS_OK == qspi_command_transfer(&_qspi, &_qspi_command, (const void *)tx_buffer, tx_length, (void *)rx_buffer, rx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } return ret_status; } void QSPI::lock() { _mutex->lock(); } void QSPI::unlock() { _mutex->unlock(); } // Note: Private helper function to initialize qspi HAL bool QSPI::_initialize() { qspi_status_t ret = qspi_init(&_qspi, _qspi_io0, _qspi_io1, _qspi_io2, _qspi_io3, _qspi_clk, _qspi_cs, _hz, _mode ); if (QSPI_STATUS_OK == ret) { _initialized = true; } else { _initialized = false; } return _initialized; } // Note: Private function with no locking bool QSPI::_acquire() { if (_owner != this) { //This will set freq as well _initialize(); _owner = this; } return _initialized; } void QSPI::_build_qspi_command(int instruction, int address, int alt) { memset( &_qspi_command, 0, sizeof(qspi_command_t) ); //Set up instruction phase parameters _qspi_command.instruction.bus_width = _inst_width; if (instruction != -1) { _qspi_command.instruction.value = instruction; } else { _qspi_command.instruction.value = 0; } //Set up address phase parameters _qspi_command.address.bus_width = _address_width; _qspi_command.address.size = _address_size; if (address != -1) { _qspi_command.address.value = address; } else { _qspi_command.address.size = QSPI_CFG_ADDR_SIZE_NONE; } //Set up alt phase parameters _qspi_command.alt.bus_width = _alt_width; _qspi_command.alt.size = _alt_size; if (alt != -1) { _qspi_command.alt.value = alt; } else { //In the case alt phase is absent, set the alt size to be NONE _qspi_command.alt.value = 0; } _qspi_command.dummy_count = _num_dummy_cycles; //Set up bus width for data phase _qspi_command.data.bus_width = _data_width; } } // namespace mbed #endif <commit_msg>QSPI: fix alt size NONE instead 0<commit_after>/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 "drivers/QSPI.h" #include "platform/mbed_critical.h" #if DEVICE_QSPI namespace mbed { QSPI* QSPI::_owner = NULL; SingletonPtr<PlatformMutex> QSPI::_mutex; QSPI::QSPI(PinName io0, PinName io1, PinName io2, PinName io3, PinName sclk, PinName ssel) : _qspi() { _qspi_io0 = io0; _qspi_io1 = io1; _qspi_io2 = io2; _qspi_io3 = io3; _qspi_clk = sclk; _qspi_cs = ssel; _inst_width = QSPI_CFG_BUS_SINGLE; _address_width = QSPI_CFG_BUS_SINGLE; _address_size = QSPI_CFG_ADDR_SIZE_24; _alt_width = QSPI_CFG_BUS_SINGLE; _alt_size = QSPI_CFG_ALT_SIZE_NONE; _data_width = QSPI_CFG_BUS_SINGLE; _num_dummy_cycles = 0; _mode = 0; _hz = ONE_MHZ; _initialized = false; //Go ahead init the device here with the default config _initialize(); } qspi_status_t QSPI::configure_format(qspi_bus_width_t inst_width, qspi_bus_width_t address_width, qspi_address_size_t address_size, qspi_bus_width_t alt_width, qspi_alt_size_t alt_size, qspi_bus_width_t data_width, int dummy_cycles, int mode ) { qspi_status_t ret_status = QSPI_STATUS_OK; if (mode != 0 && mode != 1) return QSPI_STATUS_INVALID_PARAMETER; lock(); _inst_width = inst_width; _address_width = address_width; _address_size = address_size; _alt_width = alt_width; _alt_size = alt_size; _data_width = data_width; _num_dummy_cycles = dummy_cycles; _mode = mode; //Re-init the device, as the mode might have changed if ( !_initialize() ) { ret_status = QSPI_STATUS_ERROR; } unlock(); return ret_status; } qspi_status_t QSPI::set_frequency(int hz) { qspi_status_t ret_status = QSPI_STATUS_OK; if (_initialized) { lock(); _hz = hz; //If the same owner, just change freq. //Otherwise we may have to change mode as well, so call _acquire if (_owner == this) { if (QSPI_STATUS_OK != qspi_frequency(&_qspi, _hz)) { ret_status = QSPI_STATUS_ERROR; } } else { _acquire(); } unlock(); } else { ret_status = QSPI_STATUS_ERROR; } return ret_status; } qspi_status_t QSPI::read(unsigned int address, char *rx_buffer, size_t *rx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ((rx_length != NULL) && (rx_buffer != NULL)) { if (*rx_length != 0) { lock(); if (true == _acquire()) { _build_qspi_command(-1, address, -1); if (QSPI_STATUS_OK == qspi_read(&_qspi, &_qspi_command, rx_buffer, rx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::write(unsigned int address, const char *tx_buffer, size_t *tx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ((tx_length != NULL) && (tx_buffer != NULL)) { if (*tx_length != 0) { lock(); if (true == _acquire()) { _build_qspi_command(-1, address, -1); if (QSPI_STATUS_OK == qspi_write(&_qspi, &_qspi_command, tx_buffer, tx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::read(unsigned int instruction, unsigned int alt, unsigned int address, char *rx_buffer, size_t *rx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ( (rx_length != NULL) && (rx_buffer != NULL) ) { if (*rx_length != 0) { lock(); if ( true == _acquire()) { _build_qspi_command(instruction, address, alt); if (QSPI_STATUS_OK == qspi_read(&_qspi, &_qspi_command, rx_buffer, rx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::write(unsigned int instruction, unsigned int alt, unsigned int address, const char *tx_buffer, size_t *tx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { if ( (tx_length != NULL) && (tx_buffer != NULL) ) { if (*tx_length != 0) { lock(); if (true == _acquire()) { _build_qspi_command(instruction, address, alt); if (QSPI_STATUS_OK == qspi_write(&_qspi, &_qspi_command, tx_buffer, tx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } } else { ret_status = QSPI_STATUS_INVALID_PARAMETER; } } return ret_status; } qspi_status_t QSPI::command_transfer(unsigned int instruction, const char *tx_buffer, size_t tx_length, const char *rx_buffer, size_t rx_length) { qspi_status_t ret_status = QSPI_STATUS_ERROR; if (_initialized) { lock(); if (true == _acquire()) { _build_qspi_command(instruction, -1, -1); //We just need the command if (QSPI_STATUS_OK == qspi_command_transfer(&_qspi, &_qspi_command, (const void *)tx_buffer, tx_length, (void *)rx_buffer, rx_length)) { ret_status = QSPI_STATUS_OK; } } unlock(); } return ret_status; } void QSPI::lock() { _mutex->lock(); } void QSPI::unlock() { _mutex->unlock(); } // Note: Private helper function to initialize qspi HAL bool QSPI::_initialize() { qspi_status_t ret = qspi_init(&_qspi, _qspi_io0, _qspi_io1, _qspi_io2, _qspi_io3, _qspi_clk, _qspi_cs, _hz, _mode ); if (QSPI_STATUS_OK == ret) { _initialized = true; } else { _initialized = false; } return _initialized; } // Note: Private function with no locking bool QSPI::_acquire() { if (_owner != this) { //This will set freq as well _initialize(); _owner = this; } return _initialized; } void QSPI::_build_qspi_command(int instruction, int address, int alt) { memset( &_qspi_command, 0, sizeof(qspi_command_t) ); //Set up instruction phase parameters _qspi_command.instruction.bus_width = _inst_width; if (instruction != -1) { _qspi_command.instruction.value = instruction; } else { _qspi_command.instruction.value = 0; } //Set up address phase parameters _qspi_command.address.bus_width = _address_width; _qspi_command.address.size = _address_size; if (address != -1) { _qspi_command.address.value = address; } else { _qspi_command.address.size = QSPI_CFG_ADDR_SIZE_NONE; } //Set up alt phase parameters _qspi_command.alt.bus_width = _alt_width; _qspi_command.alt.size = _alt_size; if (alt != -1) { _qspi_command.alt.value = alt; } else { //In the case alt phase is absent, set the alt size to be NONE _qspi_command.alt.size = QSPI_CFG_ALT_SIZE_NONE; } _qspi_command.dummy_count = _num_dummy_cycles; //Set up bus width for data phase _qspi_command.data.bus_width = _data_width; } } // namespace mbed #endif <|endoftext|>
<commit_before>/// AdcDac driver /// /// (c) Koheron #ifndef __DRIVERS_CLUSTER_HPP__ #define __DRIVERS_CLUSTER_HPP__ #include <context.hpp> class Cluster { public: Cluster(Context& ctx) : ctl(ctx.mm.get<mem::control>()) , sts(ctx.mm.get<mem::status>()) , ctl_clk(ctx.mm.get<mem::ctl_clk>()) {} void phase_shift(uint32_t incdec) { ctl_clk.write_mask<0, (1 << 2) + (1 << 3)>((1 << 2) + (incdec << 3)); ctl_clk.clear_bit<0, 2>(); } // Trigger void trig_pulse() { ctl.set_bit<reg::trigger, 0>(); ctl.clear_bit<reg::trigger, 0>(); } // Pulse generator void set_pulse_generator(uint32_t pulse_width, uint32_t pulse_period) { ctl.write<reg::pulse_width>(pulse_width); ctl.write<reg::pulse_period>(pulse_period); } void clk_sel(uint32_t clk_sel) { ctl_clk.write_bit<0, 1>(1); ctl_clk.write_bit<0, 0>(clk_sel); ctl_clk.write_bit<0, 1>(0); } uint32_t read_sata() { return sts.read<reg::sts_sata>(); } void ctl_sata(uint32_t sata_out_sel, uint32_t trig_delay) { ctl.write<reg::ctl_sata>(sata_out_sel + (trig_delay << 1)); } void set_phase_increment(uint64_t phase_incr) { ctl.write<reg::phase_incr0, uint64_t>(phase_incr); } void set_freq(double freq_hz) { constexpr double factor = (uint64_t(1) << 48) / double(prm::adc_clk); set_phase_increment(uint64_t(factor * freq_hz)); } auto get_adc() { // Convert from two-complement to int32 int32_t adc0 = ((static_cast<int32_t>(sts.read<reg::adc0>()) - 8192) % 16384) - 8192; int32_t adc1 = ((static_cast<int32_t>(sts.read<reg::adc1>()) - 8192) % 16384) - 8192; return std::make_tuple(adc0, adc1); } private: Memory<mem::control>& ctl; Memory<mem::status>& sts; Memory<mem::ctl_clk>& ctl_clk; }; #endif // __DRIVERS_CLUSTER_HPP__ <commit_msg>Add debugging example in cluster.hpp<commit_after>/// AdcDac driver /// /// (c) Koheron #ifndef __DRIVERS_CLUSTER_HPP__ #define __DRIVERS_CLUSTER_HPP__ #include <context.hpp> class Cluster { public: Cluster(Context& ctx_) : ctx(ctx_) , ctl(ctx.mm.get<mem::control>()) , sts(ctx.mm.get<mem::status>()) , ctl_clk(ctx.mm.get<mem::ctl_clk>()) {} void phase_shift(uint32_t incdec) { ctl_clk.write_mask<0, (1 << 2) + (1 << 3)>((1 << 2) + (incdec << 3)); ctl_clk.clear_bit<0, 2>(); } // Trigger void trig_pulse() { ctl.set_bit<reg::trigger, 0>(); ctl.clear_bit<reg::trigger, 0>(); } // Pulse generator void set_pulse_generator(uint32_t pulse_width, uint32_t pulse_period) { ctl.write<reg::pulse_width>(pulse_width); ctl.write<reg::pulse_period>(pulse_period); } void clk_sel(uint32_t clk_sel) { ctl_clk.write_bit<0, 1>(1); ctl_clk.write_bit<0, 0>(clk_sel); ctl_clk.write_bit<0, 1>(0); } uint32_t read_sata() { return sts.read<reg::sts_sata>(); } void ctl_sata(uint32_t sata_out_sel, uint32_t trig_delay) { ctl.write<reg::ctl_sata>(sata_out_sel + (trig_delay << 1)); } void set_phase_increment(uint64_t phase_incr) { ctl.write<reg::phase_incr0, uint64_t>(phase_incr); } void set_freq(double freq_hz) { constexpr double factor = (uint64_t(1) << 48) / double(prm::adc_clk); set_phase_increment(uint64_t(factor * freq_hz)); ctx.log<INFO>("Frequency set to %f Hz/n", freq_hz); } auto get_adc() { // Convert from two-complement to int32 int32_t adc0 = ((static_cast<int32_t>(sts.read<reg::adc0>()) - 8192) % 16384) - 8192; int32_t adc1 = ((static_cast<int32_t>(sts.read<reg::adc1>()) - 8192) % 16384) - 8192; return std::make_tuple(adc0, adc1); } private: Context& ctx; Memory<mem::control>& ctl; Memory<mem::status>& sts; Memory<mem::ctl_clk>& ctl_clk; }; #endif // __DRIVERS_CLUSTER_HPP__ <|endoftext|>
<commit_before>#pragma once namespace opttmp { namespace memory_layout { // component type has to be indexable, and has to have a size() operator template <typename vector_type, typename component_type, typename AoS_container_type> class struct_of_array_data { private: // data in SoA form size_t num_components; size_t entries; size_t padding; size_t padded_entries_per_component; component_type *const data; public: template <size_t component_access> inline component_type *pointer(const size_t flat_index) const { constexpr size_t component_array_offset = component_access * padded_entries_per_component; // should result in single move instruction, indirect addressing: reg + reg // + constant return data + flat_index + component_array_offset; } inline component_type *pointer(const size_t component_access, const size_t flat_index) const { const size_t component_array_offset = component_access * padded_entries_per_component; // should result in single move instruction, indirect addressing: reg + reg // + constant return data + flat_index + component_array_offset; } // careful, this returns a copy! template <size_t component_access> inline vector_type value(const size_t flat_index) const { return vector_type(this->pointer<component_access>(flat_index), Vc::flags::element_aligned); } struct_of_array_data(const AoS_container_type &org, size_t num_components, size_t entries, size_t padding) : num_components(num_components), entries(entries), padding(padding), padded_entries_per_component(entries + padding), data( new component_type[num_components * padded_entries_per_component]) { for (size_t component = 0; component < num_components; component++) { for (size_t entry = 0; entry < entries; entry++) { data[component * padded_entries_per_component + entry] = org[entry * num_components + component]; // org[entry][component]; } } for (size_t component = 0; component < num_components; component++) { for (size_t entry = entries; entry < padded_entries_per_component; entry++) { data[component * padded_entries_per_component + entry] = 0.0; } } } struct_of_array_data(const size_t entries_per_component) : data( new component_type[num_components * padded_entries_per_component]) { } ~struct_of_array_data() { if (data) { delete[] data; } } struct_of_array_data(const struct_of_array_data &other) = delete; struct_of_array_data(const struct_of_array_data &&other) = delete; struct_of_array_data &operator=(const struct_of_array_data &other) = delete; // write back into non-SoA style array void to_non_SoA(AoS_container_type &org) { for (size_t component = 0; component < num_components; component++) { for (size_t entry = 0; entry < org.size(); entry++) { // org[entry][component] = org[entry * num_components + component] = data[component * padded_entries_per_component + entry]; } } } }; } // namespace memory_layout } // namespace opttmp <commit_msg>faster SoA conversion template<commit_after>#pragma once namespace opttmp { namespace memory_layout { // component type has to be indexable, and has to have a size() operator template <typename vc_type, typename AoS_container_type, size_t num_components, size_t entries, size_t padding> class struct_of_array_data { private: // data in SoA form // const size_t num_components; // const size_t entries; // const size_t padding; static constexpr size_t padded_entries_per_component = entries + padding; typename vc_type::value_type *const data; public: template <size_t component_access> inline typename vc_type::value_type *pointer(const size_t flat_index) const { constexpr size_t component_array_offset = component_access * padded_entries_per_component; // should result in single move instruction, indirect addressing: reg + reg // + constant return data + flat_index + component_array_offset; } inline typename vc_type::value_type *pointer(const size_t component_access, const size_t flat_index) const { // const size_t component_array_offset = // component_access * padded_entries_per_component; // should result in single move instruction, indirect addressing: reg + reg // + constant // return data + flat_index + component_array_offset; return data + component_access * padded_entries_per_component + flat_index; } // careful, this returns a copy! template <size_t component_access> inline vc_type value(const size_t flat_index) const { return vc_type(this->pointer<component_access>(flat_index), Vc::flags::element_aligned); } struct_of_array_data(const AoS_container_type &org //, size_t num_components, // size_t entries, size_t padding ) : // num_components(num_components), // entries(entries), // padding(padding), padded_entries_per_component(entries + padding), data(new typename vc_type::value_type[num_components * padded_entries_per_component]) { for (size_t component = 0; component < num_components; component++) { for (size_t entry = 0; entry < entries; entry++) { data[component * padded_entries_per_component + entry] = org[entry * num_components + component]; // org[entry][component]; } } for (size_t component = 0; component < num_components; component++) { for (size_t entry = entries; entry < padded_entries_per_component; entry++) { data[component * padded_entries_per_component + entry] = 0.0; } } } struct_of_array_data(const size_t entries_per_component) : data(new typename vc_type::value_type[num_components * padded_entries_per_component]) {} ~struct_of_array_data() { if (data) { delete[] data; } } struct_of_array_data(const struct_of_array_data &other) = delete; struct_of_array_data(const struct_of_array_data &&other) = delete; struct_of_array_data &operator=(const struct_of_array_data &other) = delete; // write back into non-SoA style array void to_non_SoA(AoS_container_type &org) { for (size_t component = 0; component < num_components; component++) { for (size_t entry = 0; entry < org.size(); entry++) { // org[entry][component] = org[entry * num_components + component] = data[component * padded_entries_per_component + entry]; } } } }; } // namespace memory_layout } // namespace opttmp <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_lpc_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file p9_lpc_utils.H /// /// @brief Helper functions for indirect reads/writes to the LPC register space /// @author Joachim Fenkes <[email protected]> #ifndef P9_LPC_UTILS_H_ #define P9_LPC_UTILS_H_ const uint32_t LPC_CMD_TIMEOUT_DELAY_NS = 1000000; const uint32_t LPC_CMD_TIMEOUT_DELAY_CYCLE = 80000000; const uint32_t LPC_CMD_TIMEOUT_COUNT = 20; static fapi2::ReturnCode lpc_rw( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, uint32_t i_addr, bool i_read_notwrite, fapi2::buffer<uint32_t>& io_data) { const int l_bit_offset = (i_addr & 4) << 3; fapi2::buffer<uint64_t> l_command; l_command.writeBit<PU_LPC_CMD_REG_RNW>(i_read_notwrite) .insertFromRight<PU_LPC_CMD_REG_SIZE, PU_LPC_CMD_REG_SIZE_LEN>(0x4) .insertFromRight<PU_LPC_CMD_REG_ADR, PU_LPC_CMD_REG_ADR_LEN>(i_addr); FAPI_TRY(fapi2::putScom(i_target_chip, PU_LPC_CMD_REG, l_command), "Error writing LPC command register"); if (!i_read_notwrite) { fapi2::buffer<uint64_t> l_data; l_data.insert(io_data, l_bit_offset, 32); FAPI_TRY(fapi2::putScom(i_target_chip, PU_LPC_DATA_REG, l_data), "Error writing LPC data"); } { fapi2::buffer<uint64_t> l_status; int timeout = LPC_CMD_TIMEOUT_COUNT; while (timeout--) { FAPI_TRY(fapi2::getScom(i_target_chip, PU_LPC_STATUS_REG, l_status), "Error reading LPC status"); if (l_status.getBit<PU_LPC_STATUS_REG_DONE>()) { break; } fapi2::delay(LPC_CMD_TIMEOUT_DELAY_NS, LPC_CMD_TIMEOUT_DELAY_CYCLE); } if (LPC_UTILS_TIMEOUT_FFDC) { FAPI_ASSERT(l_status.getBit<PU_LPC_STATUS_REG_DONE>(), fapi2::LPC_ACCESS_TIMEOUT() .set_TARGET_CHIP(i_target_chip) .set_COUNT(LPC_CMD_TIMEOUT_COUNT) .set_COMMAND(l_command) .set_DATA(io_data) .set_STATUS(l_status), "LPC access timed out"); } else if (!l_status.getBit<PU_LPC_STATUS_REG_DONE>()) { return fapi2::RC_LPC_ACCESS_TIMEOUT; } } if (i_read_notwrite) { fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target_chip, PU_LPC_DATA_REG, l_data), "Error reading LPC data"); l_data.extract(io_data, l_bit_offset, 32); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } static inline fapi2::ReturnCode lpc_read( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, uint32_t i_addr, fapi2::buffer<uint32_t>& o_data) { return lpc_rw(i_target_chip, i_addr, true, o_data); } static inline fapi2::ReturnCode lpc_write( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, uint32_t i_addr, fapi2::buffer<uint32_t> i_data) { return lpc_rw(i_target_chip, i_addr, false, i_data); } #endif /* P9_LPC_UTILS_H_ */ <commit_msg>p9_sbe_lpc_init: Improve reset<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_lpc_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file p9_lpc_utils.H /// /// @brief Helper functions for indirect reads/writes to the LPC register space /// @author Joachim Fenkes <[email protected]> #ifndef P9_LPC_UTILS_H_ #define P9_LPC_UTILS_H_ const uint32_t LPC_CMD_TIMEOUT_DELAY_NS = 1000000; const uint32_t LPC_CMD_TIMEOUT_DELAY_CYCLE = 1000000; const uint32_t LPC_CMD_TIMEOUT_COUNT = 20; static fapi2::ReturnCode lpc_rw( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, uint32_t i_addr, bool i_read_notwrite, fapi2::buffer<uint32_t>& io_data) { const int l_bit_offset = (i_addr & 4) << 3; fapi2::buffer<uint64_t> l_command; l_command.writeBit<PU_LPC_CMD_REG_RNW>(i_read_notwrite) .insertFromRight<PU_LPC_CMD_REG_SIZE, PU_LPC_CMD_REG_SIZE_LEN>(0x4) .insertFromRight<PU_LPC_CMD_REG_ADR, PU_LPC_CMD_REG_ADR_LEN>(i_addr); FAPI_TRY(fapi2::putScom(i_target_chip, PU_LPC_CMD_REG, l_command), "Error writing LPC command register"); if (!i_read_notwrite) { fapi2::buffer<uint64_t> l_data; l_data.insert(io_data, l_bit_offset, 32); FAPI_TRY(fapi2::putScom(i_target_chip, PU_LPC_DATA_REG, l_data), "Error writing LPC data"); } { fapi2::buffer<uint64_t> l_status; int timeout = LPC_CMD_TIMEOUT_COUNT; while (timeout--) { FAPI_TRY(fapi2::getScom(i_target_chip, PU_LPC_STATUS_REG, l_status), "Error reading LPC status"); if (l_status.getBit<PU_LPC_STATUS_REG_DONE>()) { break; } fapi2::delay(LPC_CMD_TIMEOUT_DELAY_NS, LPC_CMD_TIMEOUT_DELAY_CYCLE); } if (LPC_UTILS_TIMEOUT_FFDC) { FAPI_ASSERT(l_status.getBit<PU_LPC_STATUS_REG_DONE>(), fapi2::LPC_ACCESS_TIMEOUT() .set_TARGET_CHIP(i_target_chip) .set_COUNT(LPC_CMD_TIMEOUT_COUNT) .set_COMMAND(l_command) .set_DATA(io_data) .set_STATUS(l_status), "LPC access timed out"); } else if (!l_status.getBit<PU_LPC_STATUS_REG_DONE>()) { return fapi2::RC_LPC_ACCESS_TIMEOUT; } } if (i_read_notwrite) { fapi2::buffer<uint64_t> l_data; FAPI_TRY(fapi2::getScom(i_target_chip, PU_LPC_DATA_REG, l_data), "Error reading LPC data"); l_data.extract(io_data, l_bit_offset, 32); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } static inline fapi2::ReturnCode lpc_read( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, uint32_t i_addr, fapi2::buffer<uint32_t>& o_data) { return lpc_rw(i_target_chip, i_addr, true, o_data); } static inline fapi2::ReturnCode lpc_write( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, uint32_t i_addr, fapi2::buffer<uint32_t> i_data) { return lpc_rw(i_target_chip, i_addr, false, i_data); } #endif /* P9_LPC_UTILS_H_ */ <|endoftext|>
<commit_before>#include "../core/op_algo.h" #include "../core/gradient_helper.h" #include "basic_arithmetics.h" #include "matmul.h" #include "initializer.h" #include <algorithm> namespace mlfe{ namespace functional{ REGIST_OP(Negative) .Input("X", "float32") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto y = odc->Output(0); y.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(Negative) .Input("X", "float32") .Input("dY", "float32") .Output("dX", "float32") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(1); auto dx = odc->Output(0); dx.reshape(dy.shape(), type::float32()); }) .Finish(); class NegativeGradient : public GradientHelper{ public: NegativeGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; auto dx = functional::negative(dy); in_grads.push_back(dx); return in_grads; } }; REGIST_GRADIENT_HELPER(Negative, NegativeGradient) REGIST_OP(ElementwiseAdd) .Input("X1", "float32") .Input("X2", "float32") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto x2 = odc->Input(1); auto y = odc->Output(0); if(x1.size() != x2.size()){ throw std::string("ElementwiseAdd : " "the Shape of A and B is not same."); } y.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(ElementwiseAdd) .Input("X1", "float32") .Input("X2", "float32") .Input("dY", "float32") .Output("dX1", "float32") .Output("dX2", "float32") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(1); auto dx1 = odc->Output(0); auto dx2 = odc->Output(1); dx1.reshape(dy.shape(), type::float32()); dx2.reshape(dy.shape(), type::float32()); }) .Finish(); class ElementwiseAddGradient : public GradientHelper{ public: ElementwiseAddGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; in_grads.push_back(dy); in_grads.push_back(dy); return in_grads; } }; REGIST_GRADIENT_HELPER(ElementwiseAdd, ElementwiseAddGradient) REGIST_OP(ElementwiseSub) .Input("X1", "float32") .Input("X2", "float32") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto x2 = odc->Input(1); auto y = odc->Output(0); if(x1.size() != x2.size()){ throw std::string("ElementwiseSub : " "the Shape of A and B is not same."); } y.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(ElementwiseSub) .Input("X1", "float32") .Input("X2", "float32") .Input("dY", "float32") .Output("dX1", "float32") .Output("dX2", "float32") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(1); auto dx1 = odc->Output(0); auto dx2 = odc->Output(1); dx1.reshape(dy.shape(), type::float32()); dx2.reshape(dy.shape(), type::float32()); }) .Finish(); class ElementwiseSubGradient : public GradientHelper{ public: ElementwiseSubGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; auto dx1 = dy; auto dx2 = functional::negative(dy); in_grads.push_back(dx1); in_grads.push_back(dx2); return in_grads; } }; REGIST_GRADIENT_HELPER(ElementwiseSub, ElementwiseSubGradient) REGIST_OP(ElementwiseMul) .Input("X1", "float32") .Input("X2", "float32") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto x2 = odc->Input(1); auto y = odc->Output(0); if(x1.size() != x2.size()){ throw std::string("ElementwiseMul : " "the Shape of A and B is not same."); } y.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(ElementwiseMul) .Input("X1", "float32") .Input("X2", "float32") .Input("dY", "float32") .Output("dX1", "float32") .Output("dX2", "float32") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(2); auto dx1 = odc->Output(0); auto dx2 = odc->Output(1); dx1.reshape(dy.shape(), type::float32()); dx2.reshape(dy.shape(), type::float32()); }) .Finish(); class ElementwiseMulGradient : public GradientHelper{ public: ElementwiseMulGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; Tensor x1 = y.get_children()[0]; Tensor x2 = y.get_children()[1]; Tensor dx1 = functional::mul(x2, dy); Tensor dx2 = functional::mul(x1, dy); in_grads.push_back(dx1); in_grads.push_back(dx2); return in_grads; } }; REGIST_GRADIENT_HELPER(ElementwiseMul, ElementwiseMulGradient) REGIST_OP(ElementwiseDiv) .Input("X1", "float32") .Input("X2", "float32") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto x2 = odc->Input(1); auto y = odc->Output(0); if(x1.size() != x2.size()){ throw std::string("ElementwiseDiv : " "the Shape of A and B is not same."); } y.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(ElementwiseDiv) .Input("X1", "float32") .Input("X2", "float32") .Input("dY", "float32") .Output("dX1", "float32") .Output("dX2", "float32") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(2); auto dx1 = odc->Output(0); auto dx2 = odc->Output(1); dx1.reshape(dy.shape(), type::float32()); dx2.reshape(dy.shape(), type::float32()); }) .Finish(); class ElementwiseDivGradient : public GradientHelper{ public: ElementwiseDivGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; auto x1 = y.get_children()[0]; auto x2 = y.get_children()[1]; auto one = functional::constant(1, x2.shape()); auto dx1 = functional::div(one, x2); auto dx2 = functional::negative(functional::div(y, x2)); in_grads.push_back(dx1); in_grads.push_back(dx2); return in_grads; } }; REGIST_GRADIENT_HELPER(ElementwiseDiv, ElementwiseDivGradient) REGIST_OP(AddN) .Input("Xs", "float32s") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto c = odc->Output(0); int num = odc->NumInput(); for(int n = 1; n < num; ++n){ if(x1.size() != odc->Input(n).size()){ throw std::string("AddN : " "the Shape of Inputs is not same."); } } c.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(AddN) .Input("dY", "float32") .Output("dXs", "float32s") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(0); for(int n = 0; n < odc->NumOutput(); ++n){ Tensor d = odc->Output(n); d.reshape(dy.shape(), type::float32()); } }) .Finish(); class AddNGradient : public GradientHelper{ public: AddNGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; Tensor x1 = y.get_children()[0]; Tensor x2 = y.get_children()[1]; Tensor dx1 = functional::mul(x2, dy); Tensor dx2 = functional::mul(x1, dy); in_grads.push_back(dx1); in_grads.push_back(dx2); return in_grads; } }; REGIST_GRADIENT_HELPER(AddN, AddNGradient) class MatrixVectorAddGradient : public GradientHelper{ public: MatrixVectorAddGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; Tensor mat = y.get_children()[0]; Tensor vec = y.get_children()[1]; Tensor one = functional::constant(1, {y.shape()[0], 1}); Tensor dvec = functional::matmul(dy, one, true); one.eval(); in_grads.push_back(dy); in_grads.push_back(dvec); return in_grads; } }; REGIST_GRADIENT_HELPER(MatrixVectorAdd, MatrixVectorAddGradient) template <> Tensor Add<double>(Tensor a, double b){ Tensor y; throw std::string("Tensor add op with Scalar Value is not support."); return y; } template <> Tensor Sub<double>(Tensor a, double b){ Tensor y; throw std::string("Tensor sub op with scalar value is not support."); return y; } template <> Tensor Mul<double>(Tensor a, double b){ Tensor y; throw std::string("Tensor mul op with Scalar Value is not support."); return y; } template <> Tensor Div<double>(Tensor a, double b){ Tensor y; throw std::string("Tensor div op with Scalar Value is not support."); return y; } Tensor negative(Tensor x){ OpAlgoContext cxt("Negative"); Tensor y = create_variable(x.shape()); auto x_shape = x.shape(); y.add_child(x); Tensor::AssignOpFunctor(y, cxt); return y; } Tensor add(Tensor x1, Tensor x2){ Tensor y; auto x1_shape = x1.shape(); auto x2_shape = x2.shape(); auto max_dim = std::max(x1_shape.size(), x2_shape.size()); auto min_dim = std::min(x1_shape.size(), x2_shape.size()); std::vector<int> max_shape, min_shape; if(max_dim == x1_shape.size()){ max_shape = x1_shape; min_shape = x2_shape; } else{ max_shape = x2_shape; min_shape = x1_shape; } y = functional::create_variable(max_shape); y.add_child(x1); y.add_child(x2); if(max_dim == 4 && min_dim == 1){ if(max_shape[1] == min_shape[0]){ OpAlgoContext cxt("BatchedMatrixVectorAdd"); Tensor::AssignOpFunctor(y, cxt); } else{ std::string err = "Can not add with "; err += std::to_string(max_dim) + "d"; err += " and "; err += std::to_string(min_dim) + "d"; throw err; } } else if(max_dim == 2 && min_dim == 1){ if(max_shape[1] == min_shape[0]){ OpAlgoContext cxt("MatrixVectorAdd"); Tensor::AssignOpFunctor(y, cxt); } else{ std::string err = "Can not add with "; err += std::to_string(max_dim) + "d"; err += " and "; err += std::to_string(min_dim) + "d"; throw err; } } else if(max_dim == min_dim){ OpAlgoContext cxt("ElementwiseAdd"); Tensor::AssignOpFunctor(y, cxt); } return y; } Tensor sub(Tensor x1, Tensor x2){ Tensor y = functional::create_variable(x1.shape()); OpAlgoContext cxt("ElementwiseSub"); y.add_child(x1); y.add_child(x2); Tensor::AssignOpFunctor(y, cxt); return y; } Tensor mul(Tensor x1, Tensor x2){ Tensor y = functional::create_variable(x1.shape()); OpAlgoContext cxt("ElementwiseMul"); y.add_child(x1); y.add_child(x2); Tensor::AssignOpFunctor(y, cxt); return y; } Tensor div(Tensor x1, Tensor x2){ Tensor y = functional::create_variable(x1.shape()); OpAlgoContext cxt("ElementwiseDiv"); y.add_child(x1); y.add_child(x2); Tensor::AssignOpFunctor(y, cxt); return y; } Tensor add_n(std::vector<Tensor> xs){ if(xs.size() >= 2){ Tensor y = functional::create_variable(xs[0].shape()); OpAlgoContext cxt("AddN"); for(auto &x : xs){ y.add_child(x); } Tensor::AssignOpFunctor(y, cxt); return y; } else if(xs.size() == 1){ return xs[0]; } else{ throw std::string("functional::Add(std::vector<Tensor>) Input Size 0"); } } } // end namespace functional #define DEFINE_BASIC_ARITHMETIC_TENSOR_EXPR(OpName, Expr) \ template <> \ Tensor operator Expr<Tensor>(Tensor a, Tensor b){ \ return functional::OpName(a, b); \ } DEFINE_BASIC_ARITHMETIC_TENSOR_EXPR(add, +) //DEFINE_BASIC_ARITHMETIC_TENSOR_EXPR(sub, -) DEFINE_BASIC_ARITHMETIC_TENSOR_EXPR(mul, *) //DEFINE_BASIC_ARITHMETIC_TENSOR_EXPR(div, /) } // end namespace mlfe <commit_msg>remove constant evaluation in MatVec gradient operator.<commit_after>#include "../core/op_algo.h" #include "../core/gradient_helper.h" #include "basic_arithmetics.h" #include "matmul.h" #include "initializer.h" #include <algorithm> namespace mlfe{ namespace functional{ REGIST_OP(Negative) .Input("X", "float32") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto y = odc->Output(0); y.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(Negative) .Input("X", "float32") .Input("dY", "float32") .Output("dX", "float32") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(1); auto dx = odc->Output(0); dx.reshape(dy.shape(), type::float32()); }) .Finish(); class NegativeGradient : public GradientHelper{ public: NegativeGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; auto dx = functional::negative(dy); in_grads.push_back(dx); return in_grads; } }; REGIST_GRADIENT_HELPER(Negative, NegativeGradient) REGIST_OP(ElementwiseAdd) .Input("X1", "float32") .Input("X2", "float32") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto x2 = odc->Input(1); auto y = odc->Output(0); if(x1.size() != x2.size()){ throw std::string("ElementwiseAdd : " "the Shape of A and B is not same."); } y.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(ElementwiseAdd) .Input("X1", "float32") .Input("X2", "float32") .Input("dY", "float32") .Output("dX1", "float32") .Output("dX2", "float32") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(1); auto dx1 = odc->Output(0); auto dx2 = odc->Output(1); dx1.reshape(dy.shape(), type::float32()); dx2.reshape(dy.shape(), type::float32()); }) .Finish(); class ElementwiseAddGradient : public GradientHelper{ public: ElementwiseAddGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; in_grads.push_back(dy); in_grads.push_back(dy); return in_grads; } }; REGIST_GRADIENT_HELPER(ElementwiseAdd, ElementwiseAddGradient) REGIST_OP(ElementwiseSub) .Input("X1", "float32") .Input("X2", "float32") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto x2 = odc->Input(1); auto y = odc->Output(0); if(x1.size() != x2.size()){ throw std::string("ElementwiseSub : " "the Shape of A and B is not same."); } y.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(ElementwiseSub) .Input("X1", "float32") .Input("X2", "float32") .Input("dY", "float32") .Output("dX1", "float32") .Output("dX2", "float32") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(1); auto dx1 = odc->Output(0); auto dx2 = odc->Output(1); dx1.reshape(dy.shape(), type::float32()); dx2.reshape(dy.shape(), type::float32()); }) .Finish(); class ElementwiseSubGradient : public GradientHelper{ public: ElementwiseSubGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; auto dx1 = dy; auto dx2 = functional::negative(dy); in_grads.push_back(dx1); in_grads.push_back(dx2); return in_grads; } }; REGIST_GRADIENT_HELPER(ElementwiseSub, ElementwiseSubGradient) REGIST_OP(ElementwiseMul) .Input("X1", "float32") .Input("X2", "float32") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto x2 = odc->Input(1); auto y = odc->Output(0); if(x1.size() != x2.size()){ throw std::string("ElementwiseMul : " "the Shape of A and B is not same."); } y.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(ElementwiseMul) .Input("X1", "float32") .Input("X2", "float32") .Input("dY", "float32") .Output("dX1", "float32") .Output("dX2", "float32") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(2); auto dx1 = odc->Output(0); auto dx2 = odc->Output(1); dx1.reshape(dy.shape(), type::float32()); dx2.reshape(dy.shape(), type::float32()); }) .Finish(); class ElementwiseMulGradient : public GradientHelper{ public: ElementwiseMulGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; Tensor x1 = y.get_children()[0]; Tensor x2 = y.get_children()[1]; Tensor dx1 = functional::mul(x2, dy); Tensor dx2 = functional::mul(x1, dy); in_grads.push_back(dx1); in_grads.push_back(dx2); return in_grads; } }; REGIST_GRADIENT_HELPER(ElementwiseMul, ElementwiseMulGradient) REGIST_OP(ElementwiseDiv) .Input("X1", "float32") .Input("X2", "float32") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto x2 = odc->Input(1); auto y = odc->Output(0); if(x1.size() != x2.size()){ throw std::string("ElementwiseDiv : " "the Shape of A and B is not same."); } y.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(ElementwiseDiv) .Input("X1", "float32") .Input("X2", "float32") .Input("dY", "float32") .Output("dX1", "float32") .Output("dX2", "float32") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(2); auto dx1 = odc->Output(0); auto dx2 = odc->Output(1); dx1.reshape(dy.shape(), type::float32()); dx2.reshape(dy.shape(), type::float32()); }) .Finish(); class ElementwiseDivGradient : public GradientHelper{ public: ElementwiseDivGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; auto x1 = y.get_children()[0]; auto x2 = y.get_children()[1]; auto one = functional::constant(1, x2.shape()); auto dx1 = functional::div(one, x2); auto dx2 = functional::negative(functional::div(y, x2)); in_grads.push_back(dx1); in_grads.push_back(dx2); return in_grads; } }; REGIST_GRADIENT_HELPER(ElementwiseDiv, ElementwiseDivGradient) REGIST_OP(AddN) .Input("Xs", "float32s") .Output("Y", "float32") .ShapeInference([](OpDesignContext * odc){ auto x1 = odc->Input(0); auto c = odc->Output(0); int num = odc->NumInput(); for(int n = 1; n < num; ++n){ if(x1.size() != odc->Input(n).size()){ throw std::string("AddN : " "the Shape of Inputs is not same."); } } c.reshape(x1.shape(), type::float32()); }) .Finish(); REGIST_OP_GRAD(AddN) .Input("dY", "float32") .Output("dXs", "float32s") .ShapeInference([](OpDesignContext * odc){ auto dy = odc->Input(0); for(int n = 0; n < odc->NumOutput(); ++n){ Tensor d = odc->Output(n); d.reshape(dy.shape(), type::float32()); } }) .Finish(); class AddNGradient : public GradientHelper{ public: AddNGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; Tensor x1 = y.get_children()[0]; Tensor x2 = y.get_children()[1]; Tensor dx1 = functional::mul(x2, dy); Tensor dx2 = functional::mul(x1, dy); in_grads.push_back(dx1); in_grads.push_back(dx2); return in_grads; } }; REGIST_GRADIENT_HELPER(AddN, AddNGradient) class MatrixVectorAddGradient : public GradientHelper{ public: MatrixVectorAddGradient(const OpDesignContext *odc) : GradientHelper(odc){} VecTensor compute_gradient(Tensor y, Tensor dy) override{ VecTensor in_grads; Tensor mat = y.get_children()[0]; Tensor vec = y.get_children()[1]; Tensor one = functional::constant(1, {y.shape()[0], 1}); Tensor dvec = functional::matmul(dy, one, true); in_grads.push_back(dy); in_grads.push_back(dvec); return in_grads; } }; REGIST_GRADIENT_HELPER(MatrixVectorAdd, MatrixVectorAddGradient) template <> Tensor Add<double>(Tensor a, double b){ Tensor y; throw std::string("Tensor add op with Scalar Value is not support."); return y; } template <> Tensor Sub<double>(Tensor a, double b){ Tensor y; throw std::string("Tensor sub op with scalar value is not support."); return y; } template <> Tensor Mul<double>(Tensor a, double b){ Tensor y; throw std::string("Tensor mul op with Scalar Value is not support."); return y; } template <> Tensor Div<double>(Tensor a, double b){ Tensor y; throw std::string("Tensor div op with Scalar Value is not support."); return y; } Tensor negative(Tensor x){ OpAlgoContext cxt("Negative"); Tensor y = create_variable(x.shape()); auto x_shape = x.shape(); y.add_child(x); Tensor::AssignOpFunctor(y, cxt); return y; } Tensor add(Tensor x1, Tensor x2){ Tensor y; auto x1_shape = x1.shape(); auto x2_shape = x2.shape(); auto max_dim = std::max(x1_shape.size(), x2_shape.size()); auto min_dim = std::min(x1_shape.size(), x2_shape.size()); std::vector<int> max_shape, min_shape; if(max_dim == x1_shape.size()){ max_shape = x1_shape; min_shape = x2_shape; } else{ max_shape = x2_shape; min_shape = x1_shape; } y = functional::create_variable(max_shape); y.add_child(x1); y.add_child(x2); if(max_dim == 4 && min_dim == 1){ if(max_shape[1] == min_shape[0]){ OpAlgoContext cxt("BatchedMatrixVectorAdd"); Tensor::AssignOpFunctor(y, cxt); } else{ std::string err = "Can not add with "; err += std::to_string(max_dim) + "d"; err += " and "; err += std::to_string(min_dim) + "d"; throw err; } } else if(max_dim == 2 && min_dim == 1){ if(max_shape[1] == min_shape[0]){ OpAlgoContext cxt("MatrixVectorAdd"); Tensor::AssignOpFunctor(y, cxt); } else{ std::string err = "Can not add with "; err += std::to_string(max_dim) + "d"; err += " and "; err += std::to_string(min_dim) + "d"; throw err; } } else if(max_dim == min_dim){ OpAlgoContext cxt("ElementwiseAdd"); Tensor::AssignOpFunctor(y, cxt); } return y; } Tensor sub(Tensor x1, Tensor x2){ Tensor y = functional::create_variable(x1.shape()); OpAlgoContext cxt("ElementwiseSub"); y.add_child(x1); y.add_child(x2); Tensor::AssignOpFunctor(y, cxt); return y; } Tensor mul(Tensor x1, Tensor x2){ Tensor y = functional::create_variable(x1.shape()); OpAlgoContext cxt("ElementwiseMul"); y.add_child(x1); y.add_child(x2); Tensor::AssignOpFunctor(y, cxt); return y; } Tensor div(Tensor x1, Tensor x2){ Tensor y = functional::create_variable(x1.shape()); OpAlgoContext cxt("ElementwiseDiv"); y.add_child(x1); y.add_child(x2); Tensor::AssignOpFunctor(y, cxt); return y; } Tensor add_n(std::vector<Tensor> xs){ if(xs.size() >= 2){ Tensor y = functional::create_variable(xs[0].shape()); OpAlgoContext cxt("AddN"); for(auto &x : xs){ y.add_child(x); } Tensor::AssignOpFunctor(y, cxt); return y; } else if(xs.size() == 1){ return xs[0]; } else{ throw std::string("functional::Add(std::vector<Tensor>) Input Size 0"); } } } // end namespace functional #define DEFINE_BASIC_ARITHMETIC_TENSOR_EXPR(OpName, Expr) \ template <> \ Tensor operator Expr<Tensor>(Tensor a, Tensor b){ \ return functional::OpName(a, b); \ } DEFINE_BASIC_ARITHMETIC_TENSOR_EXPR(add, +) //DEFINE_BASIC_ARITHMETIC_TENSOR_EXPR(sub, -) DEFINE_BASIC_ARITHMETIC_TENSOR_EXPR(mul, *) //DEFINE_BASIC_ARITHMETIC_TENSOR_EXPR(div, /) } // end namespace mlfe <|endoftext|>
<commit_before>#ifndef GNR_CALLBACK_HPP # define GNR_CALLBACK_HPP # pragma once #include <cassert> // std::size_t #include <cstddef> #include <tuple> #include <functional> #include <type_traits> #include <utility> namespace gnr { namespace detail { namespace callback { constexpr auto default_noexcept = #if defined(__cpp_exceptions) && __cpp_exceptions false; #else true; #endif // __cpp_exceptions constexpr auto default_size = 4 * sizeof(void*); template <typename> struct signature { }; // template <typename> struct class_ref; // template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...)> { using type = C&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const> { using type = C const&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const volatile> { using type = C const volatile&; }; // template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) &> { using type = C&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const &> { using type = C const&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const volatile &> { using type = C const volatile&; }; // template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) &&> { using type = C&&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const &&> { using type = C const&&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const volatile &&> { using type = C const volatile&&; }; template <typename F> using class_ref_t = typename class_ref<F>::type; // template <typename> struct remove_cv_seq; // template <typename R, typename ...A> struct remove_cv_seq<R(A...)> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) volatile> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const volatile> { using type = R(A...); }; // template <typename R, typename ...A> struct remove_cv_seq<R(A...) &> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const &> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) volatile &> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const volatile &> { using type = R(A...); }; // template <typename R, typename ...A> struct remove_cv_seq<R(A...) &&> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const &&> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) volatile &&> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const volatile &&> { using type = R(A...); }; template <typename F> constexpr inline auto extract_signature(F* const) noexcept { return signature<typename remove_cv_seq<F>::type>(); } template <typename C, typename F> constexpr inline auto extract_signature(F C::* const) noexcept { return signature<typename remove_cv_seq<F>::type>(); } template <typename F> constexpr inline auto extract_signature(F const&) noexcept -> decltype(&F::operator(), extract_signature(&F::operator())) { return extract_signature(&F::operator()); } } } template <std::size_t N = detail::callback::default_size, bool NE = detail::callback::default_noexcept > class callback { using typeid_t = void(*)(); template <typename T> static typeid_t type_id() noexcept { return typeid_t(type_id<T>); } void (*f_)(void*, void const*, void*) noexcept(NE) {}; std::aligned_storage_t<N> store_; #ifndef NDEBUG typeid_t type_id_; #endif // NDEBUG template <typename F, typename R, typename ...A> static std::enable_if_t< !std::is_member_function_pointer<F>{} && !std::is_void<R>{} > invoker(void* const store, void const* const v, void* const r) noexcept( noexcept(std::apply(*static_cast<F*>(store), *static_cast<std::tuple<A...> const*>(v) ) ) ) { *static_cast<R*>(r) = std::apply(*static_cast<F*>(store), *static_cast<std::tuple<A...> const*>(v) ); } template <typename F, typename R, typename ...A> static std::enable_if_t< !std::is_member_function_pointer<F>{} && std::is_void<R>{} > invoker(void* const store, void const* const v, void*) noexcept( noexcept(std::apply(*static_cast<F*>(store), *static_cast<std::tuple<A...> const*>(v) ) ) ) { std::apply(*static_cast<F*>(store), *static_cast<std::tuple<A...> const*>(v) ); } template <typename F, typename R, typename ...A> static std::enable_if_t< std::is_member_function_pointer<F>{} && !std::is_void<R>{} > invoker(void* const store, void const* const v, void* const r) noexcept( noexcept(std::apply( *static_cast<F*>(store), *static_cast< std::tuple<detail::callback::class_ref_t<F>, A...> const* >(v) ) ) ) { *static_cast<R*>(r) = std::apply(*static_cast<F*>(store), *static_cast< std::tuple<detail::callback::class_ref_t<F>, A...> const* >(v) ); } template <typename F, typename R, typename ...A> static std::enable_if_t< std::is_member_function_pointer<F>{} && std::is_void<R>{} > invoker(void* const store, void const* const v, void*) noexcept( noexcept(std::apply( *static_cast<F*>(store), *static_cast< std::tuple<detail::callback::class_ref_t<F>, A...> const* >(v) ) ) ) { std::apply(*static_cast<F*>(store), *static_cast< std::tuple<detail::callback::class_ref_t<F>, A...> const* >(v) ); } template <typename F, typename R, typename ...A> std::enable_if_t<!std::is_member_function_pointer<F>{}> assign(detail::callback::signature<R(A...)>) noexcept { f_ = invoker<F, R, A...>; #ifndef NDEBUG type_id_ = type_id<std::tuple<A...>>(); #endif // NDEBUG } template <typename F, typename R, typename ...A> std::enable_if_t<std::is_member_function_pointer<F>{}> assign(detail::callback::signature<R(A...)>) noexcept { f_ = invoker<F, R, A...>; #ifndef NDEBUG type_id_ = type_id<std::tuple<detail::callback::class_ref_t<F>, A...>>(); #endif // NDEBUG } template <std::size_t M> friend bool operator==(callback<M> const&, std::nullptr_t) noexcept; template<std::size_t M> friend bool operator==(std::nullptr_t, callback<M> const&) noexcept; template<std::size_t M> friend bool operator!=(callback<M> const&, std::nullptr_t) noexcept; template<std::size_t M> friend bool operator!=(std::nullptr_t, callback<M> const&) noexcept; public: enum : std::size_t { size = N }; public: template <typename T> struct arg_type { using type = std::decay_t<T>; }; template <typename T> struct arg_type<std::reference_wrapper<T> > { using type = T&; }; template <typename T> using arg_type_t = typename arg_type<T>::type; callback() = default; callback(callback const&) = default; callback(callback&&) = default; template <typename F, typename = std::enable_if_t<!std::is_same<std::decay_t<F>, callback>{}> > callback(F&& f) noexcept { assign(std::forward<F>(f)); } callback& operator=(callback const&) = default; callback& operator=(callback&&) = default; template <typename F, typename = std::enable_if_t<!std::is_same<std::decay_t<F>, callback>{}> > callback& operator=(F&& f) noexcept { assign(std::forward<F>(f)); return *this; } explicit operator bool() const noexcept { return f_; } template <typename R, typename ...A> std::enable_if_t<!std::is_void<R>{}, R> invoke(A... args) const noexcept( noexcept(f_(const_cast<void*>(static_cast<void const*>(&store_)), {}, {} ) ) ) { //assert(f_); R r; auto const a(std::tuple<arg_type_t<A>...>{std::forward<A>(args)...}); f_(const_cast<void*>(static_cast<void const*>(&store_)), &a, &r); return r; } template <typename R = void, typename ...A> std::enable_if_t<std::is_void<R>{}, R> invoke(A... args) const noexcept( noexcept(f_(const_cast<void*>(static_cast<void const*>(&store_)), {}, {} ) ) ) { //assert(f_); auto const a(std::tuple<arg_type_t<A>...>{std::forward<A>(args)...}); f_(const_cast<void*>(static_cast<void const*>(&store_)), &a, {}); } template <typename R, typename ...A> std::enable_if_t<!std::is_void<R>{}, R> operator()(A&&... args) const noexcept( noexcept(std::declval<callback>().template invoke<R>( std::forward<A>(args)... ) ) ) { return invoke<R>(std::forward<A>(args)...); } template <typename R = void, typename ...A> std::enable_if_t<std::is_void<R>{}, R> operator()(A&&... args) const noexcept( noexcept(std::declval<callback>().template invoke<R>( std::forward<A>(args)... ) ) ) { invoke<R>(std::forward<A>(args)...); } template <typename R, typename ...A> std::enable_if_t<!std::is_void<R>{}, R> apply(std::tuple<A...> const& t) const noexcept( noexcept(f_(const_cast<void*>(static_cast<void const*>(&store_)), {}, {} ) ) ) { //assert(f_); R r; f_(const_cast<void*>(static_cast<void const*>(&store_)), &t, &r); return r; } template <typename R = void, typename ...A> std::enable_if_t<std::is_void<R>{}, R> apply(std::tuple<A...> const& t) const noexcept( noexcept(f_(const_cast<void*>(static_cast<void const*>(&store_)), {}, {} ) ) ) { //assert(f_); f_(const_cast<void*>(static_cast<void const*>(&store_)), &t, {}); } void assign(std::nullptr_t) noexcept { reset(); } template <typename F> void assign(F&& f) noexcept { using functor_type = std::decay_t<F>; static_assert(sizeof(functor_type) <= sizeof(store_), "functor too large"); static_assert(std::is_trivially_copyable<functor_type>{}, "functor not trivially copyable"); ::new (static_cast<void*>(&store_)) functor_type(std::forward<F>(f)); assign<F>(detail::callback::extract_signature(std::forward<F>(f))); } void reset() noexcept { f_ = {}; } void swap(callback& other) noexcept { std::swap(*this, other); } void swap(callback&& other) noexcept { std::swap(*this, std::move(other)); } template <typename T> auto target() noexcept { return reinterpret_cast<T*>(&store_); } template <typename T> auto target() const noexcept { return reinterpret_cast<T const*>(&store_); } }; template <std::size_t N> bool operator==(callback<N> const& f, std::nullptr_t const) noexcept { return nullptr == f.stub_ ; } template<std::size_t N> bool operator==(std::nullptr_t, callback<N> const& f) noexcept { return nullptr == f.stub_; } template<std::size_t N> bool operator!=(callback<N> const& f, std::nullptr_t const) noexcept { return !operator==(nullptr, f); } template<std::size_t N> bool operator!=(std::nullptr_t, callback<N> const& f) noexcept { return !operator==(nullptr, f); } } #endif // GNR_CALLBACK_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_CALLBACK_HPP # define GNR_CALLBACK_HPP # pragma once #include <cassert> // std::size_t #include <cstddef> #include <tuple> #include <functional> #include <type_traits> #include <utility> namespace gnr { namespace detail { namespace callback { constexpr auto default_noexcept = #if defined(__cpp_exceptions) && __cpp_exceptions false; #else true; #endif // __cpp_exceptions constexpr auto default_size = 4 * sizeof(void*); template <typename> struct signature { }; // template <typename> struct class_ref; // template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...)> { using type = C&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const> { using type = C const&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const volatile> { using type = C const volatile&; }; // template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) &> { using type = C&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const &> { using type = C const&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const volatile &> { using type = C const volatile&; }; // template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) &&> { using type = C&&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const &&> { using type = C const&&; }; template <typename R, typename C, typename ...A> struct class_ref<R (C::*)(A...) const volatile &&> { using type = C const volatile&&; }; template <typename F> using class_ref_t = typename class_ref<F>::type; // template <typename> struct remove_cv_seq; // template <typename R, typename ...A> struct remove_cv_seq<R(A...)> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) volatile> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const volatile> { using type = R(A...); }; // template <typename R, typename ...A> struct remove_cv_seq<R(A...) &> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const &> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) volatile &> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const volatile &> { using type = R(A...); }; // template <typename R, typename ...A> struct remove_cv_seq<R(A...) &&> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const &&> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) volatile &&> { using type = R(A...); }; template <typename R, typename ...A> struct remove_cv_seq<R(A...) const volatile &&> { using type = R(A...); }; template <typename F> constexpr inline auto extract_signature(F* const) noexcept { return signature<typename remove_cv_seq<F>::type>(); } template <typename C, typename F> constexpr inline auto extract_signature(F C::* const) noexcept { return signature<typename remove_cv_seq<F>::type>(); } template <typename F> constexpr inline auto extract_signature(F const&) noexcept -> decltype(&F::operator(), extract_signature(&F::operator())) { return extract_signature(&F::operator()); } } } template <std::size_t N = detail::callback::default_size, bool NE = detail::callback::default_noexcept > class callback { using typeid_t = void(*)(); template <typename T> static typeid_t type_id() noexcept { return typeid_t(type_id<T>); } void (*f_)(void*, void const*, void*) noexcept(NE) {}; std::aligned_storage_t<N> store_; #ifndef NDEBUG typeid_t type_id_; #endif // NDEBUG template <typename F, typename R, typename ...A> static std::enable_if_t< !std::is_member_function_pointer<F>{} && !std::is_void<R>{} > invoker(void* const store, void const* const v, void* const r) noexcept( noexcept(std::apply(*static_cast<F*>(store), *static_cast<std::tuple<A...> const*>(v) ) ) ) { *static_cast<R*>(r) = std::apply(*static_cast<F*>(store), *static_cast<std::tuple<A...> const*>(v) ); } template <typename F, typename R, typename ...A> static std::enable_if_t< !std::is_member_function_pointer<F>{} && std::is_void<R>{} > invoker(void* const store, void const* const v, void*) noexcept( noexcept(std::apply(*static_cast<F*>(store), *static_cast<std::tuple<A...> const*>(v) ) ) ) { std::apply(*static_cast<F*>(store), *static_cast<std::tuple<A...> const*>(v) ); } template <typename F, typename R, typename ...A> static std::enable_if_t< std::is_member_function_pointer<F>{} && !std::is_void<R>{} > invoker(void* const store, void const* const v, void* const r) noexcept( noexcept(std::apply( *static_cast<F*>(store), *static_cast< std::tuple<detail::callback::class_ref_t<F>, A...> const* >(v) ) ) ) { *static_cast<R*>(r) = std::apply(*static_cast<F*>(store), *static_cast< std::tuple<detail::callback::class_ref_t<F>, A...> const* >(v) ); } template <typename F, typename R, typename ...A> static std::enable_if_t< std::is_member_function_pointer<F>{} && std::is_void<R>{} > invoker(void* const store, void const* const v, void*) noexcept( noexcept(std::apply( *static_cast<F*>(store), *static_cast< std::tuple<detail::callback::class_ref_t<F>, A...> const* >(v) ) ) ) { std::apply(*static_cast<F*>(store), *static_cast< std::tuple<detail::callback::class_ref_t<F>, A...> const* >(v) ); } template <typename F, typename R, typename ...A> std::enable_if_t<!std::is_member_function_pointer<F>{}> assign(detail::callback::signature<R(A...)>) noexcept { f_ = invoker<F, R, A...>; #ifndef NDEBUG type_id_ = type_id<std::tuple<A...>>(); #endif // NDEBUG } template <typename F, typename R, typename ...A> std::enable_if_t<std::is_member_function_pointer<F>{}> assign(detail::callback::signature<R(A...)>) noexcept { f_ = invoker<F, R, A...>; #ifndef NDEBUG type_id_ = type_id<std::tuple<detail::callback::class_ref_t<F>, A...>>(); #endif // NDEBUG } template <std::size_t M> friend bool operator==(callback<M> const&, std::nullptr_t) noexcept; template<std::size_t M> friend bool operator==(std::nullptr_t, callback<M> const&) noexcept; template<std::size_t M> friend bool operator!=(callback<M> const&, std::nullptr_t) noexcept; template<std::size_t M> friend bool operator!=(std::nullptr_t, callback<M> const&) noexcept; public: enum : std::size_t { size = N }; public: template <typename T> struct arg_type { using type = std::decay_t<T>; }; template <typename T> struct arg_type<std::reference_wrapper<T> > { using type = T&; }; template <typename T> using arg_type_t = typename arg_type<T>::type; callback() = default; callback(callback const&) = default; callback(callback&&) = default; template <typename F, typename = std::enable_if_t<!std::is_same<std::decay_t<F>, callback>{}> > callback(F&& f) noexcept { assign(std::forward<F>(f)); } callback& operator=(callback const&) = default; callback& operator=(callback&&) = default; template <typename F, typename = std::enable_if_t<!std::is_same<std::decay_t<F>, callback>{}> > callback& operator=(F&& f) noexcept { assign(std::forward<F>(f)); return *this; } explicit operator bool() const noexcept { return f_; } template <typename R, typename ...A> std::enable_if_t<!std::is_void<R>{}, R> invoke(A... args) const noexcept( noexcept(f_(const_cast<void*>(static_cast<void const*>(&store_)), {}, {} ) ) ) { //assert(f_); R r; auto const a(std::tuple<arg_type_t<A>...>{std::forward<A>(args)...}); f_(const_cast<void*>(static_cast<void const*>(&store_)), &a, &r); return r; } template <typename R = void, typename ...A> std::enable_if_t<std::is_void<R>{}, R> invoke(A... args) const noexcept( noexcept(f_(const_cast<void*>(static_cast<void const*>(&store_)), {}, {} ) ) ) { //assert(f_); auto const a(std::tuple<arg_type_t<A>...>{std::forward<A>(args)...}); f_(const_cast<void*>(static_cast<void const*>(&store_)), &a, {}); } template <typename R, typename ...A> std::enable_if_t<!std::is_void<R>{}, R> operator()(A&&... args) const noexcept( noexcept(std::declval<callback>().template invoke<R>( std::forward<A>(args)... ) ) ) { return invoke<R>(std::forward<A>(args)...); } template <typename R = void, typename ...A> std::enable_if_t<std::is_void<R>{}, R> operator()(A&&... args) const noexcept( noexcept(std::declval<callback>().template invoke<R>( std::forward<A>(args)... ) ) ) { invoke<R>(std::forward<A>(args)...); } void assign(std::nullptr_t) noexcept { reset(); } template <typename F> void assign(F&& f) noexcept { using functor_type = std::decay_t<F>; static_assert(sizeof(functor_type) <= sizeof(store_), "functor too large"); static_assert(std::is_trivially_copyable<functor_type>{}, "functor not trivially copyable"); ::new (static_cast<void*>(&store_)) functor_type(std::forward<F>(f)); assign<F>(detail::callback::extract_signature(std::forward<F>(f))); } void reset() noexcept { f_ = {}; } void swap(callback& other) noexcept { std::swap(*this, other); } void swap(callback&& other) noexcept { std::swap(*this, std::move(other)); } template <typename T> auto target() noexcept { return reinterpret_cast<T*>(&store_); } template <typename T> auto target() const noexcept { return reinterpret_cast<T const*>(&store_); } }; template <std::size_t N> bool operator==(callback<N> const& f, std::nullptr_t const) noexcept { return nullptr == f.stub_ ; } template<std::size_t N> bool operator==(std::nullptr_t, callback<N> const& f) noexcept { return nullptr == f.stub_; } template<std::size_t N> bool operator!=(callback<N> const& f, std::nullptr_t const) noexcept { return !operator==(nullptr, f); } template<std::size_t N> bool operator!=(std::nullptr_t, callback<N> const& f) noexcept { return !operator==(nullptr, f); } } #endif // GNR_CALLBACK_HPP <|endoftext|>
<commit_before>/*********************************************************************** created: Wed, 8th Feb 2012 author: Lukas E Meindl (based on code by Paul D Turner) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/OpenGL/RenderTarget.h" #include "CEGUI/RenderQueue.h" #include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h" #include "CEGUI/RendererModules/OpenGL/GlmPimpl.h" #include <cmath> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// template <typename T> const double OpenGLRenderTarget<T>::d_yfov_tan = 0.267949192431123; //----------------------------------------------------------------------------// template <typename T> OpenGLRenderTarget<T>::OpenGLRenderTarget(OpenGLRendererBase& owner) : d_owner(owner), d_area(0, 0, 0, 0), d_matrix(0), d_matrixValid(false), d_viewDistance(0) { d_matrix = new mat4Pimpl(); } //----------------------------------------------------------------------------// template <typename T> OpenGLRenderTarget<T>::~OpenGLRenderTarget() { delete d_matrix; } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::draw(const GeometryBuffer& buffer) { buffer.draw(); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::draw(const RenderQueue& queue) { queue.draw(); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::setArea(const Rectf& area) { d_area = area; d_matrixValid = false; RenderTargetEventArgs args(this); T::fireEvent(RenderTarget::EventAreaChanged, args); } //----------------------------------------------------------------------------// template <typename T> const Rectf& OpenGLRenderTarget<T>::getArea() const { return d_area; } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::activate() { glViewport(static_cast<GLsizei>(d_area.left()), static_cast<GLsizei>(d_area.top()), static_cast<GLsizei>(d_area.getWidth()), static_cast<GLsizei>(d_area.getHeight())); if (!d_matrixValid) updateMatrix(); d_owner.setViewProjectionMatrix(d_matrix); d_owner.setActiveRenderTarget(this); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::deactivate() { } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff, const Vector2f& p_in, Vector2f& p_out) const { if (!d_matrixValid) updateMatrix(); const OpenGLGeometryBufferBase& gb = static_cast<const OpenGLGeometryBufferBase&>(buff); const GLint vp[4] = { static_cast<GLint>(d_area.left()), static_cast<GLint>(d_area.top()), static_cast<GLint>(d_area.getWidth()), static_cast<GLint>(d_area.getHeight()) }; GLdouble in_x, in_y, in_z = 0.0; glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]); const glm::mat4& projMatrix = d_matrix->d_matrix; const glm::mat4& modelMatrix = gb.getMatrix()->d_matrix; // unproject the ends of the ray glm::vec3 unprojected1; glm::vec3 unprojected2; in_x = vp[2] * 0.5; in_y = vp[3] * 0.5; in_z = -d_viewDistance; unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = p_in.d_x; in_y = vp[3] - p_in.d_y; in_z = 0.0; unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // project points to orientate them with GeometryBuffer plane glm::vec3 projected1; glm::vec3 projected2; glm::vec3 projected3; in_x = 0.0; in_y = 0.0; projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 1.0; in_y = 0.0; projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 0.0; in_y = 1.0; projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // calculate vectors for generating the plane const glm::vec3 pv1 = projected2 - projected1; const glm::vec3 pv2 = projected3 - projected1; // given the vectors, calculate the plane normal const glm::vec3 planeNormal = glm::cross(pv1, pv2); // calculate plane const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal); const double pl_d = - glm::dot(projected1, planeNormalNormalized); // calculate vector of picking ray const glm::vec3 rv = unprojected1 - unprojected2; // calculate intersection of ray and plane const double pn_dot_r1 = glm::dot(unprojected1, planeNormal); const double pn_dot_rv = glm::dot(rv, planeNormal); const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) / pn_dot_rv : 0.0; const double is_x = unprojected1.x - rv.x * tmp1; const double is_y = unprojected1.y - rv.y * tmp1; p_out.d_x = static_cast<float>(is_x); p_out.d_y = static_cast<float>(is_y); p_out = p_in; // CrazyEddie wanted this } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::updateMatrix() const { const float w = d_area.getWidth(); const float h = d_area.getHeight(); // We need to check if width or height are zero and act accordingly to prevent running into issues // with divisions by zero which would lead to undefined values, as well as faulty clipping planes // This is mostly important for avoiding asserts const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f); const float aspect = widthAndHeightNotZero ? w / h : 1.0f; const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f; const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f; d_viewDistance = midx / (aspect * d_yfov_tan); glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance)); glm::vec3 center = glm::vec3(midx, midy, 1); glm::vec3 up = glm::vec3(0, -1, 0); glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0)); // Projection matrix abuse! glm::mat4 viewMatrix = glm::lookAt(eye, center, up); d_matrix->d_matrix = projectionMatrix * viewMatrix; d_matrixValid = true; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>MOD: Fixing what the radian/degree change in GLM 0.9.6 broke in the GL Renderers<commit_after>/*********************************************************************** created: Wed, 8th Feb 2012 author: Lukas E Meindl (based on code by Paul D Turner) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/OpenGL/RenderTarget.h" #include "CEGUI/RenderQueue.h" #include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h" #include "CEGUI/RendererModules/OpenGL/GlmPimpl.h" #include <cmath> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// template <typename T> const double OpenGLRenderTarget<T>::d_yfov_tan = 0.267949192431123; //----------------------------------------------------------------------------// template <typename T> OpenGLRenderTarget<T>::OpenGLRenderTarget(OpenGLRendererBase& owner) : d_owner(owner), d_area(0, 0, 0, 0), d_matrix(0), d_matrixValid(false), d_viewDistance(0) { d_matrix = new mat4Pimpl(); } //----------------------------------------------------------------------------// template <typename T> OpenGLRenderTarget<T>::~OpenGLRenderTarget() { delete d_matrix; } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::draw(const GeometryBuffer& buffer) { buffer.draw(); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::draw(const RenderQueue& queue) { queue.draw(); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::setArea(const Rectf& area) { d_area = area; d_matrixValid = false; RenderTargetEventArgs args(this); T::fireEvent(RenderTarget::EventAreaChanged, args); } //----------------------------------------------------------------------------// template <typename T> const Rectf& OpenGLRenderTarget<T>::getArea() const { return d_area; } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::activate() { glViewport(static_cast<GLsizei>(d_area.left()), static_cast<GLsizei>(d_area.top()), static_cast<GLsizei>(d_area.getWidth()), static_cast<GLsizei>(d_area.getHeight())); if (!d_matrixValid) updateMatrix(); d_owner.setViewProjectionMatrix(d_matrix); d_owner.setActiveRenderTarget(this); } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::deactivate() { } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff, const Vector2f& p_in, Vector2f& p_out) const { if (!d_matrixValid) updateMatrix(); const OpenGLGeometryBufferBase& gb = static_cast<const OpenGLGeometryBufferBase&>(buff); const GLint vp[4] = { static_cast<GLint>(d_area.left()), static_cast<GLint>(d_area.top()), static_cast<GLint>(d_area.getWidth()), static_cast<GLint>(d_area.getHeight()) }; GLdouble in_x, in_y, in_z = 0.0; glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]); const glm::mat4& projMatrix = d_matrix->d_matrix; const glm::mat4& modelMatrix = gb.getMatrix()->d_matrix; // unproject the ends of the ray glm::vec3 unprojected1; glm::vec3 unprojected2; in_x = vp[2] * 0.5; in_y = vp[3] * 0.5; in_z = -d_viewDistance; unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = p_in.d_x; in_y = vp[3] - p_in.d_y; in_z = 0.0; unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // project points to orientate them with GeometryBuffer plane glm::vec3 projected1; glm::vec3 projected2; glm::vec3 projected3; in_x = 0.0; in_y = 0.0; projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 1.0; in_y = 0.0; projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); in_x = 0.0; in_y = 1.0; projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); // calculate vectors for generating the plane const glm::vec3 pv1 = projected2 - projected1; const glm::vec3 pv2 = projected3 - projected1; // given the vectors, calculate the plane normal const glm::vec3 planeNormal = glm::cross(pv1, pv2); // calculate plane const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal); const double pl_d = - glm::dot(projected1, planeNormalNormalized); // calculate vector of picking ray const glm::vec3 rv = unprojected1 - unprojected2; // calculate intersection of ray and plane const double pn_dot_r1 = glm::dot(unprojected1, planeNormal); const double pn_dot_rv = glm::dot(rv, planeNormal); const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) / pn_dot_rv : 0.0; const double is_x = unprojected1.x - rv.x * tmp1; const double is_y = unprojected1.y - rv.y * tmp1; p_out.d_x = static_cast<float>(is_x); p_out.d_y = static_cast<float>(is_y); p_out = p_in; // CrazyEddie wanted this } //----------------------------------------------------------------------------// template <typename T> void OpenGLRenderTarget<T>::updateMatrix() const { const float w = d_area.getWidth(); const float h = d_area.getHeight(); // We need to check if width or height are zero and act accordingly to prevent running into issues // with divisions by zero which would lead to undefined values, as well as faulty clipping planes // This is mostly important for avoiding asserts const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f); const float aspect = widthAndHeightNotZero ? w / h : 1.0f; const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f; const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f; d_viewDistance = midx / (aspect * d_yfov_tan); glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance)); glm::vec3 center = glm::vec3(midx, midy, 1); glm::vec3 up = glm::vec3(0, -1, 0); //Older glm versions use degrees as parameter here by default (Unless radians are forced via GLM_FORCE_RADIANS). Newer versions of glm exlusively use radians. #if (GLM_VERSION_MAJOR == 0 && GLM_VERSION_MINOR <= 9 && GLM_VERSION_PATCH < 6) glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0)); #else glm::mat4 projectionMatrix = glm::perspective(glm::radians(30.f), aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0)); #endif // Projection matrix abuse! glm::mat4 viewMatrix = glm::lookAt(eye, center, up); d_matrix->d_matrix = projectionMatrix * viewMatrix; d_matrixValid = true; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>// 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/audio_manager_base.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/message_loop/message_loop_proxy.h" #include "base/threading/thread.h" #include "build/build_config.h" #include "media/audio/audio_output_dispatcher_impl.h" #include "media/audio/audio_output_proxy.h" #include "media/audio/audio_output_resampler.h" #include "media/audio/audio_util.h" #include "media/audio/fake_audio_input_stream.h" #include "media/audio/fake_audio_output_stream.h" #include "media/base/media_switches.h" namespace media { static const int kStreamCloseDelaySeconds = 5; // Default maximum number of output streams that can be open simultaneously // for all platforms. static const int kDefaultMaxOutputStreams = 16; // Default maximum number of input streams that can be open simultaneously // for all platforms. static const int kDefaultMaxInputStreams = 16; static const int kMaxInputChannels = 2; const char AudioManagerBase::kDefaultDeviceName[] = "Default"; const char AudioManagerBase::kDefaultDeviceId[] = "default"; struct AudioManagerBase::DispatcherParams { DispatcherParams(const AudioParameters& input, const AudioParameters& output, const std::string& device_id) : input_params(input), output_params(output), input_device_id(device_id) {} ~DispatcherParams() {} const AudioParameters input_params; const AudioParameters output_params; const std::string input_device_id; scoped_refptr<AudioOutputDispatcher> dispatcher; private: DISALLOW_COPY_AND_ASSIGN(DispatcherParams); }; class AudioManagerBase::CompareByParams { public: explicit CompareByParams(const DispatcherParams* dispatcher) : dispatcher_(dispatcher) {} bool operator()(DispatcherParams* dispatcher_in) const { // We will reuse the existing dispatcher when: // 1) Unified IO is not used, input_params and output_params of the // existing dispatcher are the same as the requested dispatcher. // 2) Unified IO is used, input_params, output_params and input_device_id // of the existing dispatcher are the same as the request dispatcher. return (dispatcher_->input_params == dispatcher_in->input_params && dispatcher_->output_params == dispatcher_in->output_params && (!dispatcher_->input_params.input_channels() || dispatcher_->input_device_id == dispatcher_in->input_device_id)); } private: const DispatcherParams* dispatcher_; }; AudioManagerBase::AudioManagerBase() : max_num_output_streams_(kDefaultMaxOutputStreams), max_num_input_streams_(kDefaultMaxInputStreams), num_output_streams_(0), num_input_streams_(0), // TODO(dalecurtis): Switch this to an ObserverListThreadSafe, so we don't // block the UI thread when swapping devices. output_listeners_( ObserverList<AudioDeviceListener>::NOTIFY_EXISTING_ONLY), audio_thread_(new base::Thread("AudioThread")) { #if defined(OS_WIN) audio_thread_->init_com_with_mta(true); #elif defined(OS_MACOSX) // CoreAudio calls must occur on the main thread of the process, which in our // case is sadly the browser UI thread. Failure to execute calls on the right // thread leads to crashes and odd behavior. See http://crbug.com/158170. // TODO(dalecurtis): We should require the message loop to be passed in. const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); if (!cmd_line->HasSwitch(switches::kDisableMainThreadAudio) && base::MessageLoopProxy::current().get() && base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_UI)) { message_loop_ = base::MessageLoopProxy::current(); return; } #endif CHECK(audio_thread_->Start()); message_loop_ = audio_thread_->message_loop_proxy(); } AudioManagerBase::~AudioManagerBase() { // The platform specific AudioManager implementation must have already // stopped the audio thread. Otherwise, we may destroy audio streams before // stopping the thread, resulting an unexpected behavior. // This way we make sure activities of the audio streams are all stopped // before we destroy them. CHECK(!audio_thread_.get()); // All the output streams should have been deleted. DCHECK_EQ(0, num_output_streams_); // All the input streams should have been deleted. DCHECK_EQ(0, num_input_streams_); } string16 AudioManagerBase::GetAudioInputDeviceModel() { return string16(); } scoped_refptr<base::MessageLoopProxy> AudioManagerBase::GetMessageLoop() { return message_loop_; } scoped_refptr<base::MessageLoopProxy> AudioManagerBase::GetWorkerLoop() { // Lazily start the worker thread. if (!audio_thread_->IsRunning()) CHECK(audio_thread_->Start()); return audio_thread_->message_loop_proxy(); } AudioOutputStream* AudioManagerBase::MakeAudioOutputStream( const AudioParameters& params, const std::string& input_device_id) { // TODO(miu): Fix ~50 call points across several unit test modules to call // this method on the audio thread, then uncomment the following: // DCHECK(message_loop_->BelongsToCurrentThread()); if (!params.IsValid()) { DLOG(ERROR) << "Audio parameters are invalid"; return NULL; } // Limit the number of audio streams opened. This is to prevent using // excessive resources for a large number of audio streams. More // importantly it prevents instability on certain systems. // See bug: http://crbug.com/30242. if (num_output_streams_ >= max_num_output_streams_) { DLOG(ERROR) << "Number of opened output audio streams " << num_output_streams_ << " exceed the max allowed number " << max_num_output_streams_; return NULL; } AudioOutputStream* stream; switch (params.format()) { case AudioParameters::AUDIO_PCM_LINEAR: stream = MakeLinearOutputStream(params); break; case AudioParameters::AUDIO_PCM_LOW_LATENCY: stream = MakeLowLatencyOutputStream(params, input_device_id); break; case AudioParameters::AUDIO_FAKE: stream = FakeAudioOutputStream::MakeFakeStream(this, params); break; default: stream = NULL; break; } if (stream) { ++num_output_streams_; } return stream; } AudioInputStream* AudioManagerBase::MakeAudioInputStream( const AudioParameters& params, const std::string& device_id) { // TODO(miu): Fix ~20 call points across several unit test modules to call // this method on the audio thread, then uncomment the following: // DCHECK(message_loop_->BelongsToCurrentThread()); if (!params.IsValid() || (params.channels() > kMaxInputChannels) || device_id.empty()) { DLOG(ERROR) << "Audio parameters are invalid for device " << device_id; return NULL; } if (num_input_streams_ >= max_num_input_streams_) { DLOG(ERROR) << "Number of opened input audio streams " << num_input_streams_ << " exceed the max allowed number " << max_num_input_streams_; return NULL; } AudioInputStream* stream; switch (params.format()) { case AudioParameters::AUDIO_PCM_LINEAR: stream = MakeLinearInputStream(params, device_id); break; case AudioParameters::AUDIO_PCM_LOW_LATENCY: stream = MakeLowLatencyInputStream(params, device_id); break; case AudioParameters::AUDIO_FAKE: stream = FakeAudioInputStream::MakeFakeStream(this, params); break; default: stream = NULL; break; } if (stream) { ++num_input_streams_; } return stream; } AudioOutputStream* AudioManagerBase::MakeAudioOutputStreamProxy( const AudioParameters& params, const std::string& input_device_id) { #if defined(OS_IOS) // IOS implements audio input only. NOTIMPLEMENTED(); return NULL; #else DCHECK(message_loop_->BelongsToCurrentThread()); // If we're not using AudioOutputResampler our output parameters are the same // as our input parameters. AudioParameters output_params = params; if (params.format() == AudioParameters::AUDIO_PCM_LOW_LATENCY) { output_params = GetPreferredOutputStreamParameters(params); // Ensure we only pass on valid output parameters. if (!output_params.IsValid()) { // We've received invalid audio output parameters, so switch to a mock // output device based on the input parameters. This may happen if the OS // provided us junk values for the hardware configuration. LOG(ERROR) << "Invalid audio output parameters received; using fake " << "audio path. Channels: " << output_params.channels() << ", " << "Sample Rate: " << output_params.sample_rate() << ", " << "Bits Per Sample: " << output_params.bits_per_sample() << ", Frames Per Buffer: " << output_params.frames_per_buffer(); // Tell the AudioManager to create a fake output device. output_params = AudioParameters( AudioParameters::AUDIO_FAKE, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } } DispatcherParams* dispatcher_params = new DispatcherParams(params, output_params, input_device_id); AudioOutputDispatchers::iterator it = std::find_if(output_dispatchers_.begin(), output_dispatchers_.end(), CompareByParams(dispatcher_params)); if (it != output_dispatchers_.end()) { delete dispatcher_params; return new AudioOutputProxy((*it)->dispatcher.get()); } const base::TimeDelta kCloseDelay = base::TimeDelta::FromSeconds(kStreamCloseDelaySeconds); if (output_params.format() != AudioParameters::AUDIO_FAKE) { scoped_refptr<AudioOutputDispatcher> dispatcher = new AudioOutputResampler(this, params, output_params, input_device_id, kCloseDelay); dispatcher_params->dispatcher = dispatcher; return new AudioOutputProxy(dispatcher.get()); } scoped_refptr<AudioOutputDispatcher> dispatcher = new AudioOutputDispatcherImpl(this, output_params, input_device_id, kCloseDelay); dispatcher_params->dispatcher = dispatcher; output_dispatchers_.push_back(dispatcher_params); return new AudioOutputProxy(dispatcher.get()); #endif // defined(OS_IOS) } void AudioManagerBase::ShowAudioInputSettings() { } void AudioManagerBase::GetAudioInputDeviceNames( media::AudioDeviceNames* device_names) { } void AudioManagerBase::ReleaseOutputStream(AudioOutputStream* stream) { DCHECK(stream); // TODO(xians) : Have a clearer destruction path for the AudioOutputStream. // For example, pass the ownership to AudioManager so it can delete the // streams. --num_output_streams_; delete stream; } void AudioManagerBase::ReleaseInputStream(AudioInputStream* stream) { DCHECK(stream); // TODO(xians) : Have a clearer destruction path for the AudioInputStream. --num_input_streams_; delete stream; } void AudioManagerBase::Shutdown() { // To avoid running into deadlocks while we stop the thread, shut it down // via a local variable while not holding the audio thread lock. scoped_ptr<base::Thread> audio_thread; { base::AutoLock lock(audio_thread_lock_); audio_thread_.swap(audio_thread); } if (!audio_thread) return; // Only true when we're sharing the UI message loop with the browser. The UI // loop is no longer running at this time and browser destruction is imminent. if (message_loop_->BelongsToCurrentThread()) { ShutdownOnAudioThread(); } else { message_loop_->PostTask(FROM_HERE, base::Bind( &AudioManagerBase::ShutdownOnAudioThread, base::Unretained(this))); } // Stop() will wait for any posted messages to be processed first. audio_thread->Stop(); } void AudioManagerBase::ShutdownOnAudioThread() { // IOS implements audio input only. #if defined(OS_IOS) return; #else // This should always be running on the audio thread, but since we've cleared // the audio_thread_ member pointer when we get here, we can't verify exactly // what thread we're running on. The method is not public though and only // called from one place, so we'll leave it at that. AudioOutputDispatchers::iterator it = output_dispatchers_.begin(); for (; it != output_dispatchers_.end(); ++it) { scoped_refptr<AudioOutputDispatcher>& dispatcher = (*it)->dispatcher; if (dispatcher.get()) { dispatcher->Shutdown(); // All AudioOutputProxies must have been freed before Shutdown is called. // If they still exist, things will go bad. They have direct pointers to // both physical audio stream objects that belong to the dispatcher as // well as the message loop of the audio thread that will soon go away. // So, better crash now than later. DCHECK(dispatcher->HasOneRef()) << "AudioOutputProxies are still alive"; dispatcher = NULL; } } output_dispatchers_.clear(); #endif // defined(OS_IOS) } void AudioManagerBase::AddOutputDeviceChangeListener( AudioDeviceListener* listener) { DCHECK(message_loop_->BelongsToCurrentThread()); output_listeners_.AddObserver(listener); } void AudioManagerBase::RemoveOutputDeviceChangeListener( AudioDeviceListener* listener) { DCHECK(message_loop_->BelongsToCurrentThread()); output_listeners_.RemoveObserver(listener); } void AudioManagerBase::NotifyAllOutputDeviceChangeListeners() { DCHECK(message_loop_->BelongsToCurrentThread()); DVLOG(1) << "Firing OnDeviceChange() notifications."; FOR_EACH_OBSERVER(AudioDeviceListener, output_listeners_, OnDeviceChange()); } AudioParameters AudioManagerBase::GetDefaultOutputStreamParameters() { return GetPreferredOutputStreamParameters(AudioParameters()); } AudioParameters AudioManagerBase::GetInputStreamParameters( const std::string& device_id) { NOTREACHED(); return AudioParameters(); } } // namespace media <commit_msg>Fixed the leak in MakeAudioOutputStreamProxy().<commit_after>// 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/audio_manager_base.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/message_loop/message_loop_proxy.h" #include "base/threading/thread.h" #include "build/build_config.h" #include "media/audio/audio_output_dispatcher_impl.h" #include "media/audio/audio_output_proxy.h" #include "media/audio/audio_output_resampler.h" #include "media/audio/audio_util.h" #include "media/audio/fake_audio_input_stream.h" #include "media/audio/fake_audio_output_stream.h" #include "media/base/media_switches.h" namespace media { static const int kStreamCloseDelaySeconds = 5; // Default maximum number of output streams that can be open simultaneously // for all platforms. static const int kDefaultMaxOutputStreams = 16; // Default maximum number of input streams that can be open simultaneously // for all platforms. static const int kDefaultMaxInputStreams = 16; static const int kMaxInputChannels = 2; const char AudioManagerBase::kDefaultDeviceName[] = "Default"; const char AudioManagerBase::kDefaultDeviceId[] = "default"; struct AudioManagerBase::DispatcherParams { DispatcherParams(const AudioParameters& input, const AudioParameters& output, const std::string& device_id) : input_params(input), output_params(output), input_device_id(device_id) {} ~DispatcherParams() {} const AudioParameters input_params; const AudioParameters output_params; const std::string input_device_id; scoped_refptr<AudioOutputDispatcher> dispatcher; private: DISALLOW_COPY_AND_ASSIGN(DispatcherParams); }; class AudioManagerBase::CompareByParams { public: explicit CompareByParams(const DispatcherParams* dispatcher) : dispatcher_(dispatcher) {} bool operator()(DispatcherParams* dispatcher_in) const { // We will reuse the existing dispatcher when: // 1) Unified IO is not used, input_params and output_params of the // existing dispatcher are the same as the requested dispatcher. // 2) Unified IO is used, input_params, output_params and input_device_id // of the existing dispatcher are the same as the request dispatcher. return (dispatcher_->input_params == dispatcher_in->input_params && dispatcher_->output_params == dispatcher_in->output_params && (!dispatcher_->input_params.input_channels() || dispatcher_->input_device_id == dispatcher_in->input_device_id)); } private: const DispatcherParams* dispatcher_; }; AudioManagerBase::AudioManagerBase() : max_num_output_streams_(kDefaultMaxOutputStreams), max_num_input_streams_(kDefaultMaxInputStreams), num_output_streams_(0), num_input_streams_(0), // TODO(dalecurtis): Switch this to an ObserverListThreadSafe, so we don't // block the UI thread when swapping devices. output_listeners_( ObserverList<AudioDeviceListener>::NOTIFY_EXISTING_ONLY), audio_thread_(new base::Thread("AudioThread")) { #if defined(OS_WIN) audio_thread_->init_com_with_mta(true); #elif defined(OS_MACOSX) // CoreAudio calls must occur on the main thread of the process, which in our // case is sadly the browser UI thread. Failure to execute calls on the right // thread leads to crashes and odd behavior. See http://crbug.com/158170. // TODO(dalecurtis): We should require the message loop to be passed in. const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); if (!cmd_line->HasSwitch(switches::kDisableMainThreadAudio) && base::MessageLoopProxy::current().get() && base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_UI)) { message_loop_ = base::MessageLoopProxy::current(); return; } #endif CHECK(audio_thread_->Start()); message_loop_ = audio_thread_->message_loop_proxy(); } AudioManagerBase::~AudioManagerBase() { // The platform specific AudioManager implementation must have already // stopped the audio thread. Otherwise, we may destroy audio streams before // stopping the thread, resulting an unexpected behavior. // This way we make sure activities of the audio streams are all stopped // before we destroy them. CHECK(!audio_thread_.get()); // All the output streams should have been deleted. DCHECK_EQ(0, num_output_streams_); // All the input streams should have been deleted. DCHECK_EQ(0, num_input_streams_); } string16 AudioManagerBase::GetAudioInputDeviceModel() { return string16(); } scoped_refptr<base::MessageLoopProxy> AudioManagerBase::GetMessageLoop() { return message_loop_; } scoped_refptr<base::MessageLoopProxy> AudioManagerBase::GetWorkerLoop() { // Lazily start the worker thread. if (!audio_thread_->IsRunning()) CHECK(audio_thread_->Start()); return audio_thread_->message_loop_proxy(); } AudioOutputStream* AudioManagerBase::MakeAudioOutputStream( const AudioParameters& params, const std::string& input_device_id) { // TODO(miu): Fix ~50 call points across several unit test modules to call // this method on the audio thread, then uncomment the following: // DCHECK(message_loop_->BelongsToCurrentThread()); if (!params.IsValid()) { DLOG(ERROR) << "Audio parameters are invalid"; return NULL; } // Limit the number of audio streams opened. This is to prevent using // excessive resources for a large number of audio streams. More // importantly it prevents instability on certain systems. // See bug: http://crbug.com/30242. if (num_output_streams_ >= max_num_output_streams_) { DLOG(ERROR) << "Number of opened output audio streams " << num_output_streams_ << " exceed the max allowed number " << max_num_output_streams_; return NULL; } AudioOutputStream* stream; switch (params.format()) { case AudioParameters::AUDIO_PCM_LINEAR: stream = MakeLinearOutputStream(params); break; case AudioParameters::AUDIO_PCM_LOW_LATENCY: stream = MakeLowLatencyOutputStream(params, input_device_id); break; case AudioParameters::AUDIO_FAKE: stream = FakeAudioOutputStream::MakeFakeStream(this, params); break; default: stream = NULL; break; } if (stream) { ++num_output_streams_; } return stream; } AudioInputStream* AudioManagerBase::MakeAudioInputStream( const AudioParameters& params, const std::string& device_id) { // TODO(miu): Fix ~20 call points across several unit test modules to call // this method on the audio thread, then uncomment the following: // DCHECK(message_loop_->BelongsToCurrentThread()); if (!params.IsValid() || (params.channels() > kMaxInputChannels) || device_id.empty()) { DLOG(ERROR) << "Audio parameters are invalid for device " << device_id; return NULL; } if (num_input_streams_ >= max_num_input_streams_) { DLOG(ERROR) << "Number of opened input audio streams " << num_input_streams_ << " exceed the max allowed number " << max_num_input_streams_; return NULL; } AudioInputStream* stream; switch (params.format()) { case AudioParameters::AUDIO_PCM_LINEAR: stream = MakeLinearInputStream(params, device_id); break; case AudioParameters::AUDIO_PCM_LOW_LATENCY: stream = MakeLowLatencyInputStream(params, device_id); break; case AudioParameters::AUDIO_FAKE: stream = FakeAudioInputStream::MakeFakeStream(this, params); break; default: stream = NULL; break; } if (stream) { ++num_input_streams_; } return stream; } AudioOutputStream* AudioManagerBase::MakeAudioOutputStreamProxy( const AudioParameters& params, const std::string& input_device_id) { #if defined(OS_IOS) // IOS implements audio input only. NOTIMPLEMENTED(); return NULL; #else DCHECK(message_loop_->BelongsToCurrentThread()); // If we're not using AudioOutputResampler our output parameters are the same // as our input parameters. AudioParameters output_params = params; if (params.format() == AudioParameters::AUDIO_PCM_LOW_LATENCY) { output_params = GetPreferredOutputStreamParameters(params); // Ensure we only pass on valid output parameters. if (!output_params.IsValid()) { // We've received invalid audio output parameters, so switch to a mock // output device based on the input parameters. This may happen if the OS // provided us junk values for the hardware configuration. LOG(ERROR) << "Invalid audio output parameters received; using fake " << "audio path. Channels: " << output_params.channels() << ", " << "Sample Rate: " << output_params.sample_rate() << ", " << "Bits Per Sample: " << output_params.bits_per_sample() << ", Frames Per Buffer: " << output_params.frames_per_buffer(); // Tell the AudioManager to create a fake output device. output_params = AudioParameters( AudioParameters::AUDIO_FAKE, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } } DispatcherParams* dispatcher_params = new DispatcherParams(params, output_params, input_device_id); AudioOutputDispatchers::iterator it = std::find_if(output_dispatchers_.begin(), output_dispatchers_.end(), CompareByParams(dispatcher_params)); if (it != output_dispatchers_.end()) { delete dispatcher_params; return new AudioOutputProxy((*it)->dispatcher.get()); } const base::TimeDelta kCloseDelay = base::TimeDelta::FromSeconds(kStreamCloseDelaySeconds); scoped_refptr<AudioOutputDispatcher> dispatcher; if (output_params.format() != AudioParameters::AUDIO_FAKE) { dispatcher = new AudioOutputResampler(this, params, output_params, input_device_id, kCloseDelay); } else { dispatcher = new AudioOutputDispatcherImpl(this, output_params, input_device_id, kCloseDelay); } dispatcher_params->dispatcher = dispatcher; output_dispatchers_.push_back(dispatcher_params); return new AudioOutputProxy(dispatcher.get()); #endif // defined(OS_IOS) } void AudioManagerBase::ShowAudioInputSettings() { } void AudioManagerBase::GetAudioInputDeviceNames( media::AudioDeviceNames* device_names) { } void AudioManagerBase::ReleaseOutputStream(AudioOutputStream* stream) { DCHECK(stream); // TODO(xians) : Have a clearer destruction path for the AudioOutputStream. // For example, pass the ownership to AudioManager so it can delete the // streams. --num_output_streams_; delete stream; } void AudioManagerBase::ReleaseInputStream(AudioInputStream* stream) { DCHECK(stream); // TODO(xians) : Have a clearer destruction path for the AudioInputStream. --num_input_streams_; delete stream; } void AudioManagerBase::Shutdown() { // To avoid running into deadlocks while we stop the thread, shut it down // via a local variable while not holding the audio thread lock. scoped_ptr<base::Thread> audio_thread; { base::AutoLock lock(audio_thread_lock_); audio_thread_.swap(audio_thread); } if (!audio_thread) return; // Only true when we're sharing the UI message loop with the browser. The UI // loop is no longer running at this time and browser destruction is imminent. if (message_loop_->BelongsToCurrentThread()) { ShutdownOnAudioThread(); } else { message_loop_->PostTask(FROM_HERE, base::Bind( &AudioManagerBase::ShutdownOnAudioThread, base::Unretained(this))); } // Stop() will wait for any posted messages to be processed first. audio_thread->Stop(); } void AudioManagerBase::ShutdownOnAudioThread() { // IOS implements audio input only. #if defined(OS_IOS) return; #else // This should always be running on the audio thread, but since we've cleared // the audio_thread_ member pointer when we get here, we can't verify exactly // what thread we're running on. The method is not public though and only // called from one place, so we'll leave it at that. AudioOutputDispatchers::iterator it = output_dispatchers_.begin(); for (; it != output_dispatchers_.end(); ++it) { scoped_refptr<AudioOutputDispatcher>& dispatcher = (*it)->dispatcher; if (dispatcher.get()) { dispatcher->Shutdown(); // All AudioOutputProxies must have been freed before Shutdown is called. // If they still exist, things will go bad. They have direct pointers to // both physical audio stream objects that belong to the dispatcher as // well as the message loop of the audio thread that will soon go away. // So, better crash now than later. DCHECK(dispatcher->HasOneRef()) << "AudioOutputProxies are still alive"; dispatcher = NULL; } } output_dispatchers_.clear(); #endif // defined(OS_IOS) } void AudioManagerBase::AddOutputDeviceChangeListener( AudioDeviceListener* listener) { DCHECK(message_loop_->BelongsToCurrentThread()); output_listeners_.AddObserver(listener); } void AudioManagerBase::RemoveOutputDeviceChangeListener( AudioDeviceListener* listener) { DCHECK(message_loop_->BelongsToCurrentThread()); output_listeners_.RemoveObserver(listener); } void AudioManagerBase::NotifyAllOutputDeviceChangeListeners() { DCHECK(message_loop_->BelongsToCurrentThread()); DVLOG(1) << "Firing OnDeviceChange() notifications."; FOR_EACH_OBSERVER(AudioDeviceListener, output_listeners_, OnDeviceChange()); } AudioParameters AudioManagerBase::GetDefaultOutputStreamParameters() { return GetPreferredOutputStreamParameters(AudioParameters()); } AudioParameters AudioManagerBase::GetInputStreamParameters( const std::string& device_id) { NOTREACHED(); return AudioParameters(); } } // namespace media <|endoftext|>
<commit_before>#include "platform.hpp" #include "../coding/sha2.hpp" #include "../coding/base64.hpp" #include "../base/logging.hpp" string Platform::ReadPathForFile(string const & file) const { string fullPath = m_writableDir + file; if (!IsFileExistsByFullPath(fullPath)) { fullPath = m_resourcesDir + file; if (!IsFileExistsByFullPath(fullPath)) { // default behaviour - assume that we have full path here if (!IsFileExistsByFullPath(file)) MYTHROW(FileAbsentException, ("File doesn't exist", file)); else return file; } } return fullPath; } string Platform::HashUniqueID(string const & s) { // generate sha2 hash for UUID string const hash = sha2::digest256(s, false); // xor it size_t const offset = hash.size() / 4; string xoredHash; for (size_t i = 0; i < offset; ++i) xoredHash.push_back(hash[i] ^ hash[i + offset] ^ hash[i + offset * 2] ^ hash[i + offset * 3]); // and use base64 encoding return base64_for_user_ids::encode(xoredHash); } string Platform::ResourcesMetaServerUrl() const { return "http://active.resources.servers.url"; } string Platform::MetaServerUrl() const { if (m_isPro) return "http://active.servers.url"; else return "http://active.servers.url"; } string Platform::DefaultUrlsJSON() const { if (m_isPro) return "[\"http://1st.default.server/\",\"http://2nd.default.server/\",\"http://3rd.default.server/\"]"; else return "[\"http://1st.default.server/\",\"http://2nd.default.server/\",\"http://3rd.default.server/\"]"; } void Platform::GetFontNames(FilesList & res) const { GetSystemFontNames(res); size_t n = 0; string const * arrPaths[4]; arrPaths[n++] = &m_writableDir; #ifdef OMIM_OS_ANDROID for (size_t i = 0; i < m_extResFiles.size(); ++i) arrPaths[n++] = &m_extResFiles[i]; #else arrPaths[n++] = &m_resourcesDir; #endif FilesList fonts; for (size_t i = 0; i < n; ++i) { LOG(LDEBUG, ("Searching for fonts in", *(arrPaths[i]))); GetFilesByExt(*(arrPaths[i]), FONT_FILE_EXTENSION, fonts); } sort(fonts.begin(), fonts.end()); fonts.erase(unique(fonts.begin(), fonts.end()), fonts.end()); res.insert(res.end(), fonts.begin(), fonts.end()); LOG(LINFO, ("Available font files:", (res))); } void Platform::GetFilesByExt(string const & directory, string const & ext, FilesList & outFiles) { // Transform extension mask to regexp (.mwm -> \.mwm$) ASSERT ( !ext.empty(), () ); ASSERT_EQUAL ( ext[0], '.' , () ); GetFilesByRegExp(directory, '\\' + ext + '$', outFiles); } string Platform::DeviceName() const { return OMIM_OS_NAME; } <commit_msg>[platform] change URLs to standard ones<commit_after>#include "platform.hpp" #include "../coding/sha2.hpp" #include "../coding/base64.hpp" #include "../base/logging.hpp" string Platform::ReadPathForFile(string const & file) const { string fullPath = m_writableDir + file; if (!IsFileExistsByFullPath(fullPath)) { fullPath = m_resourcesDir + file; if (!IsFileExistsByFullPath(fullPath)) { // default behaviour - assume that we have full path here if (!IsFileExistsByFullPath(file)) MYTHROW(FileAbsentException, ("File doesn't exist", file)); else return file; } } return fullPath; } string Platform::HashUniqueID(string const & s) { // generate sha2 hash for UUID string const hash = sha2::digest256(s, false); // xor it size_t const offset = hash.size() / 4; string xoredHash; for (size_t i = 0; i < offset; ++i) xoredHash.push_back(hash[i] ^ hash[i + offset] ^ hash[i + offset * 2] ^ hash[i + offset * 3]); // and use base64 encoding return base64_for_user_ids::encode(xoredHash); } string Platform::ResourcesMetaServerUrl() const { return "http://active.resources.servers.url"; } string Platform::MetaServerUrl() const { if (m_isPro) return "http://active.servers.url"; else return "http://active.servers.url"; } string Platform::DefaultUrlsJSON() const { if (m_isPro) return "[\"http://v2s-1.mapswithme.com/\",\"http://v2s-2.mapswithme.com/\",\"http://v2s-3.mapswithme.com/\"]"; else return "[\"http://v2-1.mapswithme.com/\",\"http://v2-2.mapswithme.com/\",\"http://v2-3.mapswithme.com/\"]"; } void Platform::GetFontNames(FilesList & res) const { GetSystemFontNames(res); size_t n = 0; string const * arrPaths[4]; arrPaths[n++] = &m_writableDir; #ifdef OMIM_OS_ANDROID for (size_t i = 0; i < m_extResFiles.size(); ++i) arrPaths[n++] = &m_extResFiles[i]; #else arrPaths[n++] = &m_resourcesDir; #endif FilesList fonts; for (size_t i = 0; i < n; ++i) { LOG(LDEBUG, ("Searching for fonts in", *(arrPaths[i]))); GetFilesByExt(*(arrPaths[i]), FONT_FILE_EXTENSION, fonts); } sort(fonts.begin(), fonts.end()); fonts.erase(unique(fonts.begin(), fonts.end()), fonts.end()); res.insert(res.end(), fonts.begin(), fonts.end()); LOG(LINFO, ("Available font files:", (res))); } void Platform::GetFilesByExt(string const & directory, string const & ext, FilesList & outFiles) { // Transform extension mask to regexp (.mwm -> \.mwm$) ASSERT ( !ext.empty(), () ); ASSERT_EQUAL ( ext[0], '.' , () ); GetFilesByRegExp(directory, '\\' + ext + '$', outFiles); } string Platform::DeviceName() const { return OMIM_OS_NAME; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/string_split.h" #include "base/string_util.h" #include "media/filters/adaptive_demuxer.h" namespace media { // // AdaptiveDemuxerStream // AdaptiveDemuxerStream::AdaptiveDemuxerStream( StreamVector const& streams, int initial_stream) : streams_(streams), current_stream_index_(initial_stream), bitstream_converter_enabled_(false) { DCheckSanity(); } void AdaptiveDemuxerStream::DCheckSanity() { // We only carry out sanity checks in debug mode. if (!logging::DEBUG_MODE) return; DCHECK(streams_[current_stream_index_].get()); bool non_null_stream_seen = false; Type type; const MediaFormat* media_format; for (size_t i = 0; i < streams_.size(); ++i) { if (!streams_[i]) continue; if (!non_null_stream_seen) { non_null_stream_seen = true; type = streams_[i]->type(); media_format = &streams_[i]->media_format(); } else { DCHECK_EQ(streams_[i]->type(), type); DCHECK(streams_[i]->media_format() == *media_format); } } } AdaptiveDemuxerStream::~AdaptiveDemuxerStream() { base::AutoLock auto_lock(lock_); current_stream_index_ = -1; streams_.clear(); } DemuxerStream* AdaptiveDemuxerStream::current_stream() { base::AutoLock auto_lock(lock_); return streams_[current_stream_index_]; } void AdaptiveDemuxerStream::Read(Callback1<Buffer*>::Type* read_callback) { current_stream()->Read(read_callback); } AVStream* AdaptiveDemuxerStream::GetAVStream() { return current_stream()->GetAVStream(); } DemuxerStream::Type AdaptiveDemuxerStream::type() { return current_stream()->type(); } const MediaFormat& AdaptiveDemuxerStream::media_format() { return current_stream()->media_format(); } void AdaptiveDemuxerStream::EnableBitstreamConverter() { { base::AutoLock auto_lock(lock_); bitstream_converter_enabled_ = true; } current_stream()->EnableBitstreamConverter(); } void AdaptiveDemuxerStream::ChangeCurrentStream(int index) { bool needs_bitstream_converter_enabled; { base::AutoLock auto_lock(lock_); current_stream_index_ = index; DCHECK(streams_[current_stream_index_]); needs_bitstream_converter_enabled = bitstream_converter_enabled_; } if (needs_bitstream_converter_enabled) EnableBitstreamConverter(); } // // AdaptiveDemuxer // AdaptiveDemuxer::AdaptiveDemuxer(DemuxerVector const& demuxers, int initial_audio_demuxer_index, int initial_video_demuxer_index) : demuxers_(demuxers), current_audio_demuxer_index_(initial_audio_demuxer_index), current_video_demuxer_index_(initial_video_demuxer_index) { DCHECK(!demuxers_.empty()); DCHECK_GE(current_audio_demuxer_index_, -1); DCHECK_GE(current_video_demuxer_index_, -1); DCHECK_LT(current_audio_demuxer_index_, static_cast<int>(demuxers_.size())); DCHECK_LT(current_video_demuxer_index_, static_cast<int>(demuxers_.size())); DCHECK(current_audio_demuxer_index_ != -1 || current_video_demuxer_index_ != -1); AdaptiveDemuxerStream::StreamVector audio_streams, video_streams; for (size_t i = 0; i < demuxers_.size(); ++i) { audio_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::AUDIO)); video_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::VIDEO)); } if (current_audio_demuxer_index_ >= 0) { audio_stream_ = new AdaptiveDemuxerStream( audio_streams, current_audio_demuxer_index_); } if (current_video_demuxer_index_ >= 0) { video_stream_ = new AdaptiveDemuxerStream( video_streams, current_video_demuxer_index_); } // TODO(fischman): any streams in the underlying demuxers that aren't being // consumed currently need to be sent to /dev/null or else FFmpegDemuxer will // hold data for them in memory, waiting for them to get drained by a // non-existent decoder. } AdaptiveDemuxer::~AdaptiveDemuxer() {} void AdaptiveDemuxer::ChangeCurrentDemuxer(int audio_index, int video_index) { // TODO(fischman): this is currently broken because when a new Demuxer is to // be used we need to set_host(host()) it, and we need to set_host(NULL) the // current Demuxer if it's no longer being used. // TODO(fischman): remember to Stop active demuxers that are being abandoned. base::AutoLock auto_lock(lock_); current_audio_demuxer_index_ = audio_index; current_video_demuxer_index_ = video_index; if (audio_stream_) audio_stream_->ChangeCurrentStream(audio_index); if (video_stream_) video_stream_->ChangeCurrentStream(video_index); } Demuxer* AdaptiveDemuxer::current_demuxer(DemuxerStream::Type type) { base::AutoLock auto_lock(lock_); switch (type) { case DemuxerStream::AUDIO: return (current_audio_demuxer_index_ < 0) ? NULL : demuxers_[current_audio_demuxer_index_]; case DemuxerStream::VIDEO: return (current_video_demuxer_index_ < 0) ? NULL : demuxers_[current_video_demuxer_index_]; default: LOG(DFATAL) << "Unexpected type: " << type; return NULL; } } // Helper class that wraps a FilterCallback and expects to get called a set // number of times, after which the wrapped callback is fired (and deleted). class CountingCallback { public: CountingCallback(int count, FilterCallback* orig_cb) : remaining_count_(count), orig_cb_(orig_cb) { DCHECK_GT(remaining_count_, 0); DCHECK(orig_cb); } FilterCallback* GetACallback() { return NewCallback(this, &CountingCallback::OnChildCallbackDone); } private: void OnChildCallbackDone() { bool fire_orig_cb = false; { base::AutoLock auto_lock(lock_); if (--remaining_count_ == 0) fire_orig_cb = true; } if (fire_orig_cb) { orig_cb_->Run(); delete this; } } base::Lock lock_; int remaining_count_; scoped_ptr<FilterCallback> orig_cb_; }; void AdaptiveDemuxer::Stop(FilterCallback* callback) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0); CountingCallback* wrapper = new CountingCallback(count, callback); if (audio) audio->Stop(wrapper->GetACallback()); if (video && audio != video) video->Stop(wrapper->GetACallback()); } void AdaptiveDemuxer::Seek(base::TimeDelta time, FilterCallback* callback) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0); CountingCallback* wrapper = new CountingCallback(count, callback); if (audio) audio->Seek(time, wrapper->GetACallback()); if (video && audio != video) video->Seek(time, wrapper->GetACallback()); } void AdaptiveDemuxer::OnAudioRendererDisabled() { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); if (audio) audio->OnAudioRendererDisabled(); if (video && audio != video) video->OnAudioRendererDisabled(); // TODO(fischman): propagate to other demuxers if/when they're selected. } void AdaptiveDemuxer::set_host(FilterHost* filter_host) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); if (audio) audio->set_host(filter_host); if (video && audio != video) video->set_host(filter_host); } scoped_refptr<DemuxerStream> AdaptiveDemuxer::GetStream( DemuxerStream::Type type) { switch (type) { case DemuxerStream::AUDIO: return audio_stream_; case DemuxerStream::VIDEO: return video_stream_; default: LOG(DFATAL) << "Unexpected type " << type; return NULL; } } // // AdaptiveDemuxerFactory // AdaptiveDemuxerFactory::AdaptiveDemuxerFactory( DemuxerFactory* delegate_factory) : delegate_factory_(delegate_factory) { DCHECK(delegate_factory); } AdaptiveDemuxerFactory::~AdaptiveDemuxerFactory() {} DemuxerFactory* AdaptiveDemuxerFactory::Clone() const { return new AdaptiveDemuxerFactory(delegate_factory_->Clone()); } // See AdaptiveDemuxerFactory's class-level comment for |url|'s format. bool ParseAdaptiveUrl( const std::string& url, int* audio_index, int* video_index, std::vector<std::string>* urls) { urls->clear(); if (url.empty()) return false; if (!StartsWithASCII(url, "x-adaptive:", false)) { return ParseAdaptiveUrl( "x-adaptive:0:0:" + url, audio_index, video_index, urls); } std::vector<std::string> parts; base::SplitStringDontTrim(url, ':', &parts); if (parts.size() < 4 || parts[0] != "x-adaptive" || !base::StringToInt(parts[1], audio_index) || !base::StringToInt(parts[2], video_index) || *audio_index < -1 || *video_index < -1) { return false; } std::string::size_type first_url_pos = parts[0].size() + 1 + parts[1].size() + 1 + parts[2].size() + 1; std::string urls_str = url.substr(first_url_pos); if (urls_str.empty()) return false; base::SplitStringDontTrim(urls_str, '^', urls); if (urls->empty() || *audio_index >= static_cast<int>(urls->size()) || *video_index >= static_cast<int>(urls->size())) { return false; } return true; } // Wrapper for a BuildCallback which accumulates the Demuxer's returned by a // number of DemuxerFactory::Build() calls and eventually constructs an // AdaptiveDemuxer and returns it to the |orig_cb| (or errors out if any // individual Demuxer fails construction). class DemuxerAccumulator { public: // Takes ownership of |orig_cb|. DemuxerAccumulator(int audio_index, int video_index, int count, DemuxerFactory::BuildCallback* orig_cb) : audio_index_(audio_index), video_index_(video_index), remaining_count_(count), orig_cb_(orig_cb), demuxers_(count, static_cast<Demuxer*>(NULL)), statuses_(count, PIPELINE_OK) { DCHECK_GT(remaining_count_, 0); DCHECK(orig_cb_.get()); } DemuxerFactory::BuildCallback* GetNthCallback(int n) { return new IndividualCallback(this, n); } private: // Wrapper for a BuildCallback that can carry one extra piece of data: the // index of this callback in the original list of outstanding requests. struct IndividualCallback : public DemuxerFactory::BuildCallback { IndividualCallback(DemuxerAccumulator* accumulator, int index) : accumulator_(accumulator), index_(index) {} virtual void RunWithParams(const Tuple2<PipelineStatus, Demuxer*>& params) { accumulator_->Run(index_, params.a, params.b); } DemuxerAccumulator* accumulator_; int index_; }; // When an individual callback is fired, it calls this method. void Run(int index, PipelineStatus status, Demuxer* demuxer) { bool fire_orig_cb = false; { base::AutoLock auto_lock(lock_); DCHECK(!demuxers_[index]); demuxers_[index] = demuxer; statuses_[index] = status; if (--remaining_count_ == 0) fire_orig_cb = true; } if (fire_orig_cb) DoneAccumulating(); } void DoneAccumulating() { PipelineStatus overall_status = PIPELINE_OK; for (size_t i = 0; i < statuses_.size(); ++i) { if (statuses_[i] != PIPELINE_OK) { overall_status = statuses_[i]; break; } } if (overall_status == PIPELINE_OK) { orig_cb_->Run( PIPELINE_OK, new AdaptiveDemuxer(demuxers_, audio_index_, video_index_)); } else { orig_cb_->Run(overall_status, static_cast<Demuxer*>(NULL)); } delete this; } // Self-delete in DoneAccumulating() only. ~DemuxerAccumulator() {} int audio_index_; int video_index_; int remaining_count_; scoped_ptr<DemuxerFactory::BuildCallback> orig_cb_; base::Lock lock_; // Guards vectors of results below. AdaptiveDemuxer::DemuxerVector demuxers_; std::vector<PipelineStatus> statuses_; DISALLOW_IMPLICIT_CONSTRUCTORS(DemuxerAccumulator); }; void AdaptiveDemuxerFactory::Build(const std::string& url, BuildCallback* cb) { std::vector<std::string> urls; int audio_index, video_index; if (!ParseAdaptiveUrl(url, &audio_index, &video_index, &urls)) { cb->Run(Tuple2<PipelineStatus, Demuxer*>( DEMUXER_ERROR_COULD_NOT_OPEN, NULL)); delete cb; return; } DemuxerAccumulator* accumulator = new DemuxerAccumulator( audio_index, video_index, urls.size(), cb); for (size_t i = 0; i < urls.size(); ++i) delegate_factory_->Build(urls[i], accumulator->GetNthCallback(i)); } } // namespace media <commit_msg>Explicitly initialize media_format to avoid incorrect uninitialized-variable compiler warning.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/string_split.h" #include "base/string_util.h" #include "media/filters/adaptive_demuxer.h" namespace media { // // AdaptiveDemuxerStream // AdaptiveDemuxerStream::AdaptiveDemuxerStream( StreamVector const& streams, int initial_stream) : streams_(streams), current_stream_index_(initial_stream), bitstream_converter_enabled_(false) { DCheckSanity(); } void AdaptiveDemuxerStream::DCheckSanity() { // We only carry out sanity checks in debug mode. if (!logging::DEBUG_MODE) return; DCHECK(streams_[current_stream_index_].get()); bool non_null_stream_seen = false; Type type; const MediaFormat* media_format = NULL; for (size_t i = 0; i < streams_.size(); ++i) { if (!streams_[i]) continue; if (!non_null_stream_seen) { non_null_stream_seen = true; type = streams_[i]->type(); media_format = &streams_[i]->media_format(); } else { DCHECK_EQ(streams_[i]->type(), type); DCHECK(streams_[i]->media_format() == *media_format); } } } AdaptiveDemuxerStream::~AdaptiveDemuxerStream() { base::AutoLock auto_lock(lock_); current_stream_index_ = -1; streams_.clear(); } DemuxerStream* AdaptiveDemuxerStream::current_stream() { base::AutoLock auto_lock(lock_); return streams_[current_stream_index_]; } void AdaptiveDemuxerStream::Read(Callback1<Buffer*>::Type* read_callback) { current_stream()->Read(read_callback); } AVStream* AdaptiveDemuxerStream::GetAVStream() { return current_stream()->GetAVStream(); } DemuxerStream::Type AdaptiveDemuxerStream::type() { return current_stream()->type(); } const MediaFormat& AdaptiveDemuxerStream::media_format() { return current_stream()->media_format(); } void AdaptiveDemuxerStream::EnableBitstreamConverter() { { base::AutoLock auto_lock(lock_); bitstream_converter_enabled_ = true; } current_stream()->EnableBitstreamConverter(); } void AdaptiveDemuxerStream::ChangeCurrentStream(int index) { bool needs_bitstream_converter_enabled; { base::AutoLock auto_lock(lock_); current_stream_index_ = index; DCHECK(streams_[current_stream_index_]); needs_bitstream_converter_enabled = bitstream_converter_enabled_; } if (needs_bitstream_converter_enabled) EnableBitstreamConverter(); } // // AdaptiveDemuxer // AdaptiveDemuxer::AdaptiveDemuxer(DemuxerVector const& demuxers, int initial_audio_demuxer_index, int initial_video_demuxer_index) : demuxers_(demuxers), current_audio_demuxer_index_(initial_audio_demuxer_index), current_video_demuxer_index_(initial_video_demuxer_index) { DCHECK(!demuxers_.empty()); DCHECK_GE(current_audio_demuxer_index_, -1); DCHECK_GE(current_video_demuxer_index_, -1); DCHECK_LT(current_audio_demuxer_index_, static_cast<int>(demuxers_.size())); DCHECK_LT(current_video_demuxer_index_, static_cast<int>(demuxers_.size())); DCHECK(current_audio_demuxer_index_ != -1 || current_video_demuxer_index_ != -1); AdaptiveDemuxerStream::StreamVector audio_streams, video_streams; for (size_t i = 0; i < demuxers_.size(); ++i) { audio_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::AUDIO)); video_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::VIDEO)); } if (current_audio_demuxer_index_ >= 0) { audio_stream_ = new AdaptiveDemuxerStream( audio_streams, current_audio_demuxer_index_); } if (current_video_demuxer_index_ >= 0) { video_stream_ = new AdaptiveDemuxerStream( video_streams, current_video_demuxer_index_); } // TODO(fischman): any streams in the underlying demuxers that aren't being // consumed currently need to be sent to /dev/null or else FFmpegDemuxer will // hold data for them in memory, waiting for them to get drained by a // non-existent decoder. } AdaptiveDemuxer::~AdaptiveDemuxer() {} void AdaptiveDemuxer::ChangeCurrentDemuxer(int audio_index, int video_index) { // TODO(fischman): this is currently broken because when a new Demuxer is to // be used we need to set_host(host()) it, and we need to set_host(NULL) the // current Demuxer if it's no longer being used. // TODO(fischman): remember to Stop active demuxers that are being abandoned. base::AutoLock auto_lock(lock_); current_audio_demuxer_index_ = audio_index; current_video_demuxer_index_ = video_index; if (audio_stream_) audio_stream_->ChangeCurrentStream(audio_index); if (video_stream_) video_stream_->ChangeCurrentStream(video_index); } Demuxer* AdaptiveDemuxer::current_demuxer(DemuxerStream::Type type) { base::AutoLock auto_lock(lock_); switch (type) { case DemuxerStream::AUDIO: return (current_audio_demuxer_index_ < 0) ? NULL : demuxers_[current_audio_demuxer_index_]; case DemuxerStream::VIDEO: return (current_video_demuxer_index_ < 0) ? NULL : demuxers_[current_video_demuxer_index_]; default: LOG(DFATAL) << "Unexpected type: " << type; return NULL; } } // Helper class that wraps a FilterCallback and expects to get called a set // number of times, after which the wrapped callback is fired (and deleted). class CountingCallback { public: CountingCallback(int count, FilterCallback* orig_cb) : remaining_count_(count), orig_cb_(orig_cb) { DCHECK_GT(remaining_count_, 0); DCHECK(orig_cb); } FilterCallback* GetACallback() { return NewCallback(this, &CountingCallback::OnChildCallbackDone); } private: void OnChildCallbackDone() { bool fire_orig_cb = false; { base::AutoLock auto_lock(lock_); if (--remaining_count_ == 0) fire_orig_cb = true; } if (fire_orig_cb) { orig_cb_->Run(); delete this; } } base::Lock lock_; int remaining_count_; scoped_ptr<FilterCallback> orig_cb_; }; void AdaptiveDemuxer::Stop(FilterCallback* callback) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0); CountingCallback* wrapper = new CountingCallback(count, callback); if (audio) audio->Stop(wrapper->GetACallback()); if (video && audio != video) video->Stop(wrapper->GetACallback()); } void AdaptiveDemuxer::Seek(base::TimeDelta time, FilterCallback* callback) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0); CountingCallback* wrapper = new CountingCallback(count, callback); if (audio) audio->Seek(time, wrapper->GetACallback()); if (video && audio != video) video->Seek(time, wrapper->GetACallback()); } void AdaptiveDemuxer::OnAudioRendererDisabled() { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); if (audio) audio->OnAudioRendererDisabled(); if (video && audio != video) video->OnAudioRendererDisabled(); // TODO(fischman): propagate to other demuxers if/when they're selected. } void AdaptiveDemuxer::set_host(FilterHost* filter_host) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); if (audio) audio->set_host(filter_host); if (video && audio != video) video->set_host(filter_host); } scoped_refptr<DemuxerStream> AdaptiveDemuxer::GetStream( DemuxerStream::Type type) { switch (type) { case DemuxerStream::AUDIO: return audio_stream_; case DemuxerStream::VIDEO: return video_stream_; default: LOG(DFATAL) << "Unexpected type " << type; return NULL; } } // // AdaptiveDemuxerFactory // AdaptiveDemuxerFactory::AdaptiveDemuxerFactory( DemuxerFactory* delegate_factory) : delegate_factory_(delegate_factory) { DCHECK(delegate_factory); } AdaptiveDemuxerFactory::~AdaptiveDemuxerFactory() {} DemuxerFactory* AdaptiveDemuxerFactory::Clone() const { return new AdaptiveDemuxerFactory(delegate_factory_->Clone()); } // See AdaptiveDemuxerFactory's class-level comment for |url|'s format. bool ParseAdaptiveUrl( const std::string& url, int* audio_index, int* video_index, std::vector<std::string>* urls) { urls->clear(); if (url.empty()) return false; if (!StartsWithASCII(url, "x-adaptive:", false)) { return ParseAdaptiveUrl( "x-adaptive:0:0:" + url, audio_index, video_index, urls); } std::vector<std::string> parts; base::SplitStringDontTrim(url, ':', &parts); if (parts.size() < 4 || parts[0] != "x-adaptive" || !base::StringToInt(parts[1], audio_index) || !base::StringToInt(parts[2], video_index) || *audio_index < -1 || *video_index < -1) { return false; } std::string::size_type first_url_pos = parts[0].size() + 1 + parts[1].size() + 1 + parts[2].size() + 1; std::string urls_str = url.substr(first_url_pos); if (urls_str.empty()) return false; base::SplitStringDontTrim(urls_str, '^', urls); if (urls->empty() || *audio_index >= static_cast<int>(urls->size()) || *video_index >= static_cast<int>(urls->size())) { return false; } return true; } // Wrapper for a BuildCallback which accumulates the Demuxer's returned by a // number of DemuxerFactory::Build() calls and eventually constructs an // AdaptiveDemuxer and returns it to the |orig_cb| (or errors out if any // individual Demuxer fails construction). class DemuxerAccumulator { public: // Takes ownership of |orig_cb|. DemuxerAccumulator(int audio_index, int video_index, int count, DemuxerFactory::BuildCallback* orig_cb) : audio_index_(audio_index), video_index_(video_index), remaining_count_(count), orig_cb_(orig_cb), demuxers_(count, static_cast<Demuxer*>(NULL)), statuses_(count, PIPELINE_OK) { DCHECK_GT(remaining_count_, 0); DCHECK(orig_cb_.get()); } DemuxerFactory::BuildCallback* GetNthCallback(int n) { return new IndividualCallback(this, n); } private: // Wrapper for a BuildCallback that can carry one extra piece of data: the // index of this callback in the original list of outstanding requests. struct IndividualCallback : public DemuxerFactory::BuildCallback { IndividualCallback(DemuxerAccumulator* accumulator, int index) : accumulator_(accumulator), index_(index) {} virtual void RunWithParams(const Tuple2<PipelineStatus, Demuxer*>& params) { accumulator_->Run(index_, params.a, params.b); } DemuxerAccumulator* accumulator_; int index_; }; // When an individual callback is fired, it calls this method. void Run(int index, PipelineStatus status, Demuxer* demuxer) { bool fire_orig_cb = false; { base::AutoLock auto_lock(lock_); DCHECK(!demuxers_[index]); demuxers_[index] = demuxer; statuses_[index] = status; if (--remaining_count_ == 0) fire_orig_cb = true; } if (fire_orig_cb) DoneAccumulating(); } void DoneAccumulating() { PipelineStatus overall_status = PIPELINE_OK; for (size_t i = 0; i < statuses_.size(); ++i) { if (statuses_[i] != PIPELINE_OK) { overall_status = statuses_[i]; break; } } if (overall_status == PIPELINE_OK) { orig_cb_->Run( PIPELINE_OK, new AdaptiveDemuxer(demuxers_, audio_index_, video_index_)); } else { orig_cb_->Run(overall_status, static_cast<Demuxer*>(NULL)); } delete this; } // Self-delete in DoneAccumulating() only. ~DemuxerAccumulator() {} int audio_index_; int video_index_; int remaining_count_; scoped_ptr<DemuxerFactory::BuildCallback> orig_cb_; base::Lock lock_; // Guards vectors of results below. AdaptiveDemuxer::DemuxerVector demuxers_; std::vector<PipelineStatus> statuses_; DISALLOW_IMPLICIT_CONSTRUCTORS(DemuxerAccumulator); }; void AdaptiveDemuxerFactory::Build(const std::string& url, BuildCallback* cb) { std::vector<std::string> urls; int audio_index, video_index; if (!ParseAdaptiveUrl(url, &audio_index, &video_index, &urls)) { cb->Run(Tuple2<PipelineStatus, Demuxer*>( DEMUXER_ERROR_COULD_NOT_OPEN, NULL)); delete cb; return; } DemuxerAccumulator* accumulator = new DemuxerAccumulator( audio_index, video_index, urls.size(), cb); for (size_t i = 0; i < urls.size(); ++i) delegate_factory_->Build(urls[i], accumulator->GetNthCallback(i)); } } // namespace media <|endoftext|>
<commit_before>/** * @copyright * ==================================================================== * Copyright (c) 2007 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== * @endcopyright * * @file InfoCallback.cpp * @brief Implementation of the class InfoCallback */ #include "SVNClient.h" #include "InfoCallback.h" #include "EnumMapper.h" #include "JNIUtil.h" #include "svn_time.h" #include "svn_path.h" struct info_entry { const char *path; bool copied; bool deleted; bool absent; bool incomplete; svn_info_t *info; }; /** * Create a InfoCallback object. jcallback is the java callback object. */ InfoCallback::InfoCallback(jobject jcallback) { m_callback = jcallback; wcPath = NULL; } /** * Destroy a InfoCallback object */ InfoCallback::~InfoCallback() { // the m_callback does not need to be destroyed, because it is the passed // in parameter to the java SVNClient.info method. } svn_error_t * InfoCallback::callback(void *baton, const char *path, const svn_info_t *info, apr_pool_t *pool) { if (baton) return ((InfoCallback *)baton)->singleInfo(path, info, pool); return SVN_NO_ERROR; } void InfoCallback::setWcPath(const char *path) { wcPath = path; } /** * Callback called for a single path. path is the path name, pool may be used * for memory allocation. */ svn_error_t * InfoCallback::singleInfo(const char *path, const svn_info_t *info, apr_pool_t *pool) { JNIEnv *env = JNIUtil::getEnv(); static jmethodID mid = 0; // the method id will not change during // the time this library is loaded, so // it can be cached. if (mid == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/InfoCallback"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; mid = env->GetMethodID(clazz, "singleInfo", "(L"JAVA_PACKAGE"/Info2;)V"); if (JNIUtil::isJavaExceptionThrown() || mid == 0) return SVN_NO_ERROR; env->DeleteLocalRef(clazz); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; } info_entry infoEntry; SVN_JNI_ERR(createInfoEntry(infoEntry, path, info, pool), SVN_NO_ERROR); jobject jinfo2 = createJavaInfo2(&infoEntry); env->CallVoidMethod(m_callback, mid, jinfo2); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(jinfo2); // Return SVN_NO_ERROR here regardless of an exception or not. return SVN_NO_ERROR; } svn_error_t * InfoCallback::createInfoEntry(info_entry &infoEntry, const char *path, const svn_info_t *info, apr_pool_t *pool) { svn_wc_adm_access_t *adm_access; const svn_wc_entry_t *entry; const char *full_path; // If we've cached the wcPath, it means that if (wcPath != NULL) full_path = svn_path_join(wcPath, path, pool); else full_path = path; SVN_ERR(svn_wc_adm_probe_open2(&adm_access, NULL, full_path, FALSE, 0, pool)); SVN_ERR(svn_wc_entry(&entry, path, adm_access, FALSE, pool)); SVN_ERR(svn_wc_adm_close(adm_access)); if (!entry) { // We want to store a NULL in the resulting array, but we can't put a // NULL reference into the infoVect vector, so we just set the path to // NULL, and use that later. infoEntry.path = NULL; return SVN_NO_ERROR; } infoEntry.copied = entry->copied; infoEntry.deleted = entry->deleted; infoEntry.absent = entry->absent; infoEntry.incomplete = entry->incomplete; // we don't create here java Status object as we don't want too many local // references infoEntry.path = apr_pstrdup(pool,path); infoEntry.info = (svn_info_t*)apr_pcalloc(pool, sizeof(svn_info_t)); infoEntry.info->URL = apr_pstrdup(pool,info->URL); infoEntry.info->rev = info->rev; infoEntry.info->kind = info->kind; infoEntry.info->repos_root_URL = apr_pstrdup(pool, info->repos_root_URL); infoEntry.info->repos_UUID = apr_pstrdup(pool, info->repos_UUID); infoEntry.info->last_changed_rev = info->last_changed_rev; infoEntry.info->last_changed_date = info->last_changed_date; infoEntry.info->last_changed_author = apr_pstrdup(pool, info->last_changed_author); if (info->lock != NULL) infoEntry.info->lock = svn_lock_dup(info->lock, pool); else infoEntry.info->lock = NULL; infoEntry.info->has_wc_info = info->has_wc_info; infoEntry.info->schedule = info->schedule; infoEntry.info->copyfrom_url = apr_pstrdup(pool, info->copyfrom_url); infoEntry.info->copyfrom_rev = info->copyfrom_rev; infoEntry.info->text_time = info->text_time; infoEntry.info->prop_time = info->prop_time; infoEntry.info->checksum = apr_pstrdup(pool, info->checksum); infoEntry.info->conflict_old = apr_pstrdup(pool, info->conflict_old); infoEntry.info->conflict_new = apr_pstrdup(pool, info->conflict_new); infoEntry.info->conflict_wrk = apr_pstrdup(pool, info->conflict_wrk); infoEntry.info->prejfile = apr_pstrdup(pool, info->prejfile); return SVN_NO_ERROR; } jobject InfoCallback::createJavaInfo2(info_entry *infoEntry) { const svn_info_t *info = infoEntry->info; JNIEnv *env = JNIUtil::getEnv(); jclass clazz = env->FindClass(JAVA_PACKAGE"/Info2"); if (JNIUtil::isJavaExceptionThrown()) return NULL; static jmethodID mid = 0; if (mid == 0) { mid = env->GetMethodID(clazz, "<init>", "(Ljava/lang/String;Ljava/lang/String;JILjava/lang/String;" "Ljava/lang/String;JLjava/util/Date;Ljava/lang/String;" "Lorg/tigris/subversion/javahl/Lock;ZILjava/lang/String;J" "Ljava/util/Date;Ljava/util/Date;" "Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;" "Ljava/lang/String;Ljava/lang/String;ZZZZ)V"); if (mid == 0 || JNIUtil::isJavaExceptionThrown()) return NULL; } jstring jpath = JNIUtil::makeJString(infoEntry->path); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jurl = JNIUtil::makeJString(info->URL); if (JNIUtil::isJavaExceptionThrown()) return NULL; jlong jrev = info->rev; jint jnodeKind = EnumMapper::mapNodeKind(info->kind); jstring jreposRootUrl = JNIUtil::makeJString(info->repos_root_URL); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jreportUUID = JNIUtil::makeJString(info->repos_UUID); if (JNIUtil::isJavaExceptionThrown()) return NULL; jlong jlastChangedRev = info->last_changed_rev; jobject jlastChangedDate = JNIUtil::createDate(info->last_changed_date); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jlastChangedAuthor = JNIUtil::makeJString(info->last_changed_author); if (JNIUtil::isJavaExceptionThrown()) return NULL; jobject jlock = SVNClient::createJavaLock(info->lock); if (JNIUtil::isJavaExceptionThrown()) return NULL; jboolean jhasWcInfo = info->has_wc_info ? JNI_TRUE:JNI_FALSE; jint jschedule = EnumMapper::mapScheduleKind(info->schedule); jstring jcopyFromUrl = JNIUtil::makeJString(info->copyfrom_url); jlong jcopyFromRev = info->copyfrom_rev; jobject jtextTime = JNIUtil::createDate(info->text_time); if (JNIUtil::isJavaExceptionThrown()) return NULL; jobject jpropTime = JNIUtil::createDate(info->prop_time); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jchecksum = JNIUtil::makeJString(info->checksum); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jconflictOld = JNIUtil::makeJString(info->conflict_old); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jconflictNew = JNIUtil::makeJString(info->conflict_new); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jconflictWrk = JNIUtil::makeJString(info->conflict_wrk); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jprejfile = JNIUtil::makeJString(info->prejfile); if (JNIUtil::isJavaExceptionThrown()) return NULL; jboolean jcopied = infoEntry->copied ? JNI_TRUE : JNI_FALSE; jboolean jdeleted = infoEntry->deleted ? JNI_TRUE : JNI_FALSE; jboolean jabsent = infoEntry->absent ? JNI_TRUE : JNI_FALSE; jboolean jincomplete = infoEntry->incomplete ? JNI_TRUE : JNI_FALSE; jobject ret = env->NewObject(clazz, mid, jpath, jurl, jrev, jnodeKind, jreposRootUrl, jreportUUID, jlastChangedRev, jlastChangedDate, jlastChangedAuthor, jlock, jhasWcInfo, jschedule, jcopyFromUrl, jcopyFromRev, jtextTime, jpropTime, jchecksum, jconflictOld, jconflictNew, jconflictWrk, jprejfile, jcopied, jdeleted, jabsent, jincomplete); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(clazz); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jpath); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jurl); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jreposRootUrl); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jlastChangedDate); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jlastChangedAuthor); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jlock); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jcopyFromUrl); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jchecksum); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jtextTime); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jpropTime); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jconflictOld); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jconflictNew); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jconflictWrk); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jprejfile); if (JNIUtil::isJavaExceptionThrown()) return NULL; return ret; } <commit_msg>JavaHL: Fix segfault when creating a Java Info2 object in the InfoCallback C++ code, using a temporary hack. This segfault injected by r24349, and can be triggered by BasicTests.testBasicInfo2().<commit_after>/** * @copyright * ==================================================================== * Copyright (c) 2007 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== * @endcopyright * * @file InfoCallback.cpp * @brief Implementation of the class InfoCallback */ #include "SVNClient.h" #include "InfoCallback.h" #include "EnumMapper.h" #include "JNIUtil.h" #include "svn_time.h" #include "svn_path.h" struct info_entry { const char *path; bool copied; bool deleted; bool absent; bool incomplete; svn_info_t *info; }; /** * Create a InfoCallback object. jcallback is the java callback object. */ InfoCallback::InfoCallback(jobject jcallback) { m_callback = jcallback; wcPath = NULL; } /** * Destroy a InfoCallback object */ InfoCallback::~InfoCallback() { // the m_callback does not need to be destroyed, because it is the passed // in parameter to the java SVNClient.info method. } svn_error_t * InfoCallback::callback(void *baton, const char *path, const svn_info_t *info, apr_pool_t *pool) { if (baton) return ((InfoCallback *)baton)->singleInfo(path, info, pool); return SVN_NO_ERROR; } void InfoCallback::setWcPath(const char *path) { wcPath = path; } /** * Callback called for a single path. path is the path name, pool may be used * for memory allocation. */ svn_error_t * InfoCallback::singleInfo(const char *path, const svn_info_t *info, apr_pool_t *pool) { JNIEnv *env = JNIUtil::getEnv(); static jmethodID mid = 0; // the method id will not change during // the time this library is loaded, so // it can be cached. if (mid == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/InfoCallback"); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; mid = env->GetMethodID(clazz, "singleInfo", "(L"JAVA_PACKAGE"/Info2;)V"); if (JNIUtil::isJavaExceptionThrown() || mid == 0) return SVN_NO_ERROR; env->DeleteLocalRef(clazz); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; } info_entry infoEntry; SVN_JNI_ERR(createInfoEntry(infoEntry, path, info, pool), SVN_NO_ERROR); jobject jinfo2 = createJavaInfo2(&infoEntry); env->CallVoidMethod(m_callback, mid, jinfo2); if (JNIUtil::isJavaExceptionThrown()) return SVN_NO_ERROR; env->DeleteLocalRef(jinfo2); // Return SVN_NO_ERROR here regardless of an exception or not. return SVN_NO_ERROR; } svn_error_t * InfoCallback::createInfoEntry(info_entry &infoEntry, const char *path, const svn_info_t *info, apr_pool_t *pool) { svn_wc_adm_access_t *adm_access; const svn_wc_entry_t *entry; const char *full_path; // If we've cached the wcPath, it means that if (wcPath != NULL) full_path = svn_path_join(wcPath, path, pool); else full_path = path; SVN_ERR(svn_wc_adm_probe_open2(&adm_access, NULL, full_path, FALSE, 0, pool)); SVN_ERR(svn_wc_entry(&entry, path, adm_access, FALSE, pool)); SVN_ERR(svn_wc_adm_close(adm_access)); if (!entry) { // We want to store a NULL in the resulting array, but we can't put a // NULL reference into the infoVect vector, so we just set the path to // NULL, and use that later. infoEntry.path = NULL; return SVN_NO_ERROR; } infoEntry.copied = entry->copied; infoEntry.deleted = entry->deleted; infoEntry.absent = entry->absent; infoEntry.incomplete = entry->incomplete; // we don't create here java Status object as we don't want too many local // references infoEntry.path = apr_pstrdup(pool,path); infoEntry.info = (svn_info_t*)apr_pcalloc(pool, sizeof(svn_info_t)); infoEntry.info->URL = apr_pstrdup(pool,info->URL); infoEntry.info->rev = info->rev; infoEntry.info->kind = info->kind; infoEntry.info->repos_root_URL = apr_pstrdup(pool, info->repos_root_URL); infoEntry.info->repos_UUID = apr_pstrdup(pool, info->repos_UUID); infoEntry.info->last_changed_rev = info->last_changed_rev; infoEntry.info->last_changed_date = info->last_changed_date; infoEntry.info->last_changed_author = apr_pstrdup(pool, info->last_changed_author); if (info->lock != NULL) infoEntry.info->lock = svn_lock_dup(info->lock, pool); else infoEntry.info->lock = NULL; infoEntry.info->has_wc_info = info->has_wc_info; infoEntry.info->schedule = info->schedule; infoEntry.info->copyfrom_url = apr_pstrdup(pool, info->copyfrom_url); infoEntry.info->copyfrom_rev = info->copyfrom_rev; infoEntry.info->text_time = info->text_time; infoEntry.info->prop_time = info->prop_time; infoEntry.info->checksum = apr_pstrdup(pool, info->checksum); infoEntry.info->conflict_old = apr_pstrdup(pool, info->conflict_old); infoEntry.info->conflict_new = apr_pstrdup(pool, info->conflict_new); infoEntry.info->conflict_wrk = apr_pstrdup(pool, info->conflict_wrk); infoEntry.info->prejfile = apr_pstrdup(pool, info->prejfile); return SVN_NO_ERROR; } jobject InfoCallback::createJavaInfo2(info_entry *infoEntry) { // ### HACK: We happen to know that a null path means that our // ### infoEntry is bogus. We should fix or remove // ### createInfoEntry() instead of using this hack. if (infoEntry->path == NULL) return NULL; const svn_info_t *info = infoEntry->info; JNIEnv *env = JNIUtil::getEnv(); jclass clazz = env->FindClass(JAVA_PACKAGE"/Info2"); if (JNIUtil::isJavaExceptionThrown()) return NULL; static jmethodID mid = 0; if (mid == 0) { mid = env->GetMethodID(clazz, "<init>", "(Ljava/lang/String;Ljava/lang/String;JILjava/lang/String;" "Ljava/lang/String;JLjava/util/Date;Ljava/lang/String;" "Lorg/tigris/subversion/javahl/Lock;ZILjava/lang/String;J" "Ljava/util/Date;Ljava/util/Date;" "Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;" "Ljava/lang/String;Ljava/lang/String;ZZZZ)V"); if (mid == 0 || JNIUtil::isJavaExceptionThrown()) return NULL; } jstring jpath = JNIUtil::makeJString(infoEntry->path); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jurl = JNIUtil::makeJString(info->URL); if (JNIUtil::isJavaExceptionThrown()) return NULL; jlong jrev = info->rev; jint jnodeKind = EnumMapper::mapNodeKind(info->kind); jstring jreposRootUrl = JNIUtil::makeJString(info->repos_root_URL); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jreportUUID = JNIUtil::makeJString(info->repos_UUID); if (JNIUtil::isJavaExceptionThrown()) return NULL; jlong jlastChangedRev = info->last_changed_rev; jobject jlastChangedDate = JNIUtil::createDate(info->last_changed_date); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jlastChangedAuthor = JNIUtil::makeJString(info->last_changed_author); if (JNIUtil::isJavaExceptionThrown()) return NULL; jobject jlock = SVNClient::createJavaLock(info->lock); if (JNIUtil::isJavaExceptionThrown()) return NULL; jboolean jhasWcInfo = info->has_wc_info ? JNI_TRUE:JNI_FALSE; jint jschedule = EnumMapper::mapScheduleKind(info->schedule); jstring jcopyFromUrl = JNIUtil::makeJString(info->copyfrom_url); jlong jcopyFromRev = info->copyfrom_rev; jobject jtextTime = JNIUtil::createDate(info->text_time); if (JNIUtil::isJavaExceptionThrown()) return NULL; jobject jpropTime = JNIUtil::createDate(info->prop_time); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jchecksum = JNIUtil::makeJString(info->checksum); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jconflictOld = JNIUtil::makeJString(info->conflict_old); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jconflictNew = JNIUtil::makeJString(info->conflict_new); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jconflictWrk = JNIUtil::makeJString(info->conflict_wrk); if (JNIUtil::isJavaExceptionThrown()) return NULL; jstring jprejfile = JNIUtil::makeJString(info->prejfile); if (JNIUtil::isJavaExceptionThrown()) return NULL; jboolean jcopied = infoEntry->copied ? JNI_TRUE : JNI_FALSE; jboolean jdeleted = infoEntry->deleted ? JNI_TRUE : JNI_FALSE; jboolean jabsent = infoEntry->absent ? JNI_TRUE : JNI_FALSE; jboolean jincomplete = infoEntry->incomplete ? JNI_TRUE : JNI_FALSE; jobject ret = env->NewObject(clazz, mid, jpath, jurl, jrev, jnodeKind, jreposRootUrl, jreportUUID, jlastChangedRev, jlastChangedDate, jlastChangedAuthor, jlock, jhasWcInfo, jschedule, jcopyFromUrl, jcopyFromRev, jtextTime, jpropTime, jchecksum, jconflictOld, jconflictNew, jconflictWrk, jprejfile, jcopied, jdeleted, jabsent, jincomplete); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(clazz); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jpath); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jurl); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jreposRootUrl); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jlastChangedDate); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jlastChangedAuthor); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jlock); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jcopyFromUrl); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jchecksum); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jtextTime); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jpropTime); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jconflictOld); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jconflictNew); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jconflictWrk); if (JNIUtil::isJavaExceptionThrown()) return NULL; env->DeleteLocalRef(jprejfile); if (JNIUtil::isJavaExceptionThrown()) return NULL; return ret; } <|endoftext|>
<commit_before>// Purpose: Get relative humidity and temperature from A2302 sensor found at akizukidenshi.com/download/ds/aosong/AM2302.pdf #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <iostream> #include <stdio.h> #include <signal.h> #include <stdlib.h> // absolute addresses #define GPIO0_ADDR (0x44E07000) #define GPIO1_ADDR (0x4804C000) #define GPIO2_ADDR (0x481AC000) #define GPIO3_ADDR (0x481AF000) // relative addresses (from the ones above) #define OE_ADDR (0x134) #define GPIO_DATAIN (0x138) // read value of pins #define GPIO_DATAOUT (0x13C) // write value to pins #define GPIO_PIN_NUMBER (31) // ex. if we are in GPIO0, then 30 here would mean GPIO0_30, where as GPIO1 would be GPIO1_30 #define PIN_HIGH (1 << GPIO_PIN_NUMBER) #define PIN_LOW (0) #define PIN_INPUT(){ \ pinconf1[OE_ADDR/4] |= (1 << GPIO_PIN_NUMBER); \ } #define PIN_OUTPUT(){ \ pinconf1[OE_ADDR/4] &= (0xFFFFFFFF ^ (1 << GPIO_PIN_NUMBER)); \ } int PIN_READ(ulong* pinconf1){ // never do this! you can still read even when it is an PIN_OUTPUT // and if you do this, then when you write and read it will never be // what you wrote the pin to be //PIN_INPUT(); return pinconf1[GPIO_DATAIN/4] & (1 << GPIO_PIN_NUMBER); } #define PIN_WRITE(val) { \ PIN_OUTPUT(); \ if(val == PIN_HIGH) \ { \ pinconf1[GPIO_DATAOUT/4] |= (1 << GPIO_PIN_NUMBER); \ } \ else if(val == PIN_LOW) \ { \ pinconf1[GPIO_DATAOUT/4] &= (0xFFFFFFFF ^ (1 << GPIO_PIN_NUMBER)); \ } \ } // state machine #define STATE_IDLE (0) #define STATE_COMMAND (1) #define STATE_RESPONSE (2) #define STATE_DATA (3) bool globalStartMeasuring = false; // used to trigger a sensor read using namespace std; static void startCommandHandler(int sig) { globalStartMeasuring = true; } void print(char * message) { printf("%s\n", message); fflush(stdout); } // return: // returns -1 if time out is greater that "timeoutUS" microseconds // otherwise, returns the number of microseconds it took for the // pin output became the value "pinValueToWaitFor" // args: // "pinValueToWaitFor" must be either PIN_HIGH or PIN_LOW int waitForTransition(ulong *pinconf1, int pinValueToWaitFor, int timeoutUS) { int countUS = 0; while(true) { // xxx it may be a problem that we check for this right away, because // what if this is true beacuse its from the last clock cycle? // maybe we should wait until the pin read becomes !pinValueToWaitFor // THEN do this if(PIN_READ(pinconf1) == pinValueToWaitFor) { return countUS; } if(countUS > timeoutUS) { return -1; } countUS++; usleep(1); } } int main() { // setup out CTRL+C signal handler struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = startCommandHandler; if(sigaction(SIGINT, &sa, NULL) == -1){ print("Bad sigaction"); return -1; } // memory-map the GPIO port directly, because using sysfs is too slow to sample at 1 us int fd = open("/dev/mem", O_RDWR | O_SYNC); ulong* pinconf1 = (ulong*) mmap(NULL, 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED, fd, GPIO0_ADDR); // sample pin read int i = PIN_READ(pinconf1); printf("i=[%d]\n", i); // sample pin write PIN_WRITE(PIN_LOW); printf("After put low [%d]\n", PIN_READ(pinconf1)); PIN_WRITE(PIN_HIGH); printf("After put high [%d]\n", PIN_READ(pinconf1)); /* int val = PIN_HIGH; if(val == PIN_HIGH) { pinconf1[GPIO_DATAOUT/4] |= (1 << GPIO_PIN_NUMBER); } else if(val == PIN_LOW) { pinconf1[GPIO_DATAOUT/4] &= (0xFFFFFFFF ^ (1 << GPIO_PIN_NUMBER)); } */ //* print("CTRL+C to Trigger sensor read."); // state machine int lastState = STATE_IDLE; int state = STATE_IDLE; int nextState = STATE_IDLE; while(true) { // implement the next state if(state != nextState) { printf("[%d] -> [%d]\n", state, nextState); fflush(stdout); lastState = state; state = nextState; } // idle if(state == STATE_IDLE){ if(globalStartMeasuring == true) { nextState = STATE_COMMAND; print("\nIdle > Command"); globalStartMeasuring = false; } } // command the sensor to begin sampling if(state == STATE_COMMAND){ PIN_WRITE(PIN_LOW); printf("After put low [%d]\n", PIN_READ(pinconf1)); usleep(1100); PIN_WRITE(PIN_HIGH); nextState = STATE_RESPONSE; printf("After put high [%d]\n", PIN_READ(pinconf1)); fflush(stdout); } // wait for the sensor to respond if(state == STATE_RESPONSE){ bool validResponse = false; int us = waitForTransition(pinconf1, PIN_LOW, 600); if(us == -1){ print("Sensor response timeout"); nextState = STATE_IDLE; }else{ printf("Waited for [%d] us\n", us); fflush(stdout); // xxx KA testing nextState = STATE_IDLE; } } //usleep(1); //sleep(1); } //*/ //* PIN_INPUT(); for(int i = 0; i < 250; i++) { //cout << pinconf1[GPIO_DATAIN/4] << endl; //cout << PIN_READ(pinconf1) << endl; // get pin GPIO_PIN_NUMBER in GPIOX if(PIN_READ(pinconf1) == PIN_HIGH) { cout << "high" <<endl; } else { cout << "low" <<endl; } usleep(500000); } //*/ // ex. 0000 0010 1000 1100 0000 0001 0101 1111 1110 1110 // ---- ---- ---- ---- is RH data // ---- ---- ---- ---- is T data // ---- ---- is checksum, where checksum = RH (2 bytes) + T (2 bytes) // ex. use RH to get relative humidity // a) convert RH from binary to decimal // b) divide by 10 to get relative humidity // ex. use T to calculate temperature // a) convert T from binary to decimal // b) divide by 10 to get temperature return 0; }<commit_msg>finish state machine for sensor read<commit_after>// Purpose: Get relative humidity and temperature from A2302 sensor found at akizukidenshi.com/download/ds/aosong/AM2302.pdf #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <iostream> #include <stdio.h> #include <signal.h> #include <stdlib.h> // absolute addresses #define GPIO0_ADDR (0x44E07000) #define GPIO1_ADDR (0x4804C000) #define GPIO2_ADDR (0x481AC000) #define GPIO3_ADDR (0x481AF000) // relative addresses (from the ones above) #define OE_ADDR (0x134) #define GPIO_DATAIN (0x138) // read value of pins #define GPIO_DATAOUT (0x13C) // write value to pins #define GPIO_PIN_NUMBER (31) // ex. if we are in GPIO0, then 30 here would mean GPIO0_30, where as GPIO1 would be GPIO1_30 #define PIN_HIGH (1 << GPIO_PIN_NUMBER) #define PIN_LOW (0) #define PIN_INPUT(){ \ pinconf1[OE_ADDR/4] |= (1 << GPIO_PIN_NUMBER); \ } #define PIN_OUTPUT(){ \ pinconf1[OE_ADDR/4] &= (0xFFFFFFFF ^ (1 << GPIO_PIN_NUMBER)); \ } int PIN_READ(ulong* pinconf1){ // never do this! you can still read even when it is an PIN_OUTPUT // and if you do this, then when you write and read it will never be // what you wrote the pin to be //PIN_INPUT(); return pinconf1[GPIO_DATAIN/4] & (1 << GPIO_PIN_NUMBER); } #define PIN_WRITE(val) { \ PIN_OUTPUT(); \ if(val == PIN_HIGH) \ { \ pinconf1[GPIO_DATAOUT/4] |= (1 << GPIO_PIN_NUMBER); \ } \ else if(val == PIN_LOW) \ { \ pinconf1[GPIO_DATAOUT/4] &= (0xFFFFFFFF ^ (1 << GPIO_PIN_NUMBER)); \ } \ } // am2302 #define NUM_BITS_DATA (40) #define NUM_BITS_RH (16) #define NUM_BITS_T (16) #define NUM_BITS_SUM (8) #define CONVERSION_FACTOR (10.0) // divide by 10 // state machine #define STATE_IDLE (0) #define STATE_COMMAND (1) #define STATE_RESPONSE (2) #define STATE_DATA (3) #define STATE_CALC (4) bool globalStartMeasuring = false; // used to trigger a sensor read using namespace std; static void startCommandHandler(int sig) { globalStartMeasuring = true; } void print(char * message) { printf("%s\n", message); fflush(stdout); } // return: // returns -1 if time out is greater that "timeoutUS" microseconds // otherwise, returns the number of microseconds it took for the // pin output became the value "pinValueToWaitFor" // args: // "pinValueToWaitFor" must be either PIN_HIGH or PIN_LOW int waitForTransition(ulong *pinconf1, int pinValueToWaitFor, int timeoutUS) { PIN_INPUT(); int countUS = 0; while(true) { // xxx it may be a problem that we check for this right away, because // what if this is true beacuse its from the last clock cycle? // maybe we should wait until the pin read becomes !pinValueToWaitFor // THEN do this if(PIN_READ(pinconf1) == pinValueToWaitFor) { return countUS; } if(countUS > timeoutUS) { return -1; } countUS++; usleep(1); } } int main() { // setup CTRL+C signal handler struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = startCommandHandler; if(sigaction(SIGINT, &sa, NULL) == -1){ print("Bad sigaction"); return -1; } // memory-map the GPIO port directly, because using sysfs is too slow to sample at 1 us int fd = open("/dev/mem", O_RDWR | O_SYNC); ulong* pinconf1 = (ulong*) mmap(NULL, 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED, fd, GPIO0_ADDR); // sample pin read int i = PIN_READ(pinconf1); printf("i=[%d]\n", i); // sample pin write PIN_WRITE(PIN_LOW); printf("After put low [%d]\n", PIN_READ(pinconf1)); PIN_WRITE(PIN_HIGH); printf("After put high [%d]\n", PIN_READ(pinconf1)); /* int val = PIN_HIGH; if(val == PIN_HIGH) { pinconf1[GPIO_DATAOUT/4] |= (1 << GPIO_PIN_NUMBER); } else if(val == PIN_LOW) { pinconf1[GPIO_DATAOUT/4] &= (0xFFFFFFFF ^ (1 << GPIO_PIN_NUMBER)); } */ //* print("CTRL+C to Trigger sensor read."); // state machine int lastState = STATE_IDLE; int state = STATE_IDLE; int nextState = STATE_IDLE; int data[NUM_BITS_DATA]; while(true) { // implement the next state if(state != nextState) { printf("[%d] -> [%d]\n", state, nextState); fflush(stdout); lastState = state; state = nextState; } // idle if(state == STATE_IDLE) { if(globalStartMeasuring == true) { // clear data for(int x = 0; x < NUM_BITS_DATA; x++) { data[x] = 0; } nextState = STATE_COMMAND; print("\nIdle > Command"); globalStartMeasuring = false; } } // command the sensor to begin sampling if(state == STATE_COMMAND) { PIN_WRITE(PIN_LOW); printf("After put low [%d]\n", PIN_READ(pinconf1)); usleep(19000); PIN_WRITE(PIN_HIGH); nextState = STATE_RESPONSE; printf("After put high [%d]\n", PIN_READ(pinconf1)); fflush(stdout); } // wait for the sensor to respond if(state == STATE_RESPONSE) { // bbg waits for 20-40 us int us = waitForTransition(pinconf1, PIN_LOW, 60); if(us == -1){ print("Sensor low response timeout"); nextState = STATE_IDLE; continue; }else{ printf("Waited for [%d] us\n", us); fflush(stdout); // xxx KA testing nextState = STATE_IDLE; } // sensor pulls low for 80 us us = waitForTransition(pinconf1, PIN_HIGH, 100); if(us == -1){ print("Sensor high response timeout"); nextState = STATE_IDLE; continue; } nextState = STATE_DATA; } //* // gather the data from the sensor if(state == STATE_DATA) { // sensor stays high for 80 us int us = waitForTransition(pinconf1, PIN_LOW, 100); if(us == -1){ print("Sensor low 2 response timeout"); nextState = STATE_IDLE; continue; } int x = 0; for(x = 0; x < NUM_BITS_DATA; x++) { // sensor goes low for 50 us to indicate start of bit us = waitForTransition(pinconf1, PIN_HIGH, 60); if(us == -1){ print("Sensor startbit response timeout"); nextState = STATE_IDLE; break; } // duration of high indicates whether it is a 1 or 0 us = waitForTransition(pinconf1, PIN_LOW, 80); if(us == -1){ printf("Sensor data bit [%d] timeout\n", x); fflush(stdout); nextState = STATE_IDLE; break; } // 0 = 26 to 28 us, which we will say is < 30 us // 1 = 70 us, which we will say it > 60 us // if high-time is between 30 us and 60 us then we don't know the bit if(us < 30) { data[x] = 0; } else if(us > 60) { data[x] = 1; } else { printf("Sensor data bit [%d] for [%d] us is not distinguishable\n", x, us); fflush(stdout); nextState = STATE_IDLE; break; } } // go back to idle state if there was an issue getting one bit if(x < (NUM_BITS_DATA - 1)){ printf("Sensor data bit [%d] error. Going back to idle state\n", x, us); fflush(stdout); nextState = STATE_IDLE; continue; } // if we made it this far, then we have a full data[] to decode nextState = STATE_CALC; } //*/ // decode the data from the sensor into RH and T // ex. 0000 0010 1000 1100 0000 0001 0101 1111 1110 1110 // ---- ---- ---- ---- is RH data // ---- ---- ---- ---- is T data // ---- ---- is checksum, where checksum = RH (2 bytes) + T (2 bytes) // ex. use RH to get relative humidity // a) convert RH from binary to decimal // b) divide by 10 to get relative humidity // ex. use T to calculate temperature // a) convert T from binary to decimal // b) divide by 10 to get temperature //* if(state == STATE_CALC) { int rh = 0; int t = 0; int sum = 0; // convert binary to decimal for rh, t and sum printf("data =["); for(int x = 0; x < NUM_BITS_DATA; x++) { printf("%d,", data[x]); if(x < NUM_BITS_RH) { rh += (data[x] << (NUM_BITS_RH - x - 1)); } else if(x < NUM_BITS_T) { t += (data[x] << (NUM_BITS_T - (x - NUM_BITS_RH) - 1)); } else if(x < NUM_BITS_DATA) { sum += (data[x] << (NUM_BITS_SUM - (x - NUM_BITS_RH - NUM_BITS_T) - 1)); } } printf("]"); printf("rh = [%d]\n", rh); printf("t = [%d]\n", t); printf("sum = [%d]\n", sum); fflush(stdout); print("Calculate checksum..."); int sumCalc = (rh + t) & (0x00FF); // get only the lower 8 bits of the sum printf("sumCalc = [%d]\n", sumCalc); fflush(stdout); if(sum != sumCalc){ printf("Incorrect check sum!"); nextState = STATE_IDLE; continue; } rh = rh/CONVERSION_FACTOR; t = t/CONVERSION_FACTOR; printf("Relative Humidity = [%d] Temperature = [%d]\n", rh, t); fflush(stdout); nextState = STATE_IDLE; } //*/ //usleep(1); //sleep(1); } //*/ //* PIN_INPUT(); for(int i = 0; i < 250; i++) { //cout << pinconf1[GPIO_DATAIN/4] << endl; //cout << PIN_READ(pinconf1) << endl; // get pin GPIO_PIN_NUMBER in GPIOX if(PIN_READ(pinconf1) == PIN_HIGH) { cout << "high" <<endl; } else { cout << "low" <<endl; } usleep(500000); } //*/ return 0; }<|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow 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 <iostream> #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/Builders.h" // from @llvm-project #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/IR/PatternMatch.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Pass/PassManager.h" // from @llvm-project #include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project #include "mlir/Transforms/Passes.h" // from @llvm-project #include "tensorflow/compiler/mlir/lite/utils/validators.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/passes_detail.h" #include "tensorflow/compiler/mlir/tensorflow/utils/verification_utils.h" namespace mlir { namespace TF { namespace { #include "tensorflow/compiler/mlir/tensorflow/transforms/generated_optimize.inc" // Returns a TF Constant tensor with the passed in values. TF::ConstOp GetI64ConstantTensor(PatternRewriter &rewriter, ArrayRef<int64_t> values, Location location) { auto cst_attr = rewriter.getI64TensorAttr(values); return rewriter.create<TF::ConstOp>(location, cst_attr.getType(), cst_attr); } // Rewrites broadcast->reshape to a reshape->broadcast that reduces // the rank of the input and output of the broadcast. class SimplifyBroadcastReshape : public OpRewritePattern<BroadcastToOp> { using OpRewritePattern<BroadcastToOp>::OpRewritePattern; LogicalResult matchAndRewrite(BroadcastToOp op, PatternRewriter &rewriter) const override { // Only rewrite if the Broadcast has only one consumer. if (!op.output().hasOneUse()) return failure(); Operation *user = *op.output().getUsers().begin(); auto reshape_op = llvm::dyn_cast_or_null<ReshapeOp>(user); if (!reshape_op) return failure(); auto reshape_type = reshape_op.output().getType().cast<ShapedType>(); if (!reshape_type.hasStaticShape()) return failure(); ArrayRef<int64_t> reshape_shape = reshape_type.getShape(); auto input_type = op.input().getType().cast<ShapedType>(); auto output_type = op.output().getType().cast<ShapedType>(); if (!input_type.hasRank() || !output_type.hasRank()) return failure(); // The pattern attempts to reduce the rank of the input to BroadcastTo. // Thus, we fail to match if the consuming reshape rank is larger. ArrayRef<int64_t> input_shape = input_type.getShape(); if (reshape_shape.size() > input_shape.size()) return failure(); // Extend the input shape with leading 1s to match the broadcast shape. ArrayRef<int64_t> broadcast_shape = output_type.getShape(); SmallVector<int64_t, 4> input_shape_extended; input_shape_extended.append(broadcast_shape.size() - input_shape.size(), 1); input_shape_extended.append(input_shape.begin(), input_shape.end()); // Collect non-unit dims and corresponding dim in the input shape. SmallVector<int64_t, 4> input_carryover_dims; SmallVector<int64_t, 4> non_unit_dims; for (int i = 0; i < input_shape_extended.size(); i++) { int64_t dim = broadcast_shape[i]; if (dim != 1) { non_unit_dims.push_back(dim); input_carryover_dims.push_back(input_shape_extended[i]); } } // If the reshape rank is less than the number of non-unit dimensions // of the broadcast, then the reshape collapses non-unit dimensions. // TODO(rahulsp) : Handle this case with more careful checks. if (reshape_shape.size() < non_unit_dims.size()) return failure(); SmallVector<int64_t, 4> old_reshape_non_unit_dims; SmallVector<int64_t, 4> new_reshape_dims; int new_reshape_dim_idx = 0; for (int64_t dim : reshape_shape) { int new_reshape_dim = 1; if (dim != 1) { old_reshape_non_unit_dims.push_back(dim); if (new_reshape_dim_idx < input_carryover_dims.size()) { new_reshape_dim = input_carryover_dims[new_reshape_dim_idx]; new_reshape_dim_idx++; } } new_reshape_dims.push_back(new_reshape_dim); } if (non_unit_dims != old_reshape_non_unit_dims) return failure(); if (failed(VerifyShapeOfReshapeOp(new_reshape_dims))) return failure(); Type el_ty = getElementTypeOrSelf(op.getType()); TF::ConstOp new_reshape_shape = GetI64ConstantTensor( rewriter, ArrayRef<int64_t>(new_reshape_dims), op.getLoc()); auto new_reshape_type = RankedTensorType::get(new_reshape_dims, el_ty); ReshapeOp new_reshape = rewriter.create<ReshapeOp>(new_reshape_shape.getLoc(), new_reshape_type, op.input(), new_reshape_shape); TF::ConstOp new_broadcast_shape = GetI64ConstantTensor(rewriter, reshape_shape, op.getLoc()); rewriter.replaceOpWithNewOp<BroadcastToOp>( reshape_op, reshape_op.output().getType(), new_reshape, new_broadcast_shape); return success(); } }; // Canonicalize operations in functions. struct TensorFlowOptimizePass : public TensorFlowOptimizePassBase<TensorFlowOptimizePass> { void runOnFunction() override { OwningRewritePatternList patterns(&getContext()); auto func = getFunction(); populateWithGenerated(patterns); patterns.insert<SimplifyBroadcastReshape>(&getContext()); (void)applyPatternsAndFoldGreedily(func, std::move(patterns)); } }; } // namespace void CreateTFStandardPipeline(OpPassManager &pm, const StandardPipelineOptions &options) { OpPassManager &func_pm = pm.nest<FuncOp>(); // First operates on the executor dialect: // - remove dead islands. // - fuse islands as much as possible. // - materialize the eventual "pass-through" ops by inlining their content. func_pm.addPass(tf_executor::CreateTFExecutorGraphPruningPass()); func_pm.addPass(tf_executor::CreateTFExecutorIslandCoarseningPass()); func_pm.addPass(CreateMaterializePassthroughOpPass()); if (options.form_clusters) func_pm.addPass(TFDevice::CreateClusterFormationPass()); // Hopefully there is a single island left, or there wasn't any to begin with. // We now run the optimizer which operates mostly inside islands. func_pm.addPass(createCanonicalizerPass()); pm.addPass(CreateTFShapeInferencePass()); if (options.enable_inliner) { pm.addPass(createInlinerPass()); } pm.addPass(createSymbolDCEPass()); pm.addNestedPass<FuncOp>(CreateTFOptimizePass()); pm.addNestedPass<FuncOp>(createCSEPass()); } std::unique_ptr<OperationPass<FuncOp>> CreateTFOptimizePass() { return std::make_unique<TensorFlowOptimizePass>(); } // Registers a pipeline builder function for the default canonicalize/optimizer. static mlir::PassPipelineRegistration<StandardPipelineOptions> pipeline( "tf-standard-pipeline", "Run all the passes involved in transforming/optimizing the graph after " "importing into MLIR, without any target specialization.", CreateTFStandardPipeline); } // namespace TF } // namespace mlir <commit_msg>Separate out initialize from run in optimize pass<commit_after>/* Copyright 2019 The TensorFlow 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 <iostream> #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/Builders.h" // from @llvm-project #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/IR/PatternMatch.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Pass/PassManager.h" // from @llvm-project #include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project #include "mlir/Transforms/Passes.h" // from @llvm-project #include "tensorflow/compiler/mlir/lite/utils/validators.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/passes_detail.h" #include "tensorflow/compiler/mlir/tensorflow/utils/verification_utils.h" namespace mlir { namespace TF { namespace { #include "tensorflow/compiler/mlir/tensorflow/transforms/generated_optimize.inc" // Returns a TF Constant tensor with the passed in values. TF::ConstOp GetI64ConstantTensor(PatternRewriter &rewriter, ArrayRef<int64_t> values, Location location) { auto cst_attr = rewriter.getI64TensorAttr(values); return rewriter.create<TF::ConstOp>(location, cst_attr.getType(), cst_attr); } // Rewrites broadcast->reshape to a reshape->broadcast that reduces // the rank of the input and output of the broadcast. class SimplifyBroadcastReshape : public OpRewritePattern<BroadcastToOp> { using OpRewritePattern<BroadcastToOp>::OpRewritePattern; LogicalResult matchAndRewrite(BroadcastToOp op, PatternRewriter &rewriter) const override { // Only rewrite if the Broadcast has only one consumer. if (!op.output().hasOneUse()) return failure(); Operation *user = *op.output().getUsers().begin(); auto reshape_op = llvm::dyn_cast_or_null<ReshapeOp>(user); if (!reshape_op) return failure(); auto reshape_type = reshape_op.output().getType().cast<ShapedType>(); if (!reshape_type.hasStaticShape()) return failure(); ArrayRef<int64_t> reshape_shape = reshape_type.getShape(); auto input_type = op.input().getType().cast<ShapedType>(); auto output_type = op.output().getType().cast<ShapedType>(); if (!input_type.hasRank() || !output_type.hasRank()) return failure(); // The pattern attempts to reduce the rank of the input to BroadcastTo. // Thus, we fail to match if the consuming reshape rank is larger. ArrayRef<int64_t> input_shape = input_type.getShape(); if (reshape_shape.size() > input_shape.size()) return failure(); // Extend the input shape with leading 1s to match the broadcast shape. ArrayRef<int64_t> broadcast_shape = output_type.getShape(); SmallVector<int64_t, 4> input_shape_extended; input_shape_extended.append(broadcast_shape.size() - input_shape.size(), 1); input_shape_extended.append(input_shape.begin(), input_shape.end()); // Collect non-unit dims and corresponding dim in the input shape. SmallVector<int64_t, 4> input_carryover_dims; SmallVector<int64_t, 4> non_unit_dims; for (int i = 0; i < input_shape_extended.size(); i++) { int64_t dim = broadcast_shape[i]; if (dim != 1) { non_unit_dims.push_back(dim); input_carryover_dims.push_back(input_shape_extended[i]); } } // If the reshape rank is less than the number of non-unit dimensions // of the broadcast, then the reshape collapses non-unit dimensions. // TODO(rahulsp) : Handle this case with more careful checks. if (reshape_shape.size() < non_unit_dims.size()) return failure(); SmallVector<int64_t, 4> old_reshape_non_unit_dims; SmallVector<int64_t, 4> new_reshape_dims; int new_reshape_dim_idx = 0; for (int64_t dim : reshape_shape) { int new_reshape_dim = 1; if (dim != 1) { old_reshape_non_unit_dims.push_back(dim); if (new_reshape_dim_idx < input_carryover_dims.size()) { new_reshape_dim = input_carryover_dims[new_reshape_dim_idx]; new_reshape_dim_idx++; } } new_reshape_dims.push_back(new_reshape_dim); } if (non_unit_dims != old_reshape_non_unit_dims) return failure(); if (failed(VerifyShapeOfReshapeOp(new_reshape_dims))) return failure(); Type el_ty = getElementTypeOrSelf(op.getType()); TF::ConstOp new_reshape_shape = GetI64ConstantTensor( rewriter, ArrayRef<int64_t>(new_reshape_dims), op.getLoc()); auto new_reshape_type = RankedTensorType::get(new_reshape_dims, el_ty); ReshapeOp new_reshape = rewriter.create<ReshapeOp>(new_reshape_shape.getLoc(), new_reshape_type, op.input(), new_reshape_shape); TF::ConstOp new_broadcast_shape = GetI64ConstantTensor(rewriter, reshape_shape, op.getLoc()); rewriter.replaceOpWithNewOp<BroadcastToOp>( reshape_op, reshape_op.output().getType(), new_reshape, new_broadcast_shape); return success(); } }; // Canonicalize operations in functions. struct TensorFlowOptimizePass : public TensorFlowOptimizePassBase<TensorFlowOptimizePass> { LogicalResult initialize(MLIRContext *context) override { OwningRewritePatternList pattern_list(context); populateWithGenerated(pattern_list); pattern_list.insert<SimplifyBroadcastReshape>(context); patterns = std::move(pattern_list); return success(); } void runOnFunction() override { auto func = getFunction(); if (failed(applyPatternsAndFoldGreedily(func, patterns))) signalPassFailure(); } FrozenRewritePatternSet patterns; }; } // namespace void CreateTFStandardPipeline(OpPassManager &pm, const StandardPipelineOptions &options) { OpPassManager &func_pm = pm.nest<FuncOp>(); // First operates on the executor dialect: // - remove dead islands. // - fuse islands as much as possible. // - materialize the eventual "pass-through" ops by inlining their content. func_pm.addPass(tf_executor::CreateTFExecutorGraphPruningPass()); func_pm.addPass(tf_executor::CreateTFExecutorIslandCoarseningPass()); func_pm.addPass(CreateMaterializePassthroughOpPass()); if (options.form_clusters) func_pm.addPass(TFDevice::CreateClusterFormationPass()); // Hopefully there is a single island left, or there wasn't any to begin with. // We now run the optimizer which operates mostly inside islands. func_pm.addPass(createCanonicalizerPass()); pm.addPass(CreateTFShapeInferencePass()); if (options.enable_inliner) { pm.addPass(createInlinerPass()); } pm.addPass(createSymbolDCEPass()); pm.addNestedPass<FuncOp>(CreateTFOptimizePass()); pm.addNestedPass<FuncOp>(createCSEPass()); } std::unique_ptr<OperationPass<FuncOp>> CreateTFOptimizePass() { return std::make_unique<TensorFlowOptimizePass>(); } // Registers a pipeline builder function for the default canonicalize/optimizer. static mlir::PassPipelineRegistration<StandardPipelineOptions> pipeline( "tf-standard-pipeline", "Run all the passes involved in transforming/optimizing the graph after " "importing into MLIR, without any target specialization.", CreateTFStandardPipeline); } // namespace TF } // namespace mlir <|endoftext|>
<commit_before>/* Copyright 2021 The TensorFlow 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 "tensorflow/compiler/xla/service/gpu/nvptx_compiler.h" #include "tensorflow/compiler/xla/service/buffer_assignment.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_parser.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" #include "tensorflow/compiler/xla/util.h" namespace xla { namespace gpu { using NVPTXCompilerTest = HloTestBase; TEST_F(NVPTXCompilerTest, AllReducePerformedInplace) { const absl::string_view hlo_string = R"( HloModule Module, input_output_alias={ {}: (0, {}, may-alias) } summit { lhs = f32[] parameter(0) rhs = f32[] parameter(1) ROOT add = f32[] add(lhs, rhs) } ENTRY entry { param0 = f32[128] parameter(0) ROOT allreduce = f32[128] all-reduce(param0), replica_groups={}, to_apply=summit } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); NVPTXCompiler compiler; TF_ASSERT_OK_AND_ASSIGN(auto buffer_assignment, compiler.AssignBuffers(module.get())); HloInstruction* all_reduce = module->entry_computation()->root_instruction(); EXPECT_EQ( buffer_assignment->GetInstructionAllocation(all_reduce, {}), buffer_assignment->GetInstructionAllocation(all_reduce->operand(0), {})); } TEST_F(NVPTXCompilerTest, AllReducePerformedInplaceTwoOperands) { const absl::string_view hlo_string = R"( HloModule Module, input_output_alias={ {0}: (0, {}, may-alias), {1}: (1, {}, may-alias) } summit { lhs = f32[] parameter(0) rhs = f32[] parameter(1) ROOT add = f32[] add(lhs, rhs) } ENTRY entry { param0 = f32[128] parameter(0) param1 = f32[128] parameter(1) ROOT allreduce = (f32[128], f32[128]) all-reduce(param0, param1), replica_groups={}, to_apply=summit } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); NVPTXCompiler compiler; TF_ASSERT_OK_AND_ASSIGN(auto buffer_assignment, compiler.AssignBuffers(module.get())); HloInstruction* all_reduce = module->entry_computation()->root_instruction(); EXPECT_EQ( buffer_assignment->GetInstructionAllocation(all_reduce, {0}), buffer_assignment->GetInstructionAllocation(all_reduce->operand(0), {})); EXPECT_EQ( buffer_assignment->GetInstructionAllocation(all_reduce, {1}), buffer_assignment->GetInstructionAllocation(all_reduce->operand(1), {})); } } // namespace gpu } // namespace xla <commit_msg>[XLA:GPU] Fix in-place all-reduce test.<commit_after>/* Copyright 2021 The TensorFlow 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 "tensorflow/compiler/xla/service/gpu/nvptx_compiler.h" #include "tensorflow/compiler/xla/service/buffer_assignment.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_parser.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" #include "tensorflow/compiler/xla/util.h" namespace xla { namespace gpu { using NVPTXCompilerTest = HloTestBase; TEST_F(NVPTXCompilerTest, AllReducePerformedInplace) { const absl::string_view hlo_string = R"( HloModule Module, input_output_alias={ {}: (0, {}, may-alias) } summit { lhs = f32[] parameter(0) rhs = f32[] parameter(1) ROOT add = f32[] add(lhs, rhs) } ENTRY entry { param0 = f32[128] parameter(0) ROOT allreduce = f32[128] all-reduce(param0), replica_groups={}, to_apply=summit } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); NVPTXCompiler compiler; TF_ASSERT_OK_AND_ASSIGN(auto buffer_assignment, compiler.AssignBuffers(module.get())); HloInstruction* all_reduce = module->entry_computation()->root_instruction(); EXPECT_TRUE(buffer_assignment->SharesTopLevelSlice(all_reduce, all_reduce->operand(0))); } TEST_F(NVPTXCompilerTest, AllReducePerformedInplaceTwoOperands) { const absl::string_view hlo_string = R"( HloModule Module, input_output_alias={ {0}: (0, {}, may-alias), {1}: (1, {}, may-alias) } summit { lhs = f32[] parameter(0) rhs = f32[] parameter(1) ROOT add = f32[] add(lhs, rhs) } ENTRY entry { param0 = f32[128] parameter(0) param1 = f32[128] parameter(1) ROOT allreduce = (f32[128], f32[128]) all-reduce(param0, param1), replica_groups={}, to_apply=summit } )"; TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<HloModule> module, ParseAndReturnVerifiedModule(hlo_string)); NVPTXCompiler compiler; TF_ASSERT_OK_AND_ASSIGN(auto buffer_assignment, compiler.AssignBuffers(module.get())); HloInstruction* all_reduce = module->entry_computation()->root_instruction(); EXPECT_TRUE(buffer_assignment->SharesSliceAtIndex( all_reduce, {0}, all_reduce->operand(0), {})); EXPECT_TRUE(buffer_assignment->SharesSliceAtIndex( all_reduce, {1}, all_reduce->operand(1), {})); } } // namespace gpu } // namespace xla <|endoftext|>
<commit_before>// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2014 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "CTaskEnum.h" const CEnumAnnotation< std::string, CTaskEnum::Task > CTaskEnum::TaskName( { "Steady-State", "Time-Course", "Scan", "Elementary Flux Modes", "Optimization", "Parameter Estimation", "Metabolic Control Analysis", "Lyapunov Exponents", "Time Scale Separation Analysis", "Sensitivities", "Moieties", "Cross Section", "Linear Noise Approximation", "Analytics", "not specified" }); const CEnumAnnotation< std::string, CTaskEnum::Task > CTaskEnum::TaskXML( { "steadyState", "timeCourse", "scan", "fluxMode", "optimization", "parameterFitting", "metabolicControlAnalysis", "lyapunovExponents", "timeScaleSeparationAnalysis", "sensitivities", "moieties", "crosssection", "linearNoiseApproximation", "analytics", "unset" }); const CEnumAnnotation< std::string, CTaskEnum::Method > CTaskEnum::MethodName( { "Not set", "Random Search", "Random Search (PVM)", "Simulated Annealing", "Corana Random Walk", "Differential Evolution", "Scatter Search", "Genetic Algorithm", "Evolutionary Programming", "Steepest Descent", "Hybrid GA/SA", "Genetic Algorithm SR", "Hooke & Jeeves", "Levenberg - Marquardt", "NL2SOL", "Nelder - Mead", "Evolution Strategy (SRES)", "Current Solution Statistics", "Particle Swarm", "Praxis", "Truncated Newton", "Enhanced Newton", "Deterministic (LSODA)", "Deterministic (LSODA2)", "Stochastic (Direct method)", "Stochastic (Gibson + Bruck)", "Stochastic (\xcf\x84-Leap)", "Stochastic (Adaptive SSA/\xcf\x84-Leap)", "Hybrid (Runge-Kutta)", "Hybrid (LSODA)", "Hybrid (RK-45)", "Hybrid (DSA-LSODAR)", "Stochastic Runge Kutta (RI5)", "ILDM (LSODA,Deuflhard)", "ILDM (LSODA,Modified)", "CSP (LSODA)", "MCA Method (Reder)", "Scan Framework", "Wolf Method", "Sensitivities Method", #ifdef COPASI_SSA "Stoichiometric Stability Analysis", #endif // COPASI_SSA "EFM Algorithm", "Bit Pattern Tree Algorithm", "Bit Pattern Algorithm", "Householder Reduction", "Cross Section Finder", "Linear Noise Approximation", "Analytics Finder" }); const CEnumAnnotation< std::string, CTaskEnum::Method > CTaskEnum::MethodXML( { "NotSet", "RandomSearch", "RandomSearch(PVM)", "SimulatedAnnealing", "CoranaRandomWalk", "DifferentialEvolution", "ScatterSearch", "GeneticAlgorithm", "EvolutionaryProgram", "SteepestDescent", "HybridGASA", "GeneticAlgorithmSR", "HookeJeeves", "LevenbergMarquardt", "NL2SOL", "NelderMead", "EvolutionaryStrategySR", "CurrentSolutionStatistics", "ParticleSwarm", "Praxis", "TruncatedNewton", "EnhancedNewton", "Deterministic(LSODA)", "Deterministic(LSODA2)", "Stochastic", "DirectMethod", "TauLeap", "AdaptiveSA", "Hybrid", "Hybrid (LSODA)", "Hybrid (DSA-ODE45)", "Hybrid (DSA-LSODAR)", "Stochastic Runge Kutta (RI5)", "TimeScaleSeparation(ILDM,Deuflhard)", "TimeScaleSeparation(ILDM,Modified)", "TimeScaleSeparation(CSP)", "MCAMethod(Reder)", "ScanFramework", "WolfMethod", "SensitivitiesMethod", #ifdef COPASI_SSA "StoichiometricStabilityAnalysis", #endif // COPASI_SSA "EFMAlgorithm", "EFMBitPatternTreeMethod", "EFMBitPatternMethod", "Householder", "crossSectionMethod", "LinearNoiseApproximation", "analyticsMethod" }); <commit_msg>Renamed the stochastic differential equation solver.<commit_after>// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2014 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "CTaskEnum.h" const CEnumAnnotation< std::string, CTaskEnum::Task > CTaskEnum::TaskName( { "Steady-State", "Time-Course", "Scan", "Elementary Flux Modes", "Optimization", "Parameter Estimation", "Metabolic Control Analysis", "Lyapunov Exponents", "Time Scale Separation Analysis", "Sensitivities", "Moieties", "Cross Section", "Linear Noise Approximation", "Analytics", "not specified" }); const CEnumAnnotation< std::string, CTaskEnum::Task > CTaskEnum::TaskXML( { "steadyState", "timeCourse", "scan", "fluxMode", "optimization", "parameterFitting", "metabolicControlAnalysis", "lyapunovExponents", "timeScaleSeparationAnalysis", "sensitivities", "moieties", "crosssection", "linearNoiseApproximation", "analytics", "unset" }); const CEnumAnnotation< std::string, CTaskEnum::Method > CTaskEnum::MethodName( { "Not set", "Random Search", "Random Search (PVM)", "Simulated Annealing", "Corana Random Walk", "Differential Evolution", "Scatter Search", "Genetic Algorithm", "Evolutionary Programming", "Steepest Descent", "Hybrid GA/SA", "Genetic Algorithm SR", "Hooke & Jeeves", "Levenberg - Marquardt", "NL2SOL", "Nelder - Mead", "Evolution Strategy (SRES)", "Current Solution Statistics", "Particle Swarm", "Praxis", "Truncated Newton", "Enhanced Newton", "Deterministic (LSODA)", "Deterministic (LSODA2)", "Stochastic (Direct method)", "Stochastic (Gibson + Bruck)", "Stochastic (\xcf\x84-Leap)", "Stochastic (Adaptive SSA/\xcf\x84-Leap)", "Hybrid (Runge-Kutta)", "Hybrid (LSODA)", "Hybrid (RK-45)", "Hybrid (DSA-LSODAR)", "SDE Solver (RI5)", "ILDM (LSODA,Deuflhard)", "ILDM (LSODA,Modified)", "CSP (LSODA)", "MCA Method (Reder)", "Scan Framework", "Wolf Method", "Sensitivities Method", #ifdef COPASI_SSA "Stoichiometric Stability Analysis", #endif // COPASI_SSA "EFM Algorithm", "Bit Pattern Tree Algorithm", "Bit Pattern Algorithm", "Householder Reduction", "Cross Section Finder", "Linear Noise Approximation", "Analytics Finder" }); const CEnumAnnotation< std::string, CTaskEnum::Method > CTaskEnum::MethodXML( { "NotSet", "RandomSearch", "RandomSearch(PVM)", "SimulatedAnnealing", "CoranaRandomWalk", "DifferentialEvolution", "ScatterSearch", "GeneticAlgorithm", "EvolutionaryProgram", "SteepestDescent", "HybridGASA", "GeneticAlgorithmSR", "HookeJeeves", "LevenbergMarquardt", "NL2SOL", "NelderMead", "EvolutionaryStrategySR", "CurrentSolutionStatistics", "ParticleSwarm", "Praxis", "TruncatedNewton", "EnhancedNewton", "Deterministic(LSODA)", "Deterministic(LSODA2)", "Stochastic", "DirectMethod", "TauLeap", "AdaptiveSA", "Hybrid", "Hybrid (LSODA)", "Hybrid (DSA-ODE45)", "Hybrid (DSA-LSODAR)", "Stochastic Runge Kutta (RI5)", "TimeScaleSeparation(ILDM,Deuflhard)", "TimeScaleSeparation(ILDM,Modified)", "TimeScaleSeparation(CSP)", "MCAMethod(Reder)", "ScanFramework", "WolfMethod", "SensitivitiesMethod", #ifdef COPASI_SSA "StoichiometricStabilityAnalysis", #endif // COPASI_SSA "EFMAlgorithm", "EFMBitPatternTreeMethod", "EFMBitPatternMethod", "Householder", "crossSectionMethod", "LinearNoiseApproximation", "analyticsMethod" }); <|endoftext|>
<commit_before>/** * @file april_tags.cpp * @brief Example application for April tags library * @author: Michael Kaess * */ #include <cstring> #include "opencv2/opencv.hpp" #include "AprilTags/TagDetector.h" #include "AprilTags/Tag36h11.h" using namespace std; const char* window_name = "apriltags_demo"; // draw April tag detection on actual image void draw_detection(cv::Mat& image, const AprilTags::TagDetection& detection) { // use corner points detected by line intersection std::pair<float, float> p1 = detection.p[0]; std::pair<float, float> p2 = detection.p[1]; std::pair<float, float> p3 = detection.p[2]; std::pair<float, float> p4 = detection.p[3]; // plot outline cv::line(image, cv::Point2f(p1.first, p1.second), cv::Point2f(p2.first, p2.second), cv::Scalar(255,0,0,0) ); cv::line(image, cv::Point2f(p2.first, p2.second), cv::Point2f(p3.first, p3.second), cv::Scalar(0,255,0,0) ); cv::line(image, cv::Point2f(p3.first, p3.second), cv::Point2f(p4.first, p4.second), cv::Scalar(0,0,255,0) ); cv::line(image, cv::Point2f(p4.first, p4.second), cv::Point2f(p1.first, p1.second), cv::Scalar(255,0,255,0) ); // mark center cv::circle(image, cv::Point2f(detection.cxy.first, detection.cxy.second), 8, cv::Scalar(0,0,255,0), 2); // print ID std::ostringstream strSt; strSt << "#" << detection.id; cv::putText(image, strSt.str(), cv::Point2f(detection.cxy.first + 10, detection.cxy.second + 10), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(0,0,255)); } int main(int argc, char* argv[]) { int device_id; if (argc==1) { device_id = 0; } else { device_id = atoi(argv[1]); } // find any available camera (laptop camera, web cam etc) cv::VideoCapture cap(device_id); if(!cap.isOpened()) { cerr << "ERROR: Can't find video device " << device_id << "\n"; return -1; } if (cap.get(CV_CAP_PROP_FRAME_WIDTH) < 640) { // some cams provide a small image by default, try to get a larger one cap.set(CV_CAP_PROP_FRAME_WIDTH, 640); cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480); } // determines which family of April tags is detected AprilTags::TagDetector tag_detector(AprilTags::tagCodes36h11); cv::namedWindow(window_name, 1); cv::Mat color; cv::Mat gray; while (true) { // capture frame cap >> color; cv::cvtColor(color, gray, CV_BGR2GRAY); std::vector<AprilTags::TagDetection> detections = tag_detector.extractTags(gray); // print out detections cout << detections.size() << " tags detected:" << endl; for (int i=0; i<detections.size(); i++) { cout << " Id: " << detections[i].id << " -- " << " Hamming distance: " << detections[i].hammingDistance << endl; // also highlight in the image draw_detection(color, detections[i]); // recovering the relative pose requires camera calibration; const double tag_size = 0.166; // real side length in meters of square black frame const double fx = 600; // camera focal length const double fy = 600; const double px = gray.cols/2; // camera principal point const double py = gray.rows/2; Eigen::Matrix4d T = detections[i].getRelativeTransform(tag_size, fx, fy, px, py); // note that for SLAM application it is better to use // reprojection error of corner points, as the noise in this // relative pose is very non-Gaussian; see iSAM source code for // suitable factors } imshow(window_name, color); // exit if any key pressed if (cv::waitKey(10) >= 0) break; } return 0; } <commit_msg>printing fps; command line options for resolution and disabling graphics<commit_after>/** * @file april_tags.cpp * @brief Example application for April tags library * @author: Michael Kaess * */ #include <iostream> #include <cstring> const std::string usage = "\n" "Usage:\n" " apriltags_demo [OPTION...] [deviceID]\n" "\n" "Options:\n" " -h -? show help options\n" " -d disable graphics\n" "\n"; const std::string intro = "\n" "April tags test code\n" "(C) 2012-2013 Massachusetts Institute of Technology\n" "Michael Kaess\n" "\n"; #include <sys/time.h> #include "opencv2/opencv.hpp" #include "AprilTags/TagDetector.h" #include "AprilTags/Tag36h11.h" // for getopt / command line options processing #include <unistd.h> extern int optind; extern char *optarg; using namespace std; const char* window_name = "apriltags_demo"; // draw April tag detection on actual image void draw_detection(cv::Mat& image, const AprilTags::TagDetection& detection) { // use corner points detected by line intersection std::pair<float, float> p1 = detection.p[0]; std::pair<float, float> p2 = detection.p[1]; std::pair<float, float> p3 = detection.p[2]; std::pair<float, float> p4 = detection.p[3]; // plot outline cv::line(image, cv::Point2f(p1.first, p1.second), cv::Point2f(p2.first, p2.second), cv::Scalar(255,0,0,0) ); cv::line(image, cv::Point2f(p2.first, p2.second), cv::Point2f(p3.first, p3.second), cv::Scalar(0,255,0,0) ); cv::line(image, cv::Point2f(p3.first, p3.second), cv::Point2f(p4.first, p4.second), cv::Scalar(0,0,255,0) ); cv::line(image, cv::Point2f(p4.first, p4.second), cv::Point2f(p1.first, p1.second), cv::Scalar(255,0,255,0) ); // mark center cv::circle(image, cv::Point2f(detection.cxy.first, detection.cxy.second), 8, cv::Scalar(0,0,255,0), 2); // print ID std::ostringstream strSt; strSt << "#" << detection.id; cv::putText(image, strSt.str(), cv::Point2f(detection.cxy.first + 10, detection.cxy.second + 10), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(0,0,255)); } double tic() { struct timeval t; gettimeofday(&t, NULL); return ((double)t.tv_sec + ((double)t.tv_usec)/1000000.); } int main(int argc, char* argv[]) { bool draw = true; int width = 640; int height = 480; int c; while ((c = getopt(argc, argv, ":h?dW:H:")) != -1) { // Each option character has to be in the string in getopt(); // the first colon changes the error character from '?' to ':'; // a colon after an option means that there is an extra // parameter to this option; 'W' is a reserved character switch (c) { case 'h': case '?': cout << intro; cout << usage; exit(0); break; case 'd': draw = false; break; case 'W': width = atoi(optarg); break; case 'H': height = atoi(optarg); break; case ':': // unknown option, from getopt cout << intro; cout << usage; exit(1); break; } } int device_id = 0; if (argc == optind + 1) { device_id = atoi(argv[optind]); } // find any available camera (laptop camera, web cam etc) cv::VideoCapture cap(device_id); if(!cap.isOpened()) { cerr << "ERROR: Can't find video device " << device_id << "\n"; return -1; } // if (cap.get(CV_CAP_PROP_FRAME_WIDTH) < 640) { // some cams provide a small image by default, try to get a larger one cap.set(CV_CAP_PROP_FRAME_WIDTH, width); cap.set(CV_CAP_PROP_FRAME_HEIGHT, height); // } // determines which family of April tags is detected AprilTags::TagDetector tag_detector(AprilTags::tagCodes36h11); if (draw) { cv::namedWindow(window_name, 1); } cv::Mat color; cv::Mat gray; int frame = 0; double last_t = tic(); while (true) { // capture frame // if (frame==0) cap >> color; cv::cvtColor(color, gray, CV_BGR2GRAY); std::vector<AprilTags::TagDetection> detections = tag_detector.extractTags(gray); // print out detections cout << detections.size() << " tags detected:" << endl; for (int i=0; i<detections.size(); i++) { cout << " Id: " << detections[i].id << " -- " << " Hamming distance: " << detections[i].hammingDistance << endl; if (draw) { // also highlight in the image draw_detection(color, detections[i]); } // recovering the relative pose requires camera calibration; const double tag_size = 0.166; // real side length in meters of square black frame const double fx = 600; // camera focal length const double fy = 600; const double px = gray.cols/2; // camera principal point const double py = gray.rows/2; Eigen::Matrix4d T = detections[i].getRelativeTransform(tag_size, fx, fy, px, py); // note that for SLAM application it is better to use // reprojection error of corner points, as the noise in this // relative pose is very non-Gaussian; see iSAM source code for // suitable factors } if (draw) { imshow(window_name, color); } frame++; if (frame % 10 == 0) { double t = tic(); cout << " " << 10./(t-last_t) << " fps" << endl; last_t = t; } // exit if any key pressed if (cv::waitKey(1) >= 0) break; } return 0; } <|endoftext|>
<commit_before> /** * Copyright (C) 2016, Canonical Ltd. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // #define BUILD_FOR_BUNDLE #include <QCommandLineParser> #include <QFile> #include <QGuiApplication> #include <QProcess> #include <QQuickView> #include <QStandardPaths> #include <QTimer> #include <QUrl> #include "attachedproperties.h" #include "reactitem.h" #include "rootview.h" #include "utilities.h" #ifdef BUILD_FOR_BUNDLE QStringList consoleOutputStrings; bool ubuntuServerStarted = false; #endif const int MAIN_WINDOW_WIDTH = 1024; const int MAIN_WINDOW_HEIGHT = 768; // TODO: some way to change while running class ReactNativeProperties : public QObject { Q_OBJECT Q_PROPERTY(bool liveReload READ liveReload WRITE setLiveReload NOTIFY liveReloadChanged) Q_PROPERTY(QUrl codeLocation READ codeLocation WRITE setCodeLocation NOTIFY codeLocationChanged) Q_PROPERTY(QString pluginsPath READ pluginsPath WRITE setPluginsPath NOTIFY pluginsPathChanged) Q_PROPERTY( QString executor READ executor WRITE setExecutor NOTIFY executorChanged) public: ReactNativeProperties(QObject *parent = 0) : QObject(parent) { m_codeLocation = m_packagerTemplate.arg(m_packagerHost).arg(m_packagerPort); } bool liveReload() const { return m_liveReload; } void setLiveReload(bool liveReload) { if (m_liveReload == liveReload) return; m_liveReload = liveReload; Q_EMIT liveReloadChanged(); } QUrl codeLocation() const { return m_codeLocation; } void setCodeLocation(const QUrl &codeLocation) { if (m_codeLocation == codeLocation) return; m_codeLocation = codeLocation; Q_EMIT codeLocationChanged(); } QString pluginsPath() const { return m_pluginsPath; } void setPluginsPath(const QString &pluginsPath) { if (m_pluginsPath == pluginsPath) return; m_pluginsPath = pluginsPath; Q_EMIT pluginsPathChanged(); } QString executor() const { return m_executor; } void setExecutor(const QString &executor) { if (m_executor == executor) return; m_executor = executor; Q_EMIT executorChanged(); } QString packagerHost() const { return m_packagerHost; } void setPackagerHost(const QString &packagerHost) { if (m_packagerHost == packagerHost) return; m_packagerHost = packagerHost; setCodeLocation(m_packagerTemplate.arg(m_packagerHost).arg(m_packagerPort)); } QString packagerPort() const { return m_packagerPort; } void setPackagerPort(const QString &packagerPort) { if (m_packagerPort == packagerPort) return; m_packagerPort = packagerPort; setCodeLocation(m_packagerTemplate.arg(m_packagerHost).arg(m_packagerPort)); } void setLocalSource(const QString &source) { if (m_localSource == source) return; // overrides packager* if (source.startsWith("file:")) { setCodeLocation(source); } else { QFileInfo fi(source); if (!fi.exists()) { qWarning() << "Attempt to set non-existent local source file"; return; } setCodeLocation(QUrl::fromLocalFile(fi.absoluteFilePath())); setLiveReload(false); } } Q_SIGNALS: void liveReloadChanged(); void codeLocationChanged(); void pluginsPathChanged(); void executorChanged(); private: bool m_liveReload = false; QString m_packagerHost = "localhost"; QString m_packagerPort = "8081"; QString m_localSource; QString m_packagerTemplate = "http://%1:%2/index.desktop.bundle?platform=desktop&dev=true"; QUrl m_codeLocation; QString m_pluginsPath; #ifdef BUILD_FOR_BUNDLE QString m_executor = "RemoteServerConnection"; #else QString m_executor = "LocalServerConnection"; #endif }; #ifdef BUILD_FOR_BUNDLE void runUbuntuServer(); void saveMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg); void writeLogsToFile(); #endif int main(int argc, char **argv) { QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); Q_INIT_RESOURCE(react_resources); #ifdef BUILD_FOR_BUNDLE qInstallMessageHandler(saveMessage); runUbuntuServer(); #endif QQuickView view; ReactNativeProperties *rnp = new ReactNativeProperties(&view); #ifdef BUILD_FOR_BUNDLE rnp->setCodeLocation("file:" + QGuiApplication::applicationDirPath() + "/assets"); #endif utilities::registerReactTypes(); QCommandLineParser p; p.setApplicationDescription("React Native host application"); p.addHelpOption(); p.addOptions({ {{"R", "live-reload"}, "Enable live reload."}, {{"H", "host"}, "Set packager host address.", rnp->packagerHost()}, {{"P", "port"}, "Set packager port number.", rnp->packagerPort()}, {{"L", "local"}, "Set path to the local packaged source", "not set"}, {{"M", "plugins-path"}, "Set path to node modules", "./plugins"}, {{"E", "executor"}, "Set Javascript executor", rnp->executor()}, }); p.process(app); rnp->setLiveReload(p.isSet("live-reload")); if (p.isSet("host")) rnp->setPackagerHost(p.value("host")); if (p.isSet("port")) rnp->setPackagerPort(p.value("port")); if (p.isSet("local")) rnp->setLocalSource(p.value("local")); if (p.isSet("plugins-path")) rnp->setPluginsPath(p.value("plugins-path")); if (p.isSet("executor")) rnp->setExecutor(p.value("executor")); view.rootContext()->setContextProperty("ReactNativeProperties", rnp); view.setSource(QUrl("qrc:///main.qml")); view.setResizeMode(QQuickView::SizeRootObjectToView); view.resize(MAIN_WINDOW_WIDTH, MAIN_WINDOW_HEIGHT); view.show(); #ifdef BUILD_FOR_BUNDLE QTimer t; t.setInterval(500); QObject::connect(&t, &QTimer::timeout, [=]() { writeLogsToFile(); }); t.start(); #endif return app.exec(); } #ifdef BUILD_FOR_BUNDLE QString getDataStoragePath() { QString dataStoragePath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); QDir dir(dataStoragePath); if (!dir.exists()) { dir.mkpath("."); } return dataStoragePath; } void writeLogsToFile() { QFile logFile(getDataStoragePath() + "/StatusIm.log"); if (logFile.open(QIODevice::WriteOnly | QIODevice::Append)) { for (QString message : consoleOutputStrings) { logFile.write(message.toStdString().c_str()); } consoleOutputStrings.clear(); logFile.flush(); logFile.close(); } } void runUbuntuServer() { QProcess *process = new QProcess(); process->setWorkingDirectory(getDataStoragePath()); process->setProgram(QGuiApplication::applicationDirPath() + "/ubuntu-server"); QObject::connect(process, &QProcess::errorOccurred, [=](QProcess::ProcessError) { qDebug() << "process name: " << process->program(); qDebug() << "process error: " << process->errorString(); }); QObject::connect(process, &QProcess::readyReadStandardOutput, [=] { qDebug() << "ubuntu-server std: " << process->readAllStandardOutput().trimmed(); }); QObject::connect(process, &QProcess::readyReadStandardError, [=] { QString output = process->readAllStandardError().trimmed(); qDebug() << "ubuntu-server err: " << output; if (output.contains("Server starting")) { ubuntuServerStarted = true; } }); QObject::connect(QGuiApplication::instance(), &QCoreApplication::aboutToQuit, [=]() { qDebug() << "Kill ubuntu server"; process->kill(); }); qDebug() << "starting ubuntu server..."; process->start(); qDebug() << "wait for started..."; while (!ubuntuServerStarted) { QGuiApplication::processEvents(); } qDebug() << "waiting finished"; } void saveMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); QString message = localMsg + "\n"; switch (type) { case QtDebugMsg: consoleOutputStrings << "Debug: " << message << "\n"; break; case QtInfoMsg: consoleOutputStrings << "Info: " << message << "\n"; break; case QtWarningMsg: consoleOutputStrings << "Warning: " << message << "\n"; break; case QtCriticalMsg: consoleOutputStrings << "Critical: " << message << "\n"; break; case QtFatalMsg: consoleOutputStrings << "Fatal: " << message << "\n"; writeLogsToFile(); abort(); } } #endif #include "main.moc" <commit_msg>Thread safe access to log messages list<commit_after> /** * Copyright (C) 2016, Canonical Ltd. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // #define BUILD_FOR_BUNDLE #include <QCommandLineParser> #include <QFile> #include <QGuiApplication> #include <QProcess> #include <QQuickView> #include <QStandardPaths> #include <QTimer> #include <QUrl> #include "attachedproperties.h" #include "reactitem.h" #include "rootview.h" #include "utilities.h" #ifdef BUILD_FOR_BUNDLE #include <QMutexLocker> QStringList consoleOutputStrings; bool ubuntuServerStarted = false; QMutex consoleOutputMutex; #endif const int MAIN_WINDOW_WIDTH = 1024; const int MAIN_WINDOW_HEIGHT = 768; // TODO: some way to change while running class ReactNativeProperties : public QObject { Q_OBJECT Q_PROPERTY(bool liveReload READ liveReload WRITE setLiveReload NOTIFY liveReloadChanged) Q_PROPERTY(QUrl codeLocation READ codeLocation WRITE setCodeLocation NOTIFY codeLocationChanged) Q_PROPERTY(QString pluginsPath READ pluginsPath WRITE setPluginsPath NOTIFY pluginsPathChanged) Q_PROPERTY( QString executor READ executor WRITE setExecutor NOTIFY executorChanged) public: ReactNativeProperties(QObject *parent = 0) : QObject(parent) { m_codeLocation = m_packagerTemplate.arg(m_packagerHost).arg(m_packagerPort); } bool liveReload() const { return m_liveReload; } void setLiveReload(bool liveReload) { if (m_liveReload == liveReload) return; m_liveReload = liveReload; Q_EMIT liveReloadChanged(); } QUrl codeLocation() const { return m_codeLocation; } void setCodeLocation(const QUrl &codeLocation) { if (m_codeLocation == codeLocation) return; m_codeLocation = codeLocation; Q_EMIT codeLocationChanged(); } QString pluginsPath() const { return m_pluginsPath; } void setPluginsPath(const QString &pluginsPath) { if (m_pluginsPath == pluginsPath) return; m_pluginsPath = pluginsPath; Q_EMIT pluginsPathChanged(); } QString executor() const { return m_executor; } void setExecutor(const QString &executor) { if (m_executor == executor) return; m_executor = executor; Q_EMIT executorChanged(); } QString packagerHost() const { return m_packagerHost; } void setPackagerHost(const QString &packagerHost) { if (m_packagerHost == packagerHost) return; m_packagerHost = packagerHost; setCodeLocation(m_packagerTemplate.arg(m_packagerHost).arg(m_packagerPort)); } QString packagerPort() const { return m_packagerPort; } void setPackagerPort(const QString &packagerPort) { if (m_packagerPort == packagerPort) return; m_packagerPort = packagerPort; setCodeLocation(m_packagerTemplate.arg(m_packagerHost).arg(m_packagerPort)); } void setLocalSource(const QString &source) { if (m_localSource == source) return; // overrides packager* if (source.startsWith("file:")) { setCodeLocation(source); } else { QFileInfo fi(source); if (!fi.exists()) { qWarning() << "Attempt to set non-existent local source file"; return; } setCodeLocation(QUrl::fromLocalFile(fi.absoluteFilePath())); setLiveReload(false); } } Q_SIGNALS: void liveReloadChanged(); void codeLocationChanged(); void pluginsPathChanged(); void executorChanged(); private: bool m_liveReload = false; QString m_packagerHost = "localhost"; QString m_packagerPort = "8081"; QString m_localSource; QString m_packagerTemplate = "http://%1:%2/index.desktop.bundle?platform=desktop&dev=true"; QUrl m_codeLocation; QString m_pluginsPath; #ifdef BUILD_FOR_BUNDLE QString m_executor = "RemoteServerConnection"; #else QString m_executor = "LocalServerConnection"; #endif }; #ifdef BUILD_FOR_BUNDLE void runUbuntuServer(); void saveMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg); void writeLogsToFile(); #endif int main(int argc, char **argv) { QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); Q_INIT_RESOURCE(react_resources); #ifdef BUILD_FOR_BUNDLE qInstallMessageHandler(saveMessage); runUbuntuServer(); #endif QQuickView view; ReactNativeProperties *rnp = new ReactNativeProperties(&view); #ifdef BUILD_FOR_BUNDLE rnp->setCodeLocation("file:" + QGuiApplication::applicationDirPath() + "/assets"); #endif utilities::registerReactTypes(); QCommandLineParser p; p.setApplicationDescription("React Native host application"); p.addHelpOption(); p.addOptions({ {{"R", "live-reload"}, "Enable live reload."}, {{"H", "host"}, "Set packager host address.", rnp->packagerHost()}, {{"P", "port"}, "Set packager port number.", rnp->packagerPort()}, {{"L", "local"}, "Set path to the local packaged source", "not set"}, {{"M", "plugins-path"}, "Set path to node modules", "./plugins"}, {{"E", "executor"}, "Set Javascript executor", rnp->executor()}, }); p.process(app); rnp->setLiveReload(p.isSet("live-reload")); if (p.isSet("host")) rnp->setPackagerHost(p.value("host")); if (p.isSet("port")) rnp->setPackagerPort(p.value("port")); if (p.isSet("local")) rnp->setLocalSource(p.value("local")); if (p.isSet("plugins-path")) rnp->setPluginsPath(p.value("plugins-path")); if (p.isSet("executor")) rnp->setExecutor(p.value("executor")); view.rootContext()->setContextProperty("ReactNativeProperties", rnp); view.setSource(QUrl("qrc:///main.qml")); view.setResizeMode(QQuickView::SizeRootObjectToView); view.resize(MAIN_WINDOW_WIDTH, MAIN_WINDOW_HEIGHT); view.show(); #ifdef BUILD_FOR_BUNDLE QTimer t; t.setInterval(500); QObject::connect(&t, &QTimer::timeout, [=]() { writeLogsToFile(); }); t.start(); #endif return app.exec(); } #ifdef BUILD_FOR_BUNDLE QString getDataStoragePath() { QString dataStoragePath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); QDir dir(dataStoragePath); if (!dir.exists()) { dir.mkpath("."); } return dataStoragePath; } void writeLogsToFile() { QMutexLocker locker(&consoleOutputMutex); QFile logFile(getDataStoragePath() + "/StatusIm.log"); if (logFile.open(QIODevice::WriteOnly | QIODevice::Append)) { for (QString message : consoleOutputStrings) { logFile.write(message.toStdString().c_str()); } consoleOutputStrings.clear(); logFile.flush(); logFile.close(); } } void runUbuntuServer() { QProcess *process = new QProcess(); process->setWorkingDirectory(getDataStoragePath()); process->setProgram(QGuiApplication::applicationDirPath() + "/ubuntu-server"); QObject::connect(process, &QProcess::errorOccurred, [=](QProcess::ProcessError) { qDebug() << "process name: " << process->program(); qDebug() << "process error: " << process->errorString(); }); QObject::connect(process, &QProcess::readyReadStandardOutput, [=] { qDebug() << "ubuntu-server std: " << process->readAllStandardOutput().trimmed(); }); QObject::connect(process, &QProcess::readyReadStandardError, [=] { QString output = process->readAllStandardError().trimmed(); qDebug() << "ubuntu-server err: " << output; if (output.contains("Server starting")) { ubuntuServerStarted = true; } }); QObject::connect(QGuiApplication::instance(), &QCoreApplication::aboutToQuit, [=]() { qDebug() << "Kill ubuntu server"; process->kill(); }); qDebug() << "starting ubuntu server..."; process->start(); qDebug() << "wait for started..."; while (!ubuntuServerStarted) { QGuiApplication::processEvents(); } qDebug() << "waiting finished"; } void appendConsoleString(const QString &msg) { QMutexLocker locker(&consoleOutputMutex); consoleOutputStrings << msg; } void saveMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); QString message = localMsg + "\n"; switch (type) { case QtDebugMsg: appendConsoleString(QString("Debug: %1 \n").arg(message)); break; case QtInfoMsg: appendConsoleString(QString("Info: %1 \n").arg(message)); break; case QtWarningMsg: appendConsoleString(QString("Warning: %1 \n").arg(message)); break; case QtCriticalMsg: appendConsoleString(QString("Critical: %1 \n").arg(message)); break; case QtFatalMsg: appendConsoleString(QString("Fatal: %1 \n").arg(message)); writeLogsToFile(); abort(); } } #endif #include "main.moc" <|endoftext|>
<commit_before>//===- Optimize.cpp - Optimize a complete program -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements all optimization of the linked module for llvm-ld. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/LoadValueNumbering.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Support/CommandLine.h" #include "llvm/System/DynamicLibrary.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Support/PluginLoader.h" using namespace llvm; // Pass Name Options as generated by the PassNameParser static cl::list<const PassInfo*, bool, FilteredPassNameParser<PassInfo::Optimization> > OptimizationList(cl::desc("Optimizations available:")); // Optimization Enumeration enum OptimizationLevels { OPT_FAST_COMPILE = 1, OPT_SIMPLE = 2, OPT_AGGRESSIVE = 3, OPT_LINK_TIME = 4, OPT_AGGRESSIVE_LINK_TIME = 5 }; // Optimization Options static cl::opt<OptimizationLevels> OptLevel( cl::desc("Choose level of optimization to apply:"), cl::init(OPT_FAST_COMPILE), cl::values( clEnumValN(OPT_FAST_COMPILE,"O0", "An alias for the -O1 option."), clEnumValN(OPT_FAST_COMPILE,"O1", "Optimize for linking speed, not execution speed."), clEnumValN(OPT_SIMPLE,"O2", "Perform only required/minimal optimizations"), clEnumValN(OPT_AGGRESSIVE,"O3", "An alias for the -O2 option."), clEnumValN(OPT_LINK_TIME,"O4", "Perform standard link time optimizations"), clEnumValN(OPT_AGGRESSIVE_LINK_TIME,"O5", "Perform aggressive link time optimizations"), clEnumValEnd ) ); static cl::opt<bool> DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); static cl::opt<bool> DisableOptimizations("disable-opt", cl::desc("Do not run any optimization passes")); static cl::opt<bool> DisableInternalize("disable-internalize", cl::desc("Do not mark all symbols as internal")); static cl::opt<bool> VerifyEach("verify-each", cl::desc("Verify intermediate results of all passes")); static cl::opt<bool> Strip("s", cl::desc("Strip symbol info from executable")); static cl::alias ExportDynamic("export-dynamic", cl::aliasopt(DisableInternalize), cl::desc("Alias for -disable-internalize")); // A utility function that adds a pass to the pass manager but will also add // a verifier pass after if we're supposed to verify. static inline void addPass(PassManager &PM, Pass *P) { // Add the pass to the pass manager... PM.add(P); // If we are verifying all of the intermediate steps, add the verifier... if (VerifyEach) PM.add(createVerifierPass()); } namespace llvm { /// Optimize - Perform link time optimizations. This will run the scalar /// optimizations, any loaded plugin-optimization modules, and then the /// inter-procedural optimizations if applicable. void Optimize(Module* M) { // Instantiate the pass manager to organize the passes. PassManager Passes; // If we're verifying, start off with a verification pass. if (VerifyEach) Passes.add(createVerifierPass()); // Add an appropriate TargetData instance for this module... addPass(Passes, new TargetData(M)); // Often if the programmer does not specify proper prototypes for the // functions they are calling, they end up calling a vararg version of the // function that does not get a body filled in (the real function has typed // arguments). This pass merges the two functions. addPass(Passes, createFunctionResolvingPass()); if (!DisableOptimizations) { // Now that composite has been compiled, scan through the module, looking // for a main function. If main is defined, mark all other functions // internal. addPass(Passes, createInternalizePass(!DisableInternalize)); // Now that we internalized some globals, see if we can hack on them! addPass(Passes, createGlobalOptimizerPass()); // Linking modules together can lead to duplicated global constants, only // keep one copy of each constant... addPass(Passes, createConstantMergePass()); // If the -s command line option was specified, strip the symbols out of the // resulting program to make it smaller. -s is a GLD option that we are // supporting. if (Strip) addPass(Passes, createStripSymbolsPass()); // Propagate constants at call sites into the functions they call. addPass(Passes, createIPConstantPropagationPass()); // Remove unused arguments from functions... addPass(Passes, createDeadArgEliminationPass()); if (!DisableInline) addPass(Passes, createFunctionInliningPass()); // Inline small functions addPass(Passes, createPruneEHPass()); // Remove dead EH info addPass(Passes, createGlobalDCEPass()); // Remove dead functions // If we didn't decide to inline a function, check to see if we can // transform it to pass arguments by value instead of by reference. addPass(Passes, createArgumentPromotionPass()); // The IPO passes may leave cruft around. Clean up after them. addPass(Passes, createInstructionCombiningPass()); addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas // Run a few AA driven optimizations, to cleanup the code. addPass(Passes, createGlobalsModRefPass()); // IP alias analysis addPass(Passes, createLICMPass()); // Hoist loop invariants addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs addPass(Passes, createGCSEPass()); // Remove common subexprs addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores // Cleanup and simplify the code after the scalar optimizations. addPass(Passes, createInstructionCombiningPass()); // Delete basic blocks, which optimization passes may have killed... addPass(Passes, createCFGSimplificationPass()); // Now that we have optimized the program, discard unreachable functions... addPass(Passes, createGlobalDCEPass()); } // Create a new optimization pass for each one specified on the command line std::auto_ptr<TargetMachine> target; for (unsigned i = 0; i < OptimizationList.size(); ++i) { const PassInfo *Opt = OptimizationList[i]; if (Opt->getNormalCtor()) addPass(Passes, Opt->getNormalCtor()()); else if (Opt->getTargetCtor()) { assert(target.get() && "Could not allocate target machine!"); addPass(Passes, Opt->getTargetCtor()(*target.get())); } else std::cerr << "llvm-ld: cannot create pass: " << Opt->getPassName() << "\n"; } // The user's passes may leave cruft around. Clean up after them them but // only if we haven't got DisableOptimizations set if (!DisableOptimizations) { addPass(Passes, createInstructionCombiningPass()); addPass(Passes, createCFGSimplificationPass()); addPass(Passes, createGlobalDCEPass()); } // Make sure everything is still good. Passes.add(createVerifierPass()); // Run our queue of passes all at once now, efficiently. Passes.run(*M); } } <commit_msg>eliminate only use of FilteredPassNameParser<commit_after>//===- Optimize.cpp - Optimize a complete program -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements all optimization of the linked module for llvm-ld. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/LoadValueNumbering.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Support/CommandLine.h" #include "llvm/System/DynamicLibrary.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Support/PluginLoader.h" using namespace llvm; // Pass Name Options as generated by the PassNameParser static cl::list<const PassInfo*, bool, PassNameParser> OptimizationList(cl::desc("Optimizations available:")); // Optimization Enumeration enum OptimizationLevels { OPT_FAST_COMPILE = 1, OPT_SIMPLE = 2, OPT_AGGRESSIVE = 3, OPT_LINK_TIME = 4, OPT_AGGRESSIVE_LINK_TIME = 5 }; // Optimization Options static cl::opt<OptimizationLevels> OptLevel( cl::desc("Choose level of optimization to apply:"), cl::init(OPT_FAST_COMPILE), cl::values( clEnumValN(OPT_FAST_COMPILE,"O0", "An alias for the -O1 option."), clEnumValN(OPT_FAST_COMPILE,"O1", "Optimize for linking speed, not execution speed."), clEnumValN(OPT_SIMPLE,"O2", "Perform only required/minimal optimizations"), clEnumValN(OPT_AGGRESSIVE,"O3", "An alias for the -O2 option."), clEnumValN(OPT_LINK_TIME,"O4", "Perform standard link time optimizations"), clEnumValN(OPT_AGGRESSIVE_LINK_TIME,"O5", "Perform aggressive link time optimizations"), clEnumValEnd ) ); static cl::opt<bool> DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); static cl::opt<bool> DisableOptimizations("disable-opt", cl::desc("Do not run any optimization passes")); static cl::opt<bool> DisableInternalize("disable-internalize", cl::desc("Do not mark all symbols as internal")); static cl::opt<bool> VerifyEach("verify-each", cl::desc("Verify intermediate results of all passes")); static cl::opt<bool> Strip("s", cl::desc("Strip symbol info from executable")); static cl::alias ExportDynamic("export-dynamic", cl::aliasopt(DisableInternalize), cl::desc("Alias for -disable-internalize")); // A utility function that adds a pass to the pass manager but will also add // a verifier pass after if we're supposed to verify. static inline void addPass(PassManager &PM, Pass *P) { // Add the pass to the pass manager... PM.add(P); // If we are verifying all of the intermediate steps, add the verifier... if (VerifyEach) PM.add(createVerifierPass()); } namespace llvm { /// Optimize - Perform link time optimizations. This will run the scalar /// optimizations, any loaded plugin-optimization modules, and then the /// inter-procedural optimizations if applicable. void Optimize(Module* M) { // Instantiate the pass manager to organize the passes. PassManager Passes; // If we're verifying, start off with a verification pass. if (VerifyEach) Passes.add(createVerifierPass()); // Add an appropriate TargetData instance for this module... addPass(Passes, new TargetData(M)); // Often if the programmer does not specify proper prototypes for the // functions they are calling, they end up calling a vararg version of the // function that does not get a body filled in (the real function has typed // arguments). This pass merges the two functions. addPass(Passes, createFunctionResolvingPass()); if (!DisableOptimizations) { // Now that composite has been compiled, scan through the module, looking // for a main function. If main is defined, mark all other functions // internal. addPass(Passes, createInternalizePass(!DisableInternalize)); // Now that we internalized some globals, see if we can hack on them! addPass(Passes, createGlobalOptimizerPass()); // Linking modules together can lead to duplicated global constants, only // keep one copy of each constant... addPass(Passes, createConstantMergePass()); // If the -s command line option was specified, strip the symbols out of the // resulting program to make it smaller. -s is a GLD option that we are // supporting. if (Strip) addPass(Passes, createStripSymbolsPass()); // Propagate constants at call sites into the functions they call. addPass(Passes, createIPConstantPropagationPass()); // Remove unused arguments from functions... addPass(Passes, createDeadArgEliminationPass()); if (!DisableInline) addPass(Passes, createFunctionInliningPass()); // Inline small functions addPass(Passes, createPruneEHPass()); // Remove dead EH info addPass(Passes, createGlobalDCEPass()); // Remove dead functions // If we didn't decide to inline a function, check to see if we can // transform it to pass arguments by value instead of by reference. addPass(Passes, createArgumentPromotionPass()); // The IPO passes may leave cruft around. Clean up after them. addPass(Passes, createInstructionCombiningPass()); addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas // Run a few AA driven optimizations, to cleanup the code. addPass(Passes, createGlobalsModRefPass()); // IP alias analysis addPass(Passes, createLICMPass()); // Hoist loop invariants addPass(Passes, createLoadValueNumberingPass()); // GVN for load instrs addPass(Passes, createGCSEPass()); // Remove common subexprs addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores // Cleanup and simplify the code after the scalar optimizations. addPass(Passes, createInstructionCombiningPass()); // Delete basic blocks, which optimization passes may have killed... addPass(Passes, createCFGSimplificationPass()); // Now that we have optimized the program, discard unreachable functions... addPass(Passes, createGlobalDCEPass()); } // Create a new optimization pass for each one specified on the command line std::auto_ptr<TargetMachine> target; for (unsigned i = 0; i < OptimizationList.size(); ++i) { const PassInfo *Opt = OptimizationList[i]; if (Opt->getNormalCtor()) addPass(Passes, Opt->getNormalCtor()()); else if (Opt->getTargetCtor()) { assert(target.get() && "Could not allocate target machine!"); addPass(Passes, Opt->getTargetCtor()(*target.get())); } else std::cerr << "llvm-ld: cannot create pass: " << Opt->getPassName() << "\n"; } // The user's passes may leave cruft around. Clean up after them them but // only if we haven't got DisableOptimizations set if (!DisableOptimizations) { addPass(Passes, createInstructionCombiningPass()); addPass(Passes, createCFGSimplificationPass()); addPass(Passes, createGlobalDCEPass()); } // Make sure everything is still good. Passes.add(createVerifierPass()); // Run our queue of passes all at once now, efficiently. Passes.run(*M); } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/screen_lock_view.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/utf_string_conversions.h" #include "chrome/browser/chromeos/login/helper.h" #include "chrome/browser/chromeos/login/rounded_rect_painter.h" #include "chrome/browser/chromeos/login/screen_locker.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/chromeos/login/user_view.h" #include "chrome/browser/chromeos/login/username_view.h" #include "chrome/browser/chromeos/login/wizard_accessibility_helper.h" #include "chrome/browser/profile_manager.h" #include "chrome/common/notification_service.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/background.h" #include "views/border.h" #include "views/controls/image_view.h" #include "views/controls/label.h" #include "views/grid_layout.h" namespace chromeos { namespace { const int kCornerRadius = 5; // A Textfield for password, which also sets focus to itself // when a mouse is clicked on it. This is necessary in screen locker // as mouse events are grabbed in the screen locker. class PasswordField : public views::Textfield { public: PasswordField() : views::Textfield(views::Textfield::STYLE_PASSWORD) { set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_EMPTY_PASSWORD_TEXT)); } // views::View overrides. virtual bool OnMousePressed(const views::MouseEvent& e) { RequestFocus(); return false; } private: DISALLOW_COPY_AND_ASSIGN(PasswordField); }; } // namespace using views::GridLayout; using login::kBorderSize; ScreenLockView::ScreenLockView(ScreenLocker* screen_locker) : user_view_(NULL), password_field_(NULL), screen_locker_(screen_locker), main_(NULL), username_(NULL) { DCHECK(screen_locker_); } gfx::Size ScreenLockView::GetPreferredSize() { return main_->GetPreferredSize(); } void ScreenLockView::Layout() { int username_height = username_->GetPreferredSize().height(); main_->SetBounds(0, 0, width(), height()); username_->SetBounds( kBorderSize, login::kUserImageSize - username_height + kBorderSize, login::kUserImageSize, username_height); } void ScreenLockView::Init() { registrar_.Add(this, NotificationType::LOGIN_USER_IMAGE_CHANGED, NotificationService::AllSources()); user_view_ = new UserView(this, false, // is_login true); // need_background main_ = new views::View(); // Use rounded rect background. views::Painter* painter = CreateWizardPainter(&BorderDefinition::kUserBorder); main_->set_background( views::Background::CreateBackgroundPainter(true, painter)); main_->set_border(CreateWizardBorder(&BorderDefinition::kUserBorder)); // Password field. password_field_ = new PasswordField(); password_field_->SetController(this); // User icon. UserManager::User user = screen_locker_->user(); user_view_->SetImage(user.image()); // User name. std::wstring text = UTF8ToWide(user.GetDisplayName()); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); const gfx::Font& font = rb.GetFont(ResourceBundle::LargeFont).DeriveFont(0, gfx::Font::BOLD); // Layouts image, textfield and button components. GridLayout* layout = new GridLayout(main_); main_->SetLayoutManager(layout); views::ColumnSet* column_set = layout->AddColumnSet(0); column_set->AddPaddingColumn(0, kBorderSize); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, kBorderSize); column_set = layout->AddColumnSet(1); column_set->AddPaddingColumn(0, 5); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, 5); layout->AddPaddingRow(0, kBorderSize); layout->StartRow(0, 0); layout->AddView(user_view_); layout->AddPaddingRow(0, kBorderSize); layout->StartRow(0, 1); layout->AddView(password_field_); layout->AddPaddingRow(0, kBorderSize); AddChildView(main_); UsernameView* username = new UsernameView(text); username_ = username; username->SetFont(font); AddChildView(username); } void ScreenLockView::ClearAndSetFocusToPassword() { password_field_->RequestFocus(); password_field_->SetText(string16()); } void ScreenLockView::SetSignoutEnabled(bool enabled) { user_view_->SetSignoutEnabled(enabled); } gfx::Rect ScreenLockView::GetPasswordBoundsRelativeTo(const views::View* view) { gfx::Point p; views::View::ConvertPointToView(password_field_, view, &p); return gfx::Rect(p, size()); } void ScreenLockView::SetEnabled(bool enabled) { views::View::SetEnabled(enabled); if (!enabled) { user_view_->StartThrobber(); } else { user_view_->StopThrobber(); } password_field_->SetEnabled(enabled); } void ScreenLockView::OnSignout() { screen_locker_->Signout(); } bool ScreenLockView::HandleKeystroke( views::Textfield* sender, const views::Textfield::Keystroke& keystroke) { screen_locker_->ClearErrors(); if (keystroke.GetKeyboardCode() == app::VKEY_RETURN) { screen_locker_->Authenticate(password_field_->text()); return true; } return false; } void ScreenLockView::Observe( NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type != NotificationType::LOGIN_USER_IMAGE_CHANGED || !user_view_) return; UserManager::User* user = Details<UserManager::User>(details).ptr(); if (screen_locker_->user().email() != user->email()) return; user_view_->SetImage(user->image()); } void ScreenLockView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (is_add && this == child) WizardAccessibilityHelper::GetInstance()->MaybeEnableAccessibility(this); } } // namespace chromeos <commit_msg>Fix UI regression in r63314. Clear focus of textfield so that re-enabling textfield sets the focus to the textfield.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/screen_lock_view.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/utf_string_conversions.h" #include "chrome/browser/chromeos/login/helper.h" #include "chrome/browser/chromeos/login/rounded_rect_painter.h" #include "chrome/browser/chromeos/login/screen_locker.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/chromeos/login/user_view.h" #include "chrome/browser/chromeos/login/username_view.h" #include "chrome/browser/chromeos/login/wizard_accessibility_helper.h" #include "chrome/browser/profile_manager.h" #include "chrome/common/notification_service.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/background.h" #include "views/border.h" #include "views/controls/image_view.h" #include "views/controls/label.h" #include "views/grid_layout.h" namespace chromeos { namespace { const int kCornerRadius = 5; // A Textfield for password, which also sets focus to itself // when a mouse is clicked on it. This is necessary in screen locker // as mouse events are grabbed in the screen locker. class PasswordField : public views::Textfield { public: PasswordField() : views::Textfield(views::Textfield::STYLE_PASSWORD) { set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_EMPTY_PASSWORD_TEXT)); } // views::View overrides. virtual bool OnMousePressed(const views::MouseEvent& e) { RequestFocus(); return false; } private: DISALLOW_COPY_AND_ASSIGN(PasswordField); }; } // namespace using views::GridLayout; using login::kBorderSize; ScreenLockView::ScreenLockView(ScreenLocker* screen_locker) : user_view_(NULL), password_field_(NULL), screen_locker_(screen_locker), main_(NULL), username_(NULL) { DCHECK(screen_locker_); } gfx::Size ScreenLockView::GetPreferredSize() { return main_->GetPreferredSize(); } void ScreenLockView::Layout() { int username_height = username_->GetPreferredSize().height(); main_->SetBounds(0, 0, width(), height()); username_->SetBounds( kBorderSize, login::kUserImageSize - username_height + kBorderSize, login::kUserImageSize, username_height); } void ScreenLockView::Init() { registrar_.Add(this, NotificationType::LOGIN_USER_IMAGE_CHANGED, NotificationService::AllSources()); user_view_ = new UserView(this, false, // is_login true); // need_background main_ = new views::View(); // Use rounded rect background. views::Painter* painter = CreateWizardPainter(&BorderDefinition::kUserBorder); main_->set_background( views::Background::CreateBackgroundPainter(true, painter)); main_->set_border(CreateWizardBorder(&BorderDefinition::kUserBorder)); // Password field. password_field_ = new PasswordField(); password_field_->SetController(this); // User icon. UserManager::User user = screen_locker_->user(); user_view_->SetImage(user.image()); // User name. std::wstring text = UTF8ToWide(user.GetDisplayName()); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); const gfx::Font& font = rb.GetFont(ResourceBundle::LargeFont).DeriveFont(0, gfx::Font::BOLD); // Layouts image, textfield and button components. GridLayout* layout = new GridLayout(main_); main_->SetLayoutManager(layout); views::ColumnSet* column_set = layout->AddColumnSet(0); column_set->AddPaddingColumn(0, kBorderSize); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, kBorderSize); column_set = layout->AddColumnSet(1); column_set->AddPaddingColumn(0, 5); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, 5); layout->AddPaddingRow(0, kBorderSize); layout->StartRow(0, 0); layout->AddView(user_view_); layout->AddPaddingRow(0, kBorderSize); layout->StartRow(0, 1); layout->AddView(password_field_); layout->AddPaddingRow(0, kBorderSize); AddChildView(main_); UsernameView* username = new UsernameView(text); username_ = username; username->SetFont(font); AddChildView(username); } void ScreenLockView::ClearAndSetFocusToPassword() { password_field_->RequestFocus(); password_field_->SetText(string16()); } void ScreenLockView::SetSignoutEnabled(bool enabled) { user_view_->SetSignoutEnabled(enabled); } gfx::Rect ScreenLockView::GetPasswordBoundsRelativeTo(const views::View* view) { gfx::Point p; views::View::ConvertPointToView(password_field_, view, &p); return gfx::Rect(p, size()); } void ScreenLockView::SetEnabled(bool enabled) { views::View::SetEnabled(enabled); if (!enabled) { user_view_->StartThrobber(); // TODO(oshima): Re-enabling does not move the focus to the view // that had a focus (issue http://crbug.com/43131). // Clear focus on the textfield so that re-enabling can set focus // back to the text field. // FocusManager may be null if the view does not have // associated Widget yet. if (password_field_->GetFocusManager()) password_field_->GetFocusManager()->ClearFocus(); } else { user_view_->StopThrobber(); } password_field_->SetEnabled(enabled); } void ScreenLockView::OnSignout() { screen_locker_->Signout(); } bool ScreenLockView::HandleKeystroke( views::Textfield* sender, const views::Textfield::Keystroke& keystroke) { screen_locker_->ClearErrors(); if (keystroke.GetKeyboardCode() == app::VKEY_RETURN) { screen_locker_->Authenticate(password_field_->text()); return true; } return false; } void ScreenLockView::Observe( NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type != NotificationType::LOGIN_USER_IMAGE_CHANGED || !user_view_) return; UserManager::User* user = Details<UserManager::User>(details).ptr(); if (screen_locker_->user().email() != user->email()) return; user_view_->SetImage(user->image()); } void ScreenLockView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (is_add && this == child) WizardAccessibilityHelper::GetInstance()->MaybeEnableAccessibility(this); } } // namespace chromeos <|endoftext|>
<commit_before>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "AccessMarking.h" #include <unordered_map> #include "Devirtualizer.h" #include "DexUtil.h" #include "Mutators.h" #include "ReachableClasses.h" #include "Resolver.h" #include "Walkers.h" namespace { size_t mark_classes_final(const DexStoresVector& stores) { size_t n_classes_finalized = 0; for (auto const& dex : DexStoreClassesIterator(stores)) { for (auto const& cls : dex) { if (is_seed(cls) || is_abstract(cls) || is_final(cls)) continue; auto const& children = get_children(cls->get_type()); if (children.empty()) { TRACE(ACCESS, 2, "Finalizing class: %s\n", SHOW(cls)); set_final(cls); ++n_classes_finalized; } } } return n_classes_finalized; } const DexMethod* find_override(const DexMethod* method, const DexClass* cls) { std::vector<const DexType*> children; get_all_children(cls->get_type(), children); for (auto const& childtype : children) { auto const& child = type_class(childtype); assert(child); for (auto const& child_method : child->get_vmethods()) { if (signatures_match(method, child_method)) { return child_method; } } } return nullptr; } size_t mark_methods_final(const DexStoresVector& stores) { size_t n_methods_finalized = 0; for (auto const& dex : DexStoreClassesIterator(stores)) { for (auto const& cls : dex) { for (auto const& method : cls->get_vmethods()) { if (is_seed(method) || is_abstract(method) || is_final(method)) { continue; } if (!find_override(method, cls)) { TRACE(ACCESS, 2, "Finalizing method: %s\n", SHOW(method)); set_final(method); ++n_methods_finalized; } } } } return n_methods_finalized; } std::vector<DexMethod*> direct_methods(const std::vector<DexClass*>& scope) { std::vector<DexMethod*> ret; for (auto cls : scope) { for (auto m : cls->get_dmethods()) { ret.push_back(m); } } return ret; } bool uses_this(const DexMethod* method) { auto const& code = method->get_code(); if (!code) return false; auto const this_reg = code->get_registers_size() - code->get_ins_size(); for (auto const& insn : code->get_instructions()) { if (insn->has_range()) { if (this_reg >= insn->range_base() && this_reg < (insn->range_base() + insn->range_size())) { return true; } } for (unsigned i = 0; i < insn->srcs_size(); i++) { if (this_reg == insn->src(i)) return true; } } return false; } std::unordered_set<DexMethod*> find_static_methods( const std::vector<DexMethod*>& candidates ) { std::unordered_set<DexMethod*> staticized; for (auto const& method : candidates) { if (is_static(method) || uses_this(method) || is_seed(method) || is_abstract(method)) { continue; } staticized.emplace(method); } return staticized; } void fix_call_sites( const std::vector<DexClass*>& scope, const std::unordered_set<DexMethod*>& statics ) { walk_opcodes( scope, [](DexMethod*) { return true; }, [&](DexMethod*, DexInstruction* inst) { if (!inst->has_methods()) return; auto mi = static_cast<DexOpcodeMethod*>(inst); auto method = mi->get_method(); if (!method->is_concrete()) { method = resolve_method(method, MethodSearch::Any); } if (statics.count(method)) { mi->rewrite_method(method); if (is_invoke_range(inst->opcode())) { mi->set_opcode(OPCODE_INVOKE_STATIC_RANGE); mi->set_range_base(mi->range_base() + 1); mi->set_range_size(mi->range_size() - 1); } else { mi->set_opcode(OPCODE_INVOKE_STATIC); auto nargs = mi->arg_word_count(); mi->set_arg_word_count(nargs - 1); for (uint16_t i = 0; i < nargs - 1; i++) { mi->set_src(i, mi->src(i + 1)); } } } } ); } void mark_methods_static(const std::unordered_set<DexMethod*>& statics) { for (auto method : statics) { TRACE(ACCESS, 2, "Staticized method: %s\n", SHOW(method)); mutators::make_static(method, mutators::KeepThis::No); } } std::unordered_set<DexMethod*> find_private_methods( const std::vector<DexClass*>& scope, const std::vector<DexMethod*>& cv ) { std::unordered_set<DexMethod*> candidates; for (auto m : cv) { TRACE(ACCESS, 3, "Considering for privatization: %s\n", SHOW(m)); if (!is_clinit(m) && !is_seed(m) && !is_abstract(m) && !is_private(m)) { candidates.emplace(m); } } walk_opcodes( scope, [](DexMethod*) { return true; }, [&](DexMethod* caller, DexInstruction* inst) { if (!inst->has_methods()) return; auto mi = static_cast<DexOpcodeMethod*>(inst); auto callee = mi->get_method(); if (!callee->is_concrete()) { callee = resolve_method(callee, MethodSearch::Any); if (!callee) return; } if (callee->get_class() == caller->get_class()) { return; } candidates.erase(callee); } ); return candidates; } void fix_call_sites_private( const std::vector<DexClass*>& scope, const std::unordered_set<DexMethod*>& privates ) { walk_opcodes( scope, [](DexMethod*) { return true; }, [&](DexMethod*, DexInstruction* inst) { if (!inst->has_methods()) return; auto mi = static_cast<DexOpcodeMethod*>(inst); auto callee = mi->get_method(); if (!callee->is_concrete()) { callee = resolve_method(callee, MethodSearch::Any); } if (privates.count(callee)) { mi->rewrite_method(callee); if (!is_static(callee)) { mi->set_opcode( is_invoke_range(mi->opcode()) ? OPCODE_INVOKE_DIRECT_RANGE : OPCODE_INVOKE_DIRECT); } } } ); } void mark_methods_private(const std::unordered_set<DexMethod*>& privates) { for (auto method : privates) { TRACE(ACCESS, 2, "Privatized method: %s\n", SHOW(method)); auto cls = type_class(method->get_class()); cls->remove_method(method); method->set_virtual(false); set_private(method); cls->add_method(method); } } } void AccessMarkingPass::run_pass( DexStoresVector& stores, ConfigFiles& cfg, PassManager& pm ) { if (!cfg.using_seeds) { return; } if (m_finalize_classes) { auto n_classes_final = mark_classes_final(stores); pm.incr_metric("finalized_classes", n_classes_final); TRACE(ACCESS, 1, "Finalized %lu classes\n", n_classes_final); } if (m_finalize_methods) { auto n_methods_final = mark_methods_final(stores); pm.incr_metric("finalized_methods", n_methods_final); TRACE(ACCESS, 1, "Finalized %lu methods\n", n_methods_final); } auto scope = build_class_scope(stores); auto candidates = devirtualize(scope); auto dmethods = direct_methods(scope); candidates.insert(candidates.end(), dmethods.begin(), dmethods.end()); if (m_staticize_methods) { auto static_methods = find_static_methods(candidates); fix_call_sites(scope, static_methods); mark_methods_static(static_methods); pm.incr_metric("staticized_methods", static_methods.size()); TRACE(ACCESS, 1, "Staticized %lu methods\n", static_methods.size()); } if (m_privatize_methods) { auto privates = find_private_methods(scope, candidates); fix_call_sites_private(scope, privates); mark_methods_private(privates); pm.incr_metric("privatized_methods", privates.size()); TRACE(ACCESS, 1, "Privatized %lu methods\n", privates.size()); } } static AccessMarkingPass s_pass; <commit_msg>Fix a corner case handling in AccessMarking<commit_after>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "AccessMarking.h" #include <unordered_map> #include "Devirtualizer.h" #include "DexUtil.h" #include "Mutators.h" #include "ReachableClasses.h" #include "Resolver.h" #include "Walkers.h" namespace { size_t mark_classes_final(const DexStoresVector& stores) { size_t n_classes_finalized = 0; for (auto const& dex : DexStoreClassesIterator(stores)) { for (auto const& cls : dex) { if (is_seed(cls) || is_abstract(cls) || is_final(cls)) continue; auto const& children = get_children(cls->get_type()); if (children.empty()) { TRACE(ACCESS, 2, "Finalizing class: %s\n", SHOW(cls)); set_final(cls); ++n_classes_finalized; } } } return n_classes_finalized; } const DexMethod* find_override(const DexMethod* method, const DexClass* cls) { std::vector<const DexType*> children; get_all_children(cls->get_type(), children); for (auto const& childtype : children) { auto const& child = type_class(childtype); assert(child); for (auto const& child_method : child->get_vmethods()) { if (signatures_match(method, child_method)) { return child_method; } } } return nullptr; } size_t mark_methods_final(const DexStoresVector& stores) { size_t n_methods_finalized = 0; for (auto const& dex : DexStoreClassesIterator(stores)) { for (auto const& cls : dex) { for (auto const& method : cls->get_vmethods()) { if (is_seed(method) || is_abstract(method) || is_final(method)) { continue; } if (!find_override(method, cls)) { TRACE(ACCESS, 2, "Finalizing method: %s\n", SHOW(method)); set_final(method); ++n_methods_finalized; } } } } return n_methods_finalized; } std::vector<DexMethod*> direct_methods(const std::vector<DexClass*>& scope) { std::vector<DexMethod*> ret; for (auto cls : scope) { for (auto m : cls->get_dmethods()) { ret.push_back(m); } } return ret; } bool uses_this(const DexMethod* method) { auto const& code = method->get_code(); if (!code) return false; auto const this_reg = code->get_registers_size() - code->get_ins_size(); for (auto const& insn : code->get_instructions()) { if (insn->has_range()) { if (this_reg >= insn->range_base() && this_reg < (insn->range_base() + insn->range_size())) { return true; } } for (unsigned i = 0; i < insn->srcs_size(); i++) { if (this_reg == insn->src(i)) return true; } } return false; } std::unordered_set<DexMethod*> find_static_methods( const std::vector<DexMethod*>& candidates ) { std::unordered_set<DexMethod*> staticized; for (auto const& method : candidates) { if (is_static(method) || uses_this(method) || is_seed(method) || is_abstract(method)) { continue; } staticized.emplace(method); } return staticized; } void fix_call_sites( const std::vector<DexClass*>& scope, const std::unordered_set<DexMethod*>& statics ) { walk_opcodes( scope, [](DexMethod*) { return true; }, [&](DexMethod*, DexInstruction* inst) { if (!inst->has_methods()) return; auto mi = static_cast<DexOpcodeMethod*>(inst); auto method = mi->get_method(); if (!method->is_concrete()) { method = resolve_method(method, MethodSearch::Any); } if (statics.count(method)) { mi->rewrite_method(method); if (is_invoke_range(inst->opcode())) { if (mi->range_size() == 1) { mi->set_opcode(OPCODE_INVOKE_STATIC); mi->set_arg_word_count(0); } else { mi->set_opcode(OPCODE_INVOKE_STATIC_RANGE); mi->set_range_base(mi->range_base() + 1); mi->set_range_size(mi->range_size() - 1); } } else { mi->set_opcode(OPCODE_INVOKE_STATIC); auto nargs = mi->arg_word_count(); mi->set_arg_word_count(nargs - 1); for (uint16_t i = 0; i < nargs - 1; i++) { mi->set_src(i, mi->src(i + 1)); } } } } ); } void mark_methods_static(const std::unordered_set<DexMethod*>& statics) { for (auto method : statics) { TRACE(ACCESS, 2, "Staticized method: %s\n", SHOW(method)); mutators::make_static(method, mutators::KeepThis::No); } } std::unordered_set<DexMethod*> find_private_methods( const std::vector<DexClass*>& scope, const std::vector<DexMethod*>& cv ) { std::unordered_set<DexMethod*> candidates; for (auto m : cv) { TRACE(ACCESS, 3, "Considering for privatization: %s\n", SHOW(m)); if (!is_clinit(m) && !is_seed(m) && !is_abstract(m) && !is_private(m)) { candidates.emplace(m); } } walk_opcodes( scope, [](DexMethod*) { return true; }, [&](DexMethod* caller, DexInstruction* inst) { if (!inst->has_methods()) return; auto mi = static_cast<DexOpcodeMethod*>(inst); auto callee = mi->get_method(); if (!callee->is_concrete()) { callee = resolve_method(callee, MethodSearch::Any); if (!callee) return; } if (callee->get_class() == caller->get_class()) { return; } candidates.erase(callee); } ); return candidates; } void fix_call_sites_private( const std::vector<DexClass*>& scope, const std::unordered_set<DexMethod*>& privates ) { walk_opcodes( scope, [](DexMethod*) { return true; }, [&](DexMethod*, DexInstruction* inst) { if (!inst->has_methods()) return; auto mi = static_cast<DexOpcodeMethod*>(inst); auto callee = mi->get_method(); if (!callee->is_concrete()) { callee = resolve_method(callee, MethodSearch::Any); } if (privates.count(callee)) { mi->rewrite_method(callee); if (!is_static(callee)) { mi->set_opcode( is_invoke_range(mi->opcode()) ? OPCODE_INVOKE_DIRECT_RANGE : OPCODE_INVOKE_DIRECT); } } } ); } void mark_methods_private(const std::unordered_set<DexMethod*>& privates) { for (auto method : privates) { TRACE(ACCESS, 2, "Privatized method: %s\n", SHOW(method)); auto cls = type_class(method->get_class()); cls->remove_method(method); method->set_virtual(false); set_private(method); cls->add_method(method); } } } void AccessMarkingPass::run_pass( DexStoresVector& stores, ConfigFiles& cfg, PassManager& pm ) { if (!cfg.using_seeds) { return; } if (m_finalize_classes) { auto n_classes_final = mark_classes_final(stores); pm.incr_metric("finalized_classes", n_classes_final); TRACE(ACCESS, 1, "Finalized %lu classes\n", n_classes_final); } if (m_finalize_methods) { auto n_methods_final = mark_methods_final(stores); pm.incr_metric("finalized_methods", n_methods_final); TRACE(ACCESS, 1, "Finalized %lu methods\n", n_methods_final); } auto scope = build_class_scope(stores); auto candidates = devirtualize(scope); auto dmethods = direct_methods(scope); candidates.insert(candidates.end(), dmethods.begin(), dmethods.end()); if (m_staticize_methods) { auto static_methods = find_static_methods(candidates); fix_call_sites(scope, static_methods); mark_methods_static(static_methods); pm.incr_metric("staticized_methods", static_methods.size()); TRACE(ACCESS, 1, "Staticized %lu methods\n", static_methods.size()); } if (m_privatize_methods) { auto privates = find_private_methods(scope, candidates); fix_call_sites_private(scope, privates); mark_methods_private(privates); pm.incr_metric("privatized_methods", privates.size()); TRACE(ACCESS, 1, "Privatized %lu methods\n", privates.size()); } } static AccessMarkingPass s_pass; <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_install_ui.h" #include <map> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/file_util.h" #include "base/rand_util.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/extensions/theme_installed_infobar_delegate.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/extensions/extension.h" #include "grit/browser_resources.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #if defined(OS_WIN) #include "app/win_util.h" #elif defined(OS_MACOSX) #include "base/scoped_cftyperef.h" #include "base/sys_string_conversions.h" #include <CoreFoundation/CFUserNotification.h> #elif defined(TOOLKIT_GTK) #include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h" #include "chrome/browser/gtk/gtk_theme_provider.h" #endif namespace { #if defined(OS_WIN) || defined(TOOLKIT_GTK) static std::wstring GetInstallWarning(Extension* extension) { // If the extension has a plugin, it's easy: the plugin has the most severe // warning. if (!extension->plugins().empty()) return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_FULL_ACCESS); // Otherwise, we go in descending order of severity: all hosts, several hosts, // a single host, no hosts. For each of these, we also have a variation of the // message for when api permissions are also requested. if (extension->HasAccessToAllHosts()) { if (extension->api_permissions().empty()) return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_ALL_HOSTS); else return l10n_util::GetString( IDS_EXTENSION_PROMPT_WARNING_NEW_ALL_HOSTS_AND_BROWSER); } const std::set<std::string> hosts = extension->GetEffectiveHostPermissions(); if (hosts.size() > 1) { if (extension->api_permissions().empty()) return l10n_util::GetString( IDS_EXTENSION_PROMPT_WARNING_NEW_MULTIPLE_HOSTS); else return l10n_util::GetString( IDS_EXTENSION_PROMPT_WARNING_NEW_MULTIPLE_HOSTS_AND_BROWSER); } if (hosts.size() == 1) { if (extension->api_permissions().empty()) return l10n_util::GetStringF( IDS_EXTENSION_PROMPT_WARNING_NEW_SINGLE_HOST, UTF8ToWide(*hosts.begin())); else return l10n_util::GetStringF( IDS_EXTENSION_PROMPT_WARNING_NEW_SINGLE_HOST_AND_BROWSER, UTF8ToWide(*hosts.begin())); } DCHECK(hosts.size() == 0); if (extension->api_permissions().empty()) return L""; else return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_BROWSER); } #endif } // namespace ExtensionInstallUI::ExtensionInstallUI(Profile* profile) : profile_(profile), ui_loop_(MessageLoop::current()) #if defined(TOOLKIT_GTK) ,previous_use_gtk_theme_(false) #endif { } void ExtensionInstallUI::ConfirmInstall(Delegate* delegate, Extension* extension, SkBitmap* install_icon) { DCHECK(ui_loop_ == MessageLoop::current()); // We special-case themes to not show any confirm UI. Instead they are // immediately installed, and then we show an infobar (see OnInstallSuccess) // to allow the user to revert if they don't like it. if (extension->IsTheme()) { // Remember the current theme in case the user pressed undo. Extension* previous_theme = profile_->GetTheme(); if (previous_theme) previous_theme_id_ = previous_theme->id(); #if defined(TOOLKIT_GTK) // On linux, we also need to take the user's system settings into account // to undo theme installation. previous_use_gtk_theme_ = GtkThemeProvider::GetFrom(profile_)->UseGtkTheme(); #endif delegate->ContinueInstall(); return; } #if defined(OS_WIN) || defined(TOOLKIT_GTK) if (!install_icon) { install_icon = ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_DEFAULT_EXTENSION_ICON_128); } ShowExtensionInstallPrompt(profile_, delegate, extension, install_icon, GetInstallWarning(extension)); #elif defined(OS_MACOSX) // TODO(port): Implement nicer UI. // Using CoreFoundation to do this dialog is unimaginably lame but will do // until the UI is redone. scoped_cftyperef<CFStringRef> confirm_title(base::SysWideToCFStringRef( l10n_util::GetString(IDS_EXTENSION_PROMPT_TITLE))); // Build the confirmation prompt, including a heading, a random humorous // warning, and a severe warning. const string16& confirm_format(ASCIIToUTF16("$1\n\n$2\n\n$3")); std::vector<string16> subst; subst.push_back(l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT_HEADING, UTF8ToUTF16(extension->name()))); string16 warnings[] = { l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_1), l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_2), l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_3) }; subst.push_back(warnings[base::RandInt(0, arraysize(warnings) - 1)]); subst.push_back(l10n_util::GetStringUTF16( IDS_EXTENSION_PROMPT_WARNING_SEVERE)); scoped_cftyperef<CFStringRef> confirm_prompt(base::SysUTF16ToCFStringRef( ReplaceStringPlaceholders(confirm_format, subst, NULL))); scoped_cftyperef<CFStringRef> confirm_cancel(base::SysWideToCFStringRef( l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON))); CFOptionFlags response; if (kCFUserNotificationAlternateResponse == CFUserNotificationDisplayAlert( 0, kCFUserNotificationCautionAlertLevel, NULL, // TODO(port): show the install_icon instead of a default. NULL, NULL, // Sound URL, localization URL. confirm_title, confirm_prompt, NULL, // Default button. confirm_cancel, NULL, // Other button. &response)) { delegate->AbortInstall(); } else { delegate->ContinueInstall(); } #else // TODO(port): Implement some UI. NOTREACHED(); delegate->ContinueInstall(); #endif // OS_* } void ExtensionInstallUI::OnInstallSuccess(Extension* extension) { ShowThemeInfoBar(extension); } void ExtensionInstallUI::OnInstallFailure(const std::string& error) { DCHECK(ui_loop_ == MessageLoop::current()); #if defined(OS_WIN) win_util::MessageBox(NULL, UTF8ToWide(error), L"Extension Install Error", MB_OK | MB_SETFOREGROUND); #elif defined(OS_MACOSX) // There must be a better way to do this, for all platforms. scoped_cftyperef<CFStringRef> message_cf( base::SysUTF8ToCFStringRef(error)); CFOptionFlags response; CFUserNotificationDisplayAlert( 0, kCFUserNotificationNoteAlertLevel, NULL, NULL, NULL, CFSTR("Extension Install Error"), message_cf, NULL, NULL, NULL, &response); #else GtkWidget* dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", error.c_str()); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); #endif } void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) { ShowThemeInfoBar(extension); } void ExtensionInstallUI::ShowThemeInfoBar(Extension* new_theme) { if (!new_theme->IsTheme()) return; Browser* browser = BrowserList::GetLastActiveWithProfile(profile_); if (!browser) return; TabContents* tab_contents = browser->GetSelectedTabContents(); if (!tab_contents) return; // First find any previous theme preview infobars. InfoBarDelegate* old_delegate = NULL; for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) { InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i); if (delegate->AsThemePreviewInfobarDelegate()) { old_delegate = delegate; break; } } // Then either replace that old one or add a new one. InfoBarDelegate* new_delegate = #if defined(TOOLKIT_GTK) new GtkThemeInstalledInfoBarDelegate( tab_contents, new_theme->name(), previous_theme_id_, previous_use_gtk_theme_); #else new ThemeInstalledInfoBarDelegate(tab_contents, new_theme->name(), previous_theme_id_); #endif if (old_delegate) tab_contents->ReplaceInfoBar(old_delegate, new_delegate); else tab_contents->AddInfoBar(new_delegate); } <commit_msg>Fix extension canceling; the CFUserNotification functionality gets a bit weird.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_install_ui.h" #include <map> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/file_util.h" #include "base/rand_util.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/extensions/theme_installed_infobar_delegate.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/extensions/extension.h" #include "grit/browser_resources.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #if defined(OS_WIN) #include "app/win_util.h" #elif defined(OS_MACOSX) #include "base/scoped_cftyperef.h" #include "base/sys_string_conversions.h" #include <CoreFoundation/CFUserNotification.h> #elif defined(TOOLKIT_GTK) #include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h" #include "chrome/browser/gtk/gtk_theme_provider.h" #endif namespace { #if defined(OS_WIN) || defined(TOOLKIT_GTK) static std::wstring GetInstallWarning(Extension* extension) { // If the extension has a plugin, it's easy: the plugin has the most severe // warning. if (!extension->plugins().empty()) return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_FULL_ACCESS); // Otherwise, we go in descending order of severity: all hosts, several hosts, // a single host, no hosts. For each of these, we also have a variation of the // message for when api permissions are also requested. if (extension->HasAccessToAllHosts()) { if (extension->api_permissions().empty()) return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_ALL_HOSTS); else return l10n_util::GetString( IDS_EXTENSION_PROMPT_WARNING_NEW_ALL_HOSTS_AND_BROWSER); } const std::set<std::string> hosts = extension->GetEffectiveHostPermissions(); if (hosts.size() > 1) { if (extension->api_permissions().empty()) return l10n_util::GetString( IDS_EXTENSION_PROMPT_WARNING_NEW_MULTIPLE_HOSTS); else return l10n_util::GetString( IDS_EXTENSION_PROMPT_WARNING_NEW_MULTIPLE_HOSTS_AND_BROWSER); } if (hosts.size() == 1) { if (extension->api_permissions().empty()) return l10n_util::GetStringF( IDS_EXTENSION_PROMPT_WARNING_NEW_SINGLE_HOST, UTF8ToWide(*hosts.begin())); else return l10n_util::GetStringF( IDS_EXTENSION_PROMPT_WARNING_NEW_SINGLE_HOST_AND_BROWSER, UTF8ToWide(*hosts.begin())); } DCHECK(hosts.size() == 0); if (extension->api_permissions().empty()) return L""; else return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_BROWSER); } #endif } // namespace ExtensionInstallUI::ExtensionInstallUI(Profile* profile) : profile_(profile), ui_loop_(MessageLoop::current()) #if defined(TOOLKIT_GTK) ,previous_use_gtk_theme_(false) #endif { } void ExtensionInstallUI::ConfirmInstall(Delegate* delegate, Extension* extension, SkBitmap* install_icon) { DCHECK(ui_loop_ == MessageLoop::current()); // We special-case themes to not show any confirm UI. Instead they are // immediately installed, and then we show an infobar (see OnInstallSuccess) // to allow the user to revert if they don't like it. if (extension->IsTheme()) { // Remember the current theme in case the user pressed undo. Extension* previous_theme = profile_->GetTheme(); if (previous_theme) previous_theme_id_ = previous_theme->id(); #if defined(TOOLKIT_GTK) // On linux, we also need to take the user's system settings into account // to undo theme installation. previous_use_gtk_theme_ = GtkThemeProvider::GetFrom(profile_)->UseGtkTheme(); #endif delegate->ContinueInstall(); return; } #if defined(OS_WIN) || defined(TOOLKIT_GTK) if (!install_icon) { install_icon = ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_DEFAULT_EXTENSION_ICON_128); } ShowExtensionInstallPrompt(profile_, delegate, extension, install_icon, GetInstallWarning(extension)); #elif defined(OS_MACOSX) // TODO(port): Implement nicer UI. // Using CoreFoundation to do this dialog is unimaginably lame but will do // until the UI is redone. scoped_cftyperef<CFStringRef> confirm_title(base::SysWideToCFStringRef( l10n_util::GetString(IDS_EXTENSION_PROMPT_TITLE))); // Build the confirmation prompt, including a heading, a random humorous // warning, and a severe warning. const string16& confirm_format(ASCIIToUTF16("$1\n\n$2\n\n$3")); std::vector<string16> subst; subst.push_back(l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT_HEADING, UTF8ToUTF16(extension->name()))); string16 warnings[] = { l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_1), l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_2), l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_3) }; subst.push_back(warnings[base::RandInt(0, arraysize(warnings) - 1)]); subst.push_back(l10n_util::GetStringUTF16( IDS_EXTENSION_PROMPT_WARNING_SEVERE)); scoped_cftyperef<CFStringRef> confirm_prompt(base::SysUTF16ToCFStringRef( ReplaceStringPlaceholders(confirm_format, subst, NULL))); scoped_cftyperef<CFStringRef> confirm_cancel(base::SysWideToCFStringRef( l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON))); CFOptionFlags response; CFUserNotificationDisplayAlert( 0, kCFUserNotificationCautionAlertLevel, NULL, // TODO(port): show the install_icon instead of a default. NULL, NULL, // Sound URL, localization URL. confirm_title, confirm_prompt, NULL, // Default button. confirm_cancel, NULL, // Other button. &response); if (response == kCFUserNotificationAlternateResponse) { delegate->AbortInstall(); } else { delegate->ContinueInstall(); } #else // TODO(port): Implement some UI. NOTREACHED(); delegate->ContinueInstall(); #endif // OS_* } void ExtensionInstallUI::OnInstallSuccess(Extension* extension) { ShowThemeInfoBar(extension); } void ExtensionInstallUI::OnInstallFailure(const std::string& error) { DCHECK(ui_loop_ == MessageLoop::current()); #if defined(OS_WIN) win_util::MessageBox(NULL, UTF8ToWide(error), L"Extension Install Error", MB_OK | MB_SETFOREGROUND); #elif defined(OS_MACOSX) // There must be a better way to do this, for all platforms. scoped_cftyperef<CFStringRef> message_cf( base::SysUTF8ToCFStringRef(error)); CFOptionFlags response; CFUserNotificationDisplayAlert( 0, kCFUserNotificationNoteAlertLevel, NULL, NULL, NULL, CFSTR("Extension Install Error"), message_cf, NULL, NULL, NULL, &response); #else GtkWidget* dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", error.c_str()); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); #endif } void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) { ShowThemeInfoBar(extension); } void ExtensionInstallUI::ShowThemeInfoBar(Extension* new_theme) { if (!new_theme->IsTheme()) return; Browser* browser = BrowserList::GetLastActiveWithProfile(profile_); if (!browser) return; TabContents* tab_contents = browser->GetSelectedTabContents(); if (!tab_contents) return; // First find any previous theme preview infobars. InfoBarDelegate* old_delegate = NULL; for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) { InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i); if (delegate->AsThemePreviewInfobarDelegate()) { old_delegate = delegate; break; } } // Then either replace that old one or add a new one. InfoBarDelegate* new_delegate = #if defined(TOOLKIT_GTK) new GtkThemeInstalledInfoBarDelegate( tab_contents, new_theme->name(), previous_theme_id_, previous_use_gtk_theme_); #else new ThemeInstalledInfoBarDelegate(tab_contents, new_theme->name(), previous_theme_id_); #endif if (old_delegate) tab_contents->ReplaceInfoBar(old_delegate, new_delegate); else tab_contents->AddInfoBar(new_delegate); } <|endoftext|>
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * \file ComfortPluginInterface.hpp * \author Peter Schüller * * \brief High-level interface for plugins. * * This interface is not as efficient as directly implementing * PluginInterface, but the plugin writer does not need to care about IDs * and the Registry. * * If you convert dlvhex 1.X plugins to dlvhex 2.X, you might want to use * this interface. */ #ifndef COMFORT_PLUGIN_INTERFACE_HPP_INCLUDED_19012011 #define COMFORT_PLUGIN_INTERFACE_HPP_INCLUDED_19012011 #include "dlvhex/PlatformDefinitions.h" #include "dlvhex/PluginInterface.h" #include <cctype> DLVHEX_NAMESPACE_BEGIN // use ModelCallback from PluginInterface.h // use FinalCallback from PluginInterface.h // use PluginConverter from PluginInterface.h // TODO rewriter, optimizer? // use the original PluginInterface, and simply register ComfortPluginAtoms instead of PluginAtoms // you can stream out ComfortTerm objects, e.g., for debugging struct ComfortTerm: public ostream_printable<ComfortTerm> { enum Type { STR, INT }; Type type; std::string strval; int intval; bool isConstant() const { return (type == STR) && (!isupper(strval[0])); } // that's how we represent variables bool isVariable() const { return (type == STR) && (isupper(strval[0])); } bool isInteger() const { return type == INT; } static ComfortTerm createVariable(const std::string& s) { assert(!s.empty() && isupper(s[0])); return ComfortTerm(STR, s, 0); } static ComfortTerm createConstant(const std::string& s) { assert(!s.empty() && !isupper(s[0])); return ComfortTerm(STR, s, 0); } static ComfortTerm createInteger(int i) { return ComfortTerm(INT, "", i); } // equality inline bool operator==(const ComfortTerm& other) const { return (type == other.type) && (type == STR || intval == other.intval) && (type == INT || strval == other.strval); } inline bool operator!=(const ComfortTerm& other) const { return !operator==(other); } // comparability (for putting ComfortTerm into sets) inline bool operator<(const ComfortTerm& other) const { return (type < other.type) || (type == STR && other.type == STR && strval < other.strval) || (type == INT && other.type == INT && intval < other.intval); } // non-virtual (see Printhelpers.hpp) std::ostream& print(std::ostream& o) const; protected: // stupid constructor, use "create..." functions ComfortTerm(Type type, const std::string& strval, int intval): type(type), strval(strval), intval(intval) {} }; typedef std::vector<ComfortTerm> ComfortTuple; // you can stream out ComfortAtom objects, e.g., for debugging struct ComfortAtom: public ostream_printable<ComfortAtom> { #warning TODO strong negation as prefix of first constant! ComfortTuple tuple; inline const std::string& toString() const { if( strval.empty() ) calculateStrVal(); return strval; } // comparability (for putting ComfortAtom into sets) bool operator<(const ComfortAtom& other) const { return tuple < other.tuple; } // non-virtual (see Printhelpers.hpp) std::ostream& print(std::ostream& o) const; inline const std::string& getPredicate() const { assert(!tuple.empty() && !tuple.front().isInteger()); return tuple.front().strval; } // TODO implement setArgument, setArguments, setPredicate, getArguments, getArgument, getArity, isStrongNegated bool unifiesWith(const ComfortAtom& other) const; protected: mutable std::string strval; void calculateStrVal() const; }; // this mimicks the old AtomSet // you can stream out ComfortInterpretation objects, e.g., for debugging struct ComfortInterpretation; struct ComfortInterpretation: public std::set<ComfortAtom>, public ostream_printable<ComfortInterpretation> { // adders // insert one atom void insert(const ComfortAtom&); // insert all atoms from other interpretation void insert(const ComfortInterpretation&); // removers // remove atoms whose predicate matches a string in the given set void remove(const std::set<std::string>& predicates); // remove atoms whose predicate does not match any string in the given set void keep(const std::set<std::string>& predicates); // remove negative atoms #warning todo strong negation void keepPos(); // accessors/helpers bool isConsistent() const; // copy all atoms that match the specified predicate into destination interpretation void matchPredicate(const std::string& predicate, ComfortInterpretation& destination) const; // copy all atoms that unify with the specified predicate into destination interpretation void matchAtom(const ComfortAtom& atom, ComfortInterpretation& destination) const; // return set difference *this \ subtractThis ComfortInterpretation difference(const ComfortInterpretation& subtractThis) const; // non-virtual (see Printhelpers.hpp) std::ostream& print(std::ostream& o) const; bool operator==(const ComfortInterpretation& c2) const; }; class ComfortPluginAtom: public PluginAtom { public: struct ComfortQuery { ComfortInterpretation interpretation; ComfortTuple input; ComfortTuple pattern; }; typedef std::set<ComfortTuple> ComfortAnswer; // as in PluginAtom, your constructor must use addInput...() methods to // define inputs and must use setOutputArity(). ComfortPluginAtom(const std::string& predicate, bool monotonic=false): PluginAtom(predicate, monotonic) {} virtual ~ComfortPluginAtom() {} // you have to implement this method virtual void retrieve(const ComfortQuery&, ComfortAnswer&) = 0; protected: // we implemented the original retrieve here, so you don't have to take care of this anymore virtual void retrieve(const Query& q, Answer& a); }; DLVHEX_NAMESPACE_END #endif // COMFORT_PLUGIN_INTERFACE_HPP_INCLUDED_19012011 <commit_msg>add some methods to ComfortInterpretation<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * \file ComfortPluginInterface.hpp * \author Peter Schüller * * \brief High-level interface for plugins. * * This interface is not as efficient as directly implementing * PluginInterface, but the plugin writer does not need to care about IDs * and the Registry. * * If you convert dlvhex 1.X plugins to dlvhex 2.X, you might want to use * this interface. */ #ifndef COMFORT_PLUGIN_INTERFACE_HPP_INCLUDED_19012011 #define COMFORT_PLUGIN_INTERFACE_HPP_INCLUDED_19012011 #include "dlvhex/PlatformDefinitions.h" #include "dlvhex/PluginInterface.h" #include <cctype> DLVHEX_NAMESPACE_BEGIN // use ModelCallback from PluginInterface.h // use FinalCallback from PluginInterface.h // use PluginConverter from PluginInterface.h // TODO rewriter, optimizer? // use the original PluginInterface, and simply register ComfortPluginAtoms instead of PluginAtoms // you can stream out ComfortTerm objects, e.g., for debugging struct ComfortTerm: public ostream_printable<ComfortTerm> { enum Type { STR, INT }; Type type; std::string strval; int intval; bool isConstant() const { return (type == STR) && (!isupper(strval[0])); } // that's how we represent variables bool isVariable() const { return (type == STR) && (isupper(strval[0])); } bool isInteger() const { return type == INT; } bool isAnon() const { return type == STR && strval == "_"; } static ComfortTerm createVariable(const std::string& s) { assert(!s.empty() && isupper(s[0])); return ComfortTerm(STR, s, 0); } static ComfortTerm createConstant(const std::string& s) { assert(!s.empty() && !isupper(s[0])); return ComfortTerm(STR, s, 0); } static ComfortTerm createInteger(int i) { return ComfortTerm(INT, "", i); } // equality inline bool operator==(const ComfortTerm& other) const { return (type == other.type) && (type == STR || intval == other.intval) && (type == INT || strval == other.strval); } inline bool operator!=(const ComfortTerm& other) const { return !operator==(other); } // comparability (for putting ComfortTerm into sets) inline bool operator<(const ComfortTerm& other) const { return (type < other.type) || (type == STR && other.type == STR && strval < other.strval) || (type == INT && other.type == INT && intval < other.intval); } // non-virtual (see Printhelpers.hpp) std::ostream& print(std::ostream& o) const; protected: // stupid constructor, use "create..." functions ComfortTerm(Type type, const std::string& strval, int intval): type(type), strval(strval), intval(intval) {} public: ComfortTerm() : type(STR), strval("") {} }; typedef std::vector<ComfortTerm> ComfortTuple; // you can stream out ComfortAtom objects, e.g., for debugging struct ComfortAtom: public ostream_printable<ComfortAtom> { #warning TODO strong negation as prefix of first constant! ComfortTuple tuple; inline const std::string& toString() const { if( strval.empty() ) calculateStrVal(); return strval; } // comparability (for putting ComfortAtom into sets) bool operator<(const ComfortAtom& other) const { return tuple < other.tuple; } // non-virtual (see Printhelpers.hpp) std::ostream& print(std::ostream& o) const; inline const std::string& getPredicate() const { assert(!tuple.empty() && !tuple.front().isInteger()); return tuple.front().strval; } inline const ComfortTuple getArguments() const { ComfortTuple ct = tuple; assert(ct.size() > 0); ct.erase(ct.begin()); return ct; } inline const ComfortTerm getArgument(int index) const { assert(index >= 0 && index < tuple.size()); return tuple[index]; } inline unsigned getArity() const { return tuple.size() - 1; } inline unsigned isStrongNegated() const { assert(!tuple.empty() && !tuple.front().isInteger()); assert(!tuple[0].strval.length() == 0); return tuple[0].strval[0] == '-'; } inline void setArgument(int index, ComfortTerm arg) { assert(index >= 0 && index < tuple.size()); tuple[index] = arg; } // TODO implement setArgument, setArguments, setPredicate, getArguments, getArgument, getArity, isStrongNegated bool unifiesWith(const ComfortAtom& other) const; protected: mutable std::string strval; void calculateStrVal() const; }; // this mimicks the old AtomSet // you can stream out ComfortInterpretation objects, e.g., for debugging struct ComfortInterpretation; struct ComfortInterpretation: public std::set<ComfortAtom>, public ostream_printable<ComfortInterpretation> { // adders // insert one atom void insert(const ComfortAtom&); // insert all atoms from other interpretation void insert(const ComfortInterpretation&); // removers // remove atoms whose predicate matches a string in the given set void remove(const std::set<std::string>& predicates); // remove atoms whose predicate does not match any string in the given set void keep(const std::set<std::string>& predicates); // remove negative atoms #warning todo strong negation void keepPos(); // accessors/helpers bool isConsistent() const; // copy all atoms that match the specified predicate into destination interpretation void matchPredicate(const std::string& predicate, ComfortInterpretation& destination) const; // copy all atoms that unify with the specified predicate into destination interpretation void matchAtom(const ComfortAtom& atom, ComfortInterpretation& destination) const; // return set difference *this \ subtractThis ComfortInterpretation difference(const ComfortInterpretation& subtractThis) const; // non-virtual (see Printhelpers.hpp) std::ostream& print(std::ostream& o) const; bool operator==(const ComfortInterpretation& c2) const; }; class ComfortPluginAtom: public PluginAtom { public: struct ComfortQuery { ComfortInterpretation interpretation; ComfortTuple input; ComfortTuple pattern; }; typedef std::set<ComfortTuple> ComfortAnswer; // as in PluginAtom, your constructor must use addInput...() methods to // define inputs and must use setOutputArity(). ComfortPluginAtom(const std::string& predicate, bool monotonic=false): PluginAtom(predicate, monotonic) {} virtual ~ComfortPluginAtom() {} // you have to implement this method virtual void retrieve(const ComfortQuery&, ComfortAnswer&) = 0; protected: // we implemented the original retrieve here, so you don't have to take care of this anymore virtual void retrieve(const Query& q, Answer& a); }; DLVHEX_NAMESPACE_END #endif // COMFORT_PLUGIN_INTERFACE_HPP_INCLUDED_19012011 <|endoftext|>
<commit_before>/** * Non-metric Space Library * * Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info). * With contributions from Lawrence Cayton (http://lcayton.com/). * * For the complete list of contributors and further details see: * https://github.com/searchivarius/NonMetricSpaceLib * * Copyright (c) 2010--2013 * * This code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * */ #include <algorithm> #include <sstream> #include <unordered_map> #include "space.h" #include "rangequery.h" #include "knnquery.h" #include "incremental_quick_select.h" #include "permutation_inverted_index.h" #include "utils.h" namespace similarity { using namespace std; template <typename dist_t> PermutationInvertedIndex<dist_t>::PermutationInvertedIndex( const Space<dist_t>* space, const ObjectVector& data, const size_t num_pivot, const size_t num_pivot_index, const size_t num_pivot_search, const size_t max_pos_diff, const double db_scan_fraction) : data_(data), // reference db_scan_(static_cast<size_t>(db_scan_fraction * data.size())), num_pivot_index_(min(num_pivot_index, num_pivot_search + max_pos_diff)), num_pivot_search_(num_pivot_search), max_pos_diff_(max_pos_diff) { CHECK(num_pivot_search > 0); CHECK(num_pivot_search <= num_pivot_index); CHECK(num_pivot_index <= num_pivot); LOG(INFO) << "# pivots = " << num_pivot; LOG(INFO) << "# pivots to index requested (ki) = " << num_pivot_index; LOG(INFO) << "# pivots to index effective (ki) = " << num_pivot_index_; LOG(INFO) << "# pivots search (ks) = " << num_pivot_search_; LOG(INFO) << "# max position difference = " << max_pos_diff_; GetPermutationPivot(data, space, num_pivot, &pivot_); posting_lists_.resize(num_pivot); for (size_t id = 0; id < data.size(); ++id) { Permutation perm; GetPermutation(pivot_, space, data[id], &perm); for (size_t j = 0; j < perm.size(); ++j) { if (perm[j] < num_pivot_index_) { posting_lists_[j].push_back(ObjectInvEntry(id, perm[j])); } } } for (size_t j = 0; j < posting_lists_.size(); ++j) { sort(posting_lists_[j].begin(), posting_lists_[j].end()); } } template <typename dist_t> PermutationInvertedIndex<dist_t>::~PermutationInvertedIndex() { } template <typename dist_t> const string PermutationInvertedIndex<dist_t>::ToString() const { stringstream str; str << "inverted index"; return str.str(); } template <typename dist_t> template <typename QueryType> void PermutationInvertedIndex<dist_t>::GenSearch(QueryType* query) { Permutation perm_q; GetPermutation(pivot_, query, &perm_q); // TODO @leo or @bileg If you uncomment, you get higher recall for some reason, strange... #if 0 vector<IntInt> perm_dists(data_.size()); for (size_t i = 0; i < data_.size(); ++i) { perm_dists[i] = make_pair(num_pivot_search_ * num_pivot_index_, i); } for (size_t i = 0; i < perm_q.size(); ++i) { if (perm_q[i] < num_pivot_search_) { for (auto& v : posting_lists_[i]) { // spearman footrule int spearman_dist = std::abs(static_cast<int>(v.pos_) - static_cast<int>(perm_q[i])); // spearman rho //spearman_dist = spearman_dist * spearman_dist; perm_dists[v.id_].first += spearman_dist - static_cast<int>(num_pivot_index_); } } } IncrementalQuickSelect<IntInt> quick_select(perm_dists); size_t scan_qty = min(db_scan_, perm_dists.size()); for (size_t i = 0; i < scan_qty; ++i) { const size_t idx = quick_select.GetNext().second; quick_select.Next(); query->CheckAndAddToResult(data_[idx]); } #else vector<vector<ObjectInvEntry>::iterator> iterBegs; vector<vector<ObjectInvEntry>::iterator> iterEnds; size_t maxScanQty = 0; for (size_t i = 0; i < perm_q.size(); ++i) { if (perm_q[i] < num_pivot_search_) { ObjectInvEntry o1(0, std::max(perm_q[i] - static_cast<int>(max_pos_diff_), 0)); ObjectInvEntry o2(0, std::min(perm_q[i] + static_cast<int>(max_pos_diff_) + 1, static_cast<int>(num_pivot_index_))); auto itEnd = lower_bound(posting_lists_[i].begin(), posting_lists_[i].end(), o2); auto it = lower_bound(posting_lists_[i].begin(), itEnd, o1); maxScanQty += itEnd - it; iterBegs.push_back(it); iterEnds.push_back(itEnd); } } bool bUseMap = maxScanQty < USE_MAP_THRESHOLD * data_.size(); // TODO: @leo this is rather adhoc vector<IntInt> perm_dists; //LOG(INFO) << "bUseMap: " << bUseMap << " maxScanQty: " << maxScanQty << " data.size() " << data_.size(); if (bUseMap) { unordered_map<int,int> perm_dists_set; int MaxDist = (num_pivot_search_ - 1) * num_pivot_index_; for (size_t i = 0, inum = 0; i < perm_q.size(); ++i) { if (perm_q[i] < num_pivot_search_) { auto it = iterBegs[inum]; const auto& itEnd = iterEnds[inum]; ++inum; for (; it != itEnd; ++it) { int id = it->id_; int pos = it->pos_; CHECK(std::abs(pos - perm_q[i]) <= max_pos_diff_); // spearman footrule int spearman_dist = std::abs(static_cast<int>(pos) - static_cast<int>(perm_q[i])); auto iter = perm_dists_set.find(id); if (iter != perm_dists_set.end()) { iter->second += spearman_dist - static_cast<int>(num_pivot_index_); } else { perm_dists_set.insert(make_pair(id, MaxDist + spearman_dist)); } } } } // Copy data from set to array perm_dists.reserve(perm_dists_set.size()); for(const auto it: perm_dists_set) { // Id goes second perm_dists.push_back(make_pair(it.second, it.first)); } } else { int MaxDist = num_pivot_search_ * num_pivot_index_; perm_dists.reserve(data_.size()); for (size_t i = 0; i < data_.size(); ++i) perm_dists.push_back(make_pair(MaxDist, i)); for (size_t i = 0, inum = 0; i < perm_q.size(); ++i) { if (perm_q[i] < num_pivot_search_) { auto it = iterBegs[inum]; const auto& itEnd = iterEnds[inum]; ++inum; for (; it < itEnd; ++it) { int id = it->id_; int pos = it->pos_; CHECK(std::abs(pos - perm_q[i]) <= max_pos_diff_); // spearman footrule int spearman_dist = std::abs(static_cast<int>(pos) - static_cast<int>(perm_q[i])); perm_dists[id].first += spearman_dist - static_cast<int>(num_pivot_index_); } } } } size_t scan_qty = min(db_scan_, perm_dists.size()); IncrementalQuickSelect<IntInt> quick_select(perm_dists); for (size_t i = 0; i < scan_qty; ++i) { const size_t idx = quick_select.GetNext().second; quick_select.Next(); query->CheckAndAddToResult(data_[idx]); } #endif } template <typename dist_t> void PermutationInvertedIndex<dist_t>::Search( RangeQuery<dist_t>* query) { GenSearch(query); } template <typename dist_t> void PermutationInvertedIndex<dist_t>::Search( KNNQuery<dist_t>* query) { GenSearch(query); } template class PermutationInvertedIndex<float>; template class PermutationInvertedIndex<double>; template class PermutationInvertedIndex<int>; } // namespace similarity <commit_msg>another renaming...<commit_after>/** * Non-metric Space Library * * Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info). * With contributions from Lawrence Cayton (http://lcayton.com/). * * For the complete list of contributors and further details see: * https://github.com/searchivarius/NonMetricSpaceLib * * Copyright (c) 2010--2013 * * This code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * */ #include <algorithm> #include <sstream> #include <unordered_map> #include "space.h" #include "rangequery.h" #include "knnquery.h" #include "incremental_quick_select.h" #include "permutation_inverted_index.h" #include "utils.h" namespace similarity { using namespace std; template <typename dist_t> PermutationInvertedIndex<dist_t>::PermutationInvertedIndex( const Space<dist_t>* space, const ObjectVector& data, const size_t num_pivot, const size_t num_pivot_index, const size_t num_pivot_search, const size_t max_pos_diff, const double db_scan_fraction) : data_(data), // reference db_scan_(static_cast<size_t>(db_scan_fraction * data.size())), num_pivot_index_(min(num_pivot_index, num_pivot_search + max_pos_diff)), num_pivot_search_(num_pivot_search), max_pos_diff_(max_pos_diff) { CHECK(num_pivot_search > 0); CHECK(num_pivot_search <= num_pivot_index); CHECK(num_pivot_index <= num_pivot); LOG(INFO) << "# pivots = " << num_pivot; LOG(INFO) << "# pivots to index requested (ki) = " << num_pivot_index; LOG(INFO) << "# pivots to index effective (ki) = " << num_pivot_index_; LOG(INFO) << "# pivots search (ks) = " << num_pivot_search_; LOG(INFO) << "# max position difference = " << max_pos_diff_; GetPermutationPivot(data, space, num_pivot, &pivot_); posting_lists_.resize(num_pivot); for (size_t id = 0; id < data.size(); ++id) { Permutation perm; GetPermutation(pivot_, space, data[id], &perm); for (size_t j = 0; j < perm.size(); ++j) { if (perm[j] < num_pivot_index_) { posting_lists_[j].push_back(ObjectInvEntry(id, perm[j])); } } } for (size_t j = 0; j < posting_lists_.size(); ++j) { sort(posting_lists_[j].begin(), posting_lists_[j].end()); } } template <typename dist_t> PermutationInvertedIndex<dist_t>::~PermutationInvertedIndex() { } template <typename dist_t> const string PermutationInvertedIndex<dist_t>::ToString() const { stringstream str; str << "(permutation) inverted index"; return str.str(); } template <typename dist_t> template <typename QueryType> void PermutationInvertedIndex<dist_t>::GenSearch(QueryType* query) { Permutation perm_q; GetPermutation(pivot_, query, &perm_q); // TODO @leo or @bileg If you uncomment, you get higher recall for some reason, strange... #if 0 vector<IntInt> perm_dists(data_.size()); for (size_t i = 0; i < data_.size(); ++i) { perm_dists[i] = make_pair(num_pivot_search_ * num_pivot_index_, i); } for (size_t i = 0; i < perm_q.size(); ++i) { if (perm_q[i] < num_pivot_search_) { for (auto& v : posting_lists_[i]) { // spearman footrule int spearman_dist = std::abs(static_cast<int>(v.pos_) - static_cast<int>(perm_q[i])); // spearman rho //spearman_dist = spearman_dist * spearman_dist; perm_dists[v.id_].first += spearman_dist - static_cast<int>(num_pivot_index_); } } } IncrementalQuickSelect<IntInt> quick_select(perm_dists); size_t scan_qty = min(db_scan_, perm_dists.size()); for (size_t i = 0; i < scan_qty; ++i) { const size_t idx = quick_select.GetNext().second; quick_select.Next(); query->CheckAndAddToResult(data_[idx]); } #else vector<vector<ObjectInvEntry>::iterator> iterBegs; vector<vector<ObjectInvEntry>::iterator> iterEnds; size_t maxScanQty = 0; for (size_t i = 0; i < perm_q.size(); ++i) { if (perm_q[i] < num_pivot_search_) { ObjectInvEntry o1(0, std::max(perm_q[i] - static_cast<int>(max_pos_diff_), 0)); ObjectInvEntry o2(0, std::min(perm_q[i] + static_cast<int>(max_pos_diff_) + 1, static_cast<int>(num_pivot_index_))); auto itEnd = lower_bound(posting_lists_[i].begin(), posting_lists_[i].end(), o2); auto it = lower_bound(posting_lists_[i].begin(), itEnd, o1); maxScanQty += itEnd - it; iterBegs.push_back(it); iterEnds.push_back(itEnd); } } bool bUseMap = maxScanQty < USE_MAP_THRESHOLD * data_.size(); // TODO: @leo this is rather adhoc vector<IntInt> perm_dists; //LOG(INFO) << "bUseMap: " << bUseMap << " maxScanQty: " << maxScanQty << " data.size() " << data_.size(); if (bUseMap) { unordered_map<int,int> perm_dists_set; int MaxDist = (num_pivot_search_ - 1) * num_pivot_index_; for (size_t i = 0, inum = 0; i < perm_q.size(); ++i) { if (perm_q[i] < num_pivot_search_) { auto it = iterBegs[inum]; const auto& itEnd = iterEnds[inum]; ++inum; for (; it != itEnd; ++it) { int id = it->id_; int pos = it->pos_; CHECK(std::abs(pos - perm_q[i]) <= max_pos_diff_); // spearman footrule int spearman_dist = std::abs(static_cast<int>(pos) - static_cast<int>(perm_q[i])); auto iter = perm_dists_set.find(id); if (iter != perm_dists_set.end()) { iter->second += spearman_dist - static_cast<int>(num_pivot_index_); } else { perm_dists_set.insert(make_pair(id, MaxDist + spearman_dist)); } } } } // Copy data from set to array perm_dists.reserve(perm_dists_set.size()); for(const auto it: perm_dists_set) { // Id goes second perm_dists.push_back(make_pair(it.second, it.first)); } } else { int MaxDist = num_pivot_search_ * num_pivot_index_; perm_dists.reserve(data_.size()); for (size_t i = 0; i < data_.size(); ++i) perm_dists.push_back(make_pair(MaxDist, i)); for (size_t i = 0, inum = 0; i < perm_q.size(); ++i) { if (perm_q[i] < num_pivot_search_) { auto it = iterBegs[inum]; const auto& itEnd = iterEnds[inum]; ++inum; for (; it < itEnd; ++it) { int id = it->id_; int pos = it->pos_; CHECK(std::abs(pos - perm_q[i]) <= max_pos_diff_); // spearman footrule int spearman_dist = std::abs(static_cast<int>(pos) - static_cast<int>(perm_q[i])); perm_dists[id].first += spearman_dist - static_cast<int>(num_pivot_index_); } } } } size_t scan_qty = min(db_scan_, perm_dists.size()); IncrementalQuickSelect<IntInt> quick_select(perm_dists); for (size_t i = 0; i < scan_qty; ++i) { const size_t idx = quick_select.GetNext().second; quick_select.Next(); query->CheckAndAddToResult(data_[idx]); } #endif } template <typename dist_t> void PermutationInvertedIndex<dist_t>::Search( RangeQuery<dist_t>* query) { GenSearch(query); } template <typename dist_t> void PermutationInvertedIndex<dist_t>::Search( KNNQuery<dist_t>* query) { GenSearch(query); } template class PermutationInvertedIndex<float>; template class PermutationInvertedIndex<double>; template class PermutationInvertedIndex<int>; } // namespace similarity <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "docsumwriter.h" #include "docsumstate.h" #include "docsum_field_writer_state.h" #include <vespa/searchlib/common/transport.h> #include <vespa/searchlib/util/slime_output_raw_buf_adapter.h> #include <vespa/searchlib/attribute/iattributemanager.h> #include <vespa/vespalib/data/slime/slime.h> #include <vespa/log/log.h> LOG_SETUP(".searchlib.docsummary.docsumwriter"); using namespace vespalib::slime::convenience; namespace search::docsummary { uint32_t IDocsumWriter::slime2RawBuf(const Slime & slime, RawBuf & buf) { const uint32_t preUsed = buf.GetUsedLen(); const uint32_t magic = ::search::fs4transport::SLIME_MAGIC_ID; buf.append(&magic, sizeof(magic)); SlimeOutputRawBufAdapter adapter(buf); vespalib::slime::BinaryFormat::encode(slime, adapter); return (buf.GetUsedLen() - preUsed); } DynamicDocsumWriter::ResolveClassInfo DynamicDocsumWriter::resolveClassInfo(vespalib::stringref outputClassName, uint32_t inputClassId) const { DynamicDocsumWriter::ResolveClassInfo rci = resolveOutputClass(outputClassName); if (!rci.mustSkip && !rci.allGenerated) { resolveInputClass(rci, inputClassId); } return rci; } DynamicDocsumWriter::ResolveClassInfo DynamicDocsumWriter::resolveOutputClass(vespalib::stringref summaryClass) const { DynamicDocsumWriter::ResolveClassInfo result; uint32_t id = _defaultOutputClass; id = _resultConfig->LookupResultClassId(summaryClass, id); if (id != ResultConfig::NoClassID()) { const ResultClass *oC = _resultConfig->LookupResultClass(id); if (oC == nullptr) { LOG(warning, "Illegal docsum class requested: %d, using empty docsum for documents", id); result.mustSkip = true; } else { result.outputClass = oC; const ResultClass::DynamicInfo *rcInfo = oC->getDynamicInfo(); if (rcInfo->_generateCnt == oC->GetNumEntries()) { LOG_ASSERT(rcInfo->_overrideCnt == rcInfo->_generateCnt); result.allGenerated = true; } result.outputClassInfo = rcInfo; } } result.outputClassId = id; return result; } void DynamicDocsumWriter::resolveInputClass(ResolveClassInfo &rci, uint32_t id) const { rci.inputClass = _resultConfig->LookupResultClass(id); if (rci.inputClass == nullptr) { rci.mustSkip = true; return; } if (rci.outputClass == nullptr) { LOG_ASSERT(rci.outputClassId == ResultConfig::NoClassID()); rci.outputClassId = id; rci.outputClass = rci.inputClass; rci.outputClassInfo = rci.inputClass->getDynamicInfo(); } } static void convertEntry(GetDocsumsState *state, const ResConfigEntry *resCfg, const ResEntry *entry, Inserter &inserter, Slime &slime) { using vespalib::slime::BinaryFormat; const char *ptr; uint32_t len; LOG_ASSERT(resCfg != nullptr && entry != nullptr); switch (resCfg->_type) { case RES_INT: case RES_SHORT: case RES_BYTE: inserter.insertLong(entry->_intval); break; case RES_BOOL: inserter.insertBool(entry->_intval != 0); break; case RES_FLOAT: case RES_DOUBLE: inserter.insertDouble(entry->_doubleval); break; case RES_INT64: inserter.insertLong(entry->_int64val); break; case RES_STRING: case RES_LONG_STRING: case RES_FEATUREDATA: case RES_XMLSTRING: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); inserter.insertString(Memory(ptr, len)); break; case RES_DATA: case RES_TENSOR: case RES_LONG_DATA: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); inserter.insertData(Memory(ptr, len)); break; case RES_JSONSTRING: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); if (len != 0) { // note: 'JSONSTRING' really means 'structured data' size_t d = BinaryFormat::decode_into(Memory(ptr, len), slime, inserter); if (d != len) { LOG(warning, "could not decode %u bytes: %zu bytes decoded", len, d); } } break; } } void DynamicDocsumWriter::insertDocsum(const ResolveClassInfo & rci, uint32_t docid, GetDocsumsState *state, IDocsumStore *docinfos, vespalib::Slime & slime, vespalib::slime::Inserter & topInserter) { if (rci.allGenerated) { // generate docsum entry on-the-fly vespalib::slime::Cursor & docsum = topInserter.insertObject(); for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) { const ResConfigEntry *resCfg = rci.outputClass->GetEntry(i); IDocsumFieldWriter *writer = _overrideTable[resCfg->_enumValue]; if (! writer->isDefaultValue(docid, state)) { const Memory field_name(resCfg->_bindname.data(), resCfg->_bindname.size()); ObjectInserter inserter(docsum, field_name); writer->insertField(docid, nullptr, state, resCfg->_type, inserter); } } } else { // look up docsum entry DocsumStoreValue value = docinfos->getMappedDocsum(docid); // re-pack docsum blob GeneralResult gres(rci.inputClass); if (! gres.inplaceUnpack(value)) { LOG(debug, "Unpack failed: illegal docsum entry for document %d. This is expected during lidspace compaction.", docid); topInserter.insertNix(); return; } vespalib::slime::Cursor & docsum = topInserter.insertObject(); for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) { const ResConfigEntry *outCfg = rci.outputClass->GetEntry(i); IDocsumFieldWriter *writer = _overrideTable[outCfg->_enumValue]; const Memory field_name(outCfg->_bindname.data(), outCfg->_bindname.size()); ObjectInserter inserter(docsum, field_name); if (writer != nullptr) { //TODO: Need to add test for writer->isDefaultValue writer->insertField(docid, &gres, state, outCfg->_type, inserter); } else { //TODO: Need to add similar test as writer->isDefaultValue if (rci.inputClass == rci.outputClass) { convertEntry(state, outCfg, gres.GetEntry(i), inserter, slime); } else { int inIdx = rci.inputClass->GetIndexFromEnumValue(outCfg->_enumValue); const ResConfigEntry *inCfg = rci.inputClass->GetEntry(inIdx); if (inCfg != nullptr && inCfg->_type == outCfg->_type) { // copy field const ResEntry *entry = gres.GetEntry(inIdx); LOG_ASSERT(entry != nullptr); convertEntry(state, outCfg, entry, inserter, slime); } } } } } } DynamicDocsumWriter::DynamicDocsumWriter( ResultConfig *config, KeywordExtractor *extractor) : _resultConfig(config), _keywordExtractor(extractor), _defaultOutputClass(ResultConfig::NoClassID()), _numClasses(config->GetNumResultClasses()), _numEnumValues(config->GetFieldNameEnum().GetNumEntries()), _numFieldWriterStates(0), _classInfoTable(nullptr), _overrideTable(nullptr) { LOG_ASSERT(config != nullptr); _classInfoTable = new ResultClass::DynamicInfo[_numClasses]; _overrideTable = new IDocsumFieldWriter*[_numEnumValues]; uint32_t i = 0; for (ResultConfig::iterator it(config->begin()), mt(config->end()); it != mt; it++, i++) { _classInfoTable[i]._overrideCnt = 0; _classInfoTable[i]._generateCnt = 0; it->setDynamicInfo(&(_classInfoTable[i])); } LOG_ASSERT(i == _numClasses); for (i = 0; i < _numEnumValues; i++) _overrideTable[i] = nullptr; } DynamicDocsumWriter::~DynamicDocsumWriter() { delete _resultConfig; delete _keywordExtractor; delete [] _classInfoTable; for (uint32_t i = 0; i < _numEnumValues; i++) delete _overrideTable[i]; delete [] _overrideTable; } bool DynamicDocsumWriter::SetDefaultOutputClass(uint32_t classID) { const ResultClass *resClass = _resultConfig->LookupResultClass(classID); if (resClass == nullptr || _defaultOutputClass != ResultConfig::NoClassID()) { if (resClass == nullptr) { LOG(warning, "cannot set default output docsum class to %d; class not defined", classID); } else if (_defaultOutputClass != ResultConfig::NoClassID()) { LOG(warning, "cannot set default output docsum class to %d; value already set", classID); } return false; } _defaultOutputClass = classID; return true; } bool DynamicDocsumWriter::Override(const char *fieldName, IDocsumFieldWriter *writer) { uint32_t fieldEnumValue = _resultConfig->GetFieldNameEnum().Lookup(fieldName); if (fieldEnumValue >= _numEnumValues || _overrideTable[fieldEnumValue] != nullptr) { if (fieldEnumValue >= _numEnumValues) { LOG(warning, "cannot override docsum field '%s'; undefined field name", fieldName); } else if (_overrideTable[fieldEnumValue] != nullptr) { LOG(warning, "cannot override docsum field '%s'; already overridden", fieldName); } delete writer; return false; } writer->setIndex(fieldEnumValue); _overrideTable[fieldEnumValue] = writer; if (writer->setFieldWriterStateIndex(_numFieldWriterStates)) { ++_numFieldWriterStates; } for (auto & entry : *_resultConfig) { if (entry.GetIndexFromEnumValue(fieldEnumValue) >= 0) { ResultClass::DynamicInfo *info = entry.getDynamicInfo(); info->_overrideCnt++; if (writer->IsGenerated()) info->_generateCnt++; } } return true; } void DynamicDocsumWriter::InitState(IAttributeManager & attrMan, GetDocsumsState *state) { state->_kwExtractor = _keywordExtractor; state->_attrCtx = attrMan.createContext(); state->_attributes.resize(_numEnumValues); state->_fieldWriterStates.resize(_numFieldWriterStates); for (size_t i(0); i < state->_attributes.size(); i++) { const IDocsumFieldWriter *fw = _overrideTable[i]; if (fw) { const vespalib::string & attributeName = fw->getAttributeName(); if (!attributeName.empty()) { state->_attributes[i] = state->_attrCtx->getAttribute(attributeName); } } } } uint32_t DynamicDocsumWriter::WriteDocsum(uint32_t docid, GetDocsumsState *state, IDocsumStore *docinfos, search::RawBuf *target) { vespalib::Slime slime; vespalib::slime::SlimeInserter inserter(slime); ResolveClassInfo rci = resolveClassInfo(state->_args.getResultClassName(), docinfos->getSummaryClassId()); insertDocsum(rci, docid, state, docinfos, slime, inserter); return slime2RawBuf(slime, *target); } } <commit_msg>skip fields which are empty or only have the default value<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "docsumwriter.h" #include "docsumstate.h" #include "docsum_field_writer_state.h" #include <vespa/searchlib/common/transport.h> #include <vespa/searchlib/util/slime_output_raw_buf_adapter.h> #include <vespa/searchlib/attribute/iattributemanager.h> #include <vespa/vespalib/data/slime/slime.h> #include <vespa/log/log.h> LOG_SETUP(".searchlib.docsummary.docsumwriter"); using namespace vespalib::slime::convenience; namespace search::docsummary { uint32_t IDocsumWriter::slime2RawBuf(const Slime & slime, RawBuf & buf) { const uint32_t preUsed = buf.GetUsedLen(); const uint32_t magic = ::search::fs4transport::SLIME_MAGIC_ID; buf.append(&magic, sizeof(magic)); SlimeOutputRawBufAdapter adapter(buf); vespalib::slime::BinaryFormat::encode(slime, adapter); return (buf.GetUsedLen() - preUsed); } DynamicDocsumWriter::ResolveClassInfo DynamicDocsumWriter::resolveClassInfo(vespalib::stringref outputClassName, uint32_t inputClassId) const { DynamicDocsumWriter::ResolveClassInfo rci = resolveOutputClass(outputClassName); if (!rci.mustSkip && !rci.allGenerated) { resolveInputClass(rci, inputClassId); } return rci; } DynamicDocsumWriter::ResolveClassInfo DynamicDocsumWriter::resolveOutputClass(vespalib::stringref summaryClass) const { DynamicDocsumWriter::ResolveClassInfo result; uint32_t id = _defaultOutputClass; id = _resultConfig->LookupResultClassId(summaryClass, id); if (id != ResultConfig::NoClassID()) { const ResultClass *oC = _resultConfig->LookupResultClass(id); if (oC == nullptr) { LOG(warning, "Illegal docsum class requested: %d, using empty docsum for documents", id); result.mustSkip = true; } else { result.outputClass = oC; const ResultClass::DynamicInfo *rcInfo = oC->getDynamicInfo(); if (rcInfo->_generateCnt == oC->GetNumEntries()) { LOG_ASSERT(rcInfo->_overrideCnt == rcInfo->_generateCnt); result.allGenerated = true; } result.outputClassInfo = rcInfo; } } result.outputClassId = id; return result; } void DynamicDocsumWriter::resolveInputClass(ResolveClassInfo &rci, uint32_t id) const { rci.inputClass = _resultConfig->LookupResultClass(id); if (rci.inputClass == nullptr) { rci.mustSkip = true; return; } if (rci.outputClass == nullptr) { LOG_ASSERT(rci.outputClassId == ResultConfig::NoClassID()); rci.outputClassId = id; rci.outputClass = rci.inputClass; rci.outputClassInfo = rci.inputClass->getDynamicInfo(); } } constexpr uint32_t default_32bits_int = (uint32_t)std::numeric_limits<int32_t>::min(); constexpr uint64_t default_64bits_int = (uint64_t)std::numeric_limits<int64_t>::min(); static void convertEntry(GetDocsumsState *state, const ResConfigEntry *resCfg, const ResEntry *entry, Inserter &inserter, Slime &slime) { using vespalib::slime::BinaryFormat; const char *ptr; uint32_t len; LOG_ASSERT(resCfg != nullptr && entry != nullptr); switch (resCfg->_type) { case RES_INT: case RES_SHORT: case RES_BYTE: if (entry->_intval != default_32bits_int) { inserter.insertLong(entry->_intval); } break; case RES_BOOL: inserter.insertBool(entry->_intval != 0); break; case RES_FLOAT: case RES_DOUBLE: if (! std::isnan(entry->_doubleval)) { inserter.insertDouble(entry->_doubleval); } break; case RES_INT64: if (entry->_int64val != default_64bits_int) { inserter.insertLong(entry->_int64val); } break; case RES_STRING: case RES_LONG_STRING: case RES_FEATUREDATA: case RES_XMLSTRING: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); if (len != 0) { inserter.insertString(Memory(ptr, len)); } break; case RES_DATA: case RES_TENSOR: case RES_LONG_DATA: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); if (len != 0) { inserter.insertData(Memory(ptr, len)); } break; case RES_JSONSTRING: entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace); if (len != 0) { // note: 'JSONSTRING' really means 'structured data' size_t d = BinaryFormat::decode_into(Memory(ptr, len), slime, inserter); if (d != len) { LOG(warning, "could not decode %u bytes: %zu bytes decoded", len, d); } } break; } } void DynamicDocsumWriter::insertDocsum(const ResolveClassInfo & rci, uint32_t docid, GetDocsumsState *state, IDocsumStore *docinfos, vespalib::Slime & slime, vespalib::slime::Inserter & topInserter) { if (rci.allGenerated) { // generate docsum entry on-the-fly vespalib::slime::Cursor & docsum = topInserter.insertObject(); for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) { const ResConfigEntry *resCfg = rci.outputClass->GetEntry(i); IDocsumFieldWriter *writer = _overrideTable[resCfg->_enumValue]; if (! writer->isDefaultValue(docid, state)) { const Memory field_name(resCfg->_bindname.data(), resCfg->_bindname.size()); ObjectInserter inserter(docsum, field_name); writer->insertField(docid, nullptr, state, resCfg->_type, inserter); } } } else { // look up docsum entry DocsumStoreValue value = docinfos->getMappedDocsum(docid); // re-pack docsum blob GeneralResult gres(rci.inputClass); if (! gres.inplaceUnpack(value)) { LOG(debug, "Unpack failed: illegal docsum entry for document %d. This is expected during lidspace compaction.", docid); topInserter.insertNix(); return; } vespalib::slime::Cursor & docsum = topInserter.insertObject(); for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) { const ResConfigEntry *outCfg = rci.outputClass->GetEntry(i); IDocsumFieldWriter *writer = _overrideTable[outCfg->_enumValue]; const Memory field_name(outCfg->_bindname.data(), outCfg->_bindname.size()); ObjectInserter inserter(docsum, field_name); if (writer != nullptr) { if (! writer->isDefaultValue(docid, state)) { writer->insertField(docid, &gres, state, outCfg->_type, inserter); } } else { if (rci.inputClass == rci.outputClass) { convertEntry(state, outCfg, gres.GetEntry(i), inserter, slime); } else { int inIdx = rci.inputClass->GetIndexFromEnumValue(outCfg->_enumValue); const ResConfigEntry *inCfg = rci.inputClass->GetEntry(inIdx); if (inCfg != nullptr && inCfg->_type == outCfg->_type) { // copy field const ResEntry *entry = gres.GetEntry(inIdx); LOG_ASSERT(entry != nullptr); convertEntry(state, outCfg, entry, inserter, slime); } } } } } } DynamicDocsumWriter::DynamicDocsumWriter( ResultConfig *config, KeywordExtractor *extractor) : _resultConfig(config), _keywordExtractor(extractor), _defaultOutputClass(ResultConfig::NoClassID()), _numClasses(config->GetNumResultClasses()), _numEnumValues(config->GetFieldNameEnum().GetNumEntries()), _numFieldWriterStates(0), _classInfoTable(nullptr), _overrideTable(nullptr) { LOG_ASSERT(config != nullptr); _classInfoTable = new ResultClass::DynamicInfo[_numClasses]; _overrideTable = new IDocsumFieldWriter*[_numEnumValues]; uint32_t i = 0; for (ResultConfig::iterator it(config->begin()), mt(config->end()); it != mt; it++, i++) { _classInfoTable[i]._overrideCnt = 0; _classInfoTable[i]._generateCnt = 0; it->setDynamicInfo(&(_classInfoTable[i])); } LOG_ASSERT(i == _numClasses); for (i = 0; i < _numEnumValues; i++) _overrideTable[i] = nullptr; } DynamicDocsumWriter::~DynamicDocsumWriter() { delete _resultConfig; delete _keywordExtractor; delete [] _classInfoTable; for (uint32_t i = 0; i < _numEnumValues; i++) delete _overrideTable[i]; delete [] _overrideTable; } bool DynamicDocsumWriter::SetDefaultOutputClass(uint32_t classID) { const ResultClass *resClass = _resultConfig->LookupResultClass(classID); if (resClass == nullptr || _defaultOutputClass != ResultConfig::NoClassID()) { if (resClass == nullptr) { LOG(warning, "cannot set default output docsum class to %d; class not defined", classID); } else if (_defaultOutputClass != ResultConfig::NoClassID()) { LOG(warning, "cannot set default output docsum class to %d; value already set", classID); } return false; } _defaultOutputClass = classID; return true; } bool DynamicDocsumWriter::Override(const char *fieldName, IDocsumFieldWriter *writer) { uint32_t fieldEnumValue = _resultConfig->GetFieldNameEnum().Lookup(fieldName); if (fieldEnumValue >= _numEnumValues || _overrideTable[fieldEnumValue] != nullptr) { if (fieldEnumValue >= _numEnumValues) { LOG(warning, "cannot override docsum field '%s'; undefined field name", fieldName); } else if (_overrideTable[fieldEnumValue] != nullptr) { LOG(warning, "cannot override docsum field '%s'; already overridden", fieldName); } delete writer; return false; } writer->setIndex(fieldEnumValue); _overrideTable[fieldEnumValue] = writer; if (writer->setFieldWriterStateIndex(_numFieldWriterStates)) { ++_numFieldWriterStates; } for (auto & entry : *_resultConfig) { if (entry.GetIndexFromEnumValue(fieldEnumValue) >= 0) { ResultClass::DynamicInfo *info = entry.getDynamicInfo(); info->_overrideCnt++; if (writer->IsGenerated()) info->_generateCnt++; } } return true; } void DynamicDocsumWriter::InitState(IAttributeManager & attrMan, GetDocsumsState *state) { state->_kwExtractor = _keywordExtractor; state->_attrCtx = attrMan.createContext(); state->_attributes.resize(_numEnumValues); state->_fieldWriterStates.resize(_numFieldWriterStates); for (size_t i(0); i < state->_attributes.size(); i++) { const IDocsumFieldWriter *fw = _overrideTable[i]; if (fw) { const vespalib::string & attributeName = fw->getAttributeName(); if (!attributeName.empty()) { state->_attributes[i] = state->_attrCtx->getAttribute(attributeName); } } } } uint32_t DynamicDocsumWriter::WriteDocsum(uint32_t docid, GetDocsumsState *state, IDocsumStore *docinfos, search::RawBuf *target) { vespalib::Slime slime; vespalib::slime::SlimeInserter inserter(slime); ResolveClassInfo rci = resolveClassInfo(state->_args.getResultClassName(), docinfos->getSummaryClassId()); insertDocsum(rci, docid, state, docinfos, slime, inserter); return slime2RawBuf(slime, *target); } } <|endoftext|>
<commit_before>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <cstdlib> #include <unistd.h> #include <android/window.h> #include "EngineAndroid.h" #include "utils/Log.h" static int looperCallback(int fd, int events, void* data) { if (events & ALOOPER_EVENT_INPUT) { char message; if (read(fd, &message, sizeof(message)) == -1) { ouzel::Log(ouzel::Log::Level::ERR) << "Failed to read from pipe"; return 1; } ouzel::EngineAndroid* engineAndroid = static_cast<ouzel::EngineAndroid*>(data); engineAndroid->executeAll(); } return 1; } namespace ouzel { EngineAndroid::EngineAndroid(JavaVM* aJavaVM): javaVM(aJavaVM) { std::fill(std::begin(fd), std::end(fd), 0); JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return; } uriClass = jniEnv->FindClass("android/net/Uri"); uriClass = static_cast<jclass>(jniEnv->NewGlobalRef(uriClass)); parseMethod = jniEnv->GetStaticMethodID(uriClass, "parse", "(Ljava/lang/String;)Landroid/net/Uri;"); intentClass = jniEnv->FindClass("android/content/Intent"); intentClass = static_cast<jclass>(jniEnv->NewGlobalRef(intentClass)); intentConstructor = jniEnv->GetMethodID(intentClass, "<init>", "(Ljava/lang/String;Landroid/net/Uri;)V"); } EngineAndroid::~EngineAndroid() { if (updateThread.joinable()) updateThread.join(); JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return; } if (mainActivity) jniEnv->DeleteGlobalRef(mainActivity); if (window) jniEnv->DeleteGlobalRef(window); if (surface) jniEnv->DeleteGlobalRef(surface); if (intentClass) jniEnv->DeleteGlobalRef(intentClass); if (uriClass) jniEnv->DeleteGlobalRef(uriClass); if (looper) ALooper_release(looper); if (fd[0]) close(fd[0]); if (fd[1]) close(fd[1]); } void EngineAndroid::onCreate(jobject aMainActivity) { JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return; } mainActivity = jniEnv->NewGlobalRef(aMainActivity); jclass mainActivityClass = jniEnv->GetObjectClass(mainActivity); startActivityMethod = jniEnv->GetMethodID(mainActivityClass, "startActivity", "(Landroid/content/Intent;)V"); // get asset manager jmethodID getAssetsMethod = jniEnv->GetMethodID(mainActivityClass, "getAssets", "()Landroid/content/res/AssetManager;"); jobject assetManagerObject = jniEnv->CallObjectMethod(mainActivity, getAssetsMethod); assetManager = AAssetManager_fromJava(jniEnv, assetManagerObject); // get window jmethodID getWindowMethod = jniEnv->GetMethodID(mainActivityClass, "getWindow", "()Landroid/view/Window;"); window = jniEnv->CallObjectMethod(mainActivity, getWindowMethod); window = jniEnv->NewGlobalRef(window); jclass windowClass = jniEnv->GetObjectClass(window); addFlagsMethod = jniEnv->GetMethodID(windowClass, "addFlags", "(I)V"); clearFlagsMethod = jniEnv->GetMethodID(windowClass, "clearFlags", "(I)V"); // File class jclass fileClass = jniEnv->FindClass("java/io/File"); jmethodID getAbsolutePathMethod = jniEnv->GetMethodID(fileClass, "getAbsolutePath", "()Ljava/lang/String;"); // dataDir jmethodID getFilesDirMethod = jniEnv->GetMethodID(mainActivityClass, "getFilesDir", "()Ljava/io/File;"); jobject filesDirFile = jniEnv->CallObjectMethod(mainActivity, getFilesDirMethod); jstring filesDirString = static_cast<jstring>(jniEnv->CallObjectMethod(filesDirFile, getAbsolutePathMethod)); const char* filesDirCString = jniEnv->GetStringUTFChars(filesDirString, 0); filesDirectory = filesDirCString; jniEnv->ReleaseStringUTFChars(filesDirString, filesDirCString); // cacheDir jmethodID getCacheDirMethod = jniEnv->GetMethodID(mainActivityClass, "getCacheDir", "()Ljava/io/File;"); jobject cacheDirFile = jniEnv->CallObjectMethod(mainActivity, getCacheDirMethod); jstring cacheDirString = static_cast<jstring>(jniEnv->CallObjectMethod(cacheDirFile, getAbsolutePathMethod)); const char* cacheDirCString = jniEnv->GetStringUTFChars(cacheDirString, 0); cacheDirectory = cacheDirCString; jniEnv->ReleaseStringUTFChars(cacheDirString, cacheDirCString); // looper looper = ALooper_forThread(); // this is called on main thread, so it is safe to get the looper here ALooper_acquire(looper); pipe(fd); ALooper_addFd(looper, fd[0], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, looperCallback, this); } void EngineAndroid::setSurface(jobject aSurface) { JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return; } surface = jniEnv->NewGlobalRef(aSurface); } int EngineAndroid::run() { updateThread = std::thread(&EngineAndroid::loop, this); return EXIT_SUCCESS; } void EngineAndroid::execute(const std::function<void(void)>& func) { { std::lock_guard<std::mutex> lock(executeMutex); executeQueue.push(func); } char message = 1; if (write(fd[1], &message, sizeof(message)) == -1) { Log(Log::Level::ERR) << "Failed to write to pipe"; } } bool EngineAndroid::openURL(const std::string& url) { JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return false; } jstring actionString = jniEnv->NewStringUTF("android.intent.action.VIEW"); jstring urlString = jniEnv->NewStringUTF(url.c_str()); jobject uri = jniEnv->CallStaticObjectMethod(uriClass, parseMethod, urlString); jobject intentObject = jniEnv->NewObject(intentClass, intentConstructor, actionString, uri); jniEnv->CallVoidMethod(mainActivity, startActivityMethod, intentObject); jniEnv->DeleteLocalRef(intentObject); jniEnv->DeleteLocalRef(uri); jniEnv->DeleteLocalRef(urlString); jniEnv->DeleteLocalRef(actionString); if (jniEnv->ExceptionCheck()) { Log(Log::Level::ERR) << "Failed to open URL"; jniEnv->ExceptionClear(); return false; } return true; } void EngineAndroid::setScreenSaverEnabled(bool newScreenSaverEnabled) { Engine::setScreenSaverEnabled(newScreenSaverEnabled); execute([newScreenSaverEnabled, this]() { JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return; } if (newScreenSaverEnabled) { jniEnv->CallVoidMethod(window, clearFlagsMethod, AWINDOW_FLAG_KEEP_SCREEN_ON); } else { jniEnv->CallVoidMethod(window, addFlagsMethod, AWINDOW_FLAG_KEEP_SCREEN_ON); } }); } void EngineAndroid::executeAll() { std::function<void(void)> func; { std::lock_guard<std::mutex> lock(executeMutex); if (!executeQueue.empty()) { func = std::move(executeQueue.front()); executeQueue.pop(); } } if (func) { func(); } } void EngineAndroid::main() { JNIEnv* jniEnv; JavaVMAttachArgs attachArgs; attachArgs.version = JNI_VERSION_1_6; attachArgs.name = NULL; // thread name attachArgs.group = NULL; // thread group if (javaVM->AttachCurrentThread(&jniEnv, &attachArgs) != JNI_OK) { Log(Log::Level::ERR) << "Failed to attach current thread to Java VM"; } Engine::main(); if (javaVM->DetachCurrentThread() != JNI_OK) { Log(Log::Level::ERR) << "Failed to detach current thread from Java VM"; } } void EngineAndroid::loop() { JNIEnv* jniEnv; JavaVMAttachArgs attachArgs; attachArgs.version = JNI_VERSION_1_6; attachArgs.name = NULL; // thread name attachArgs.group = NULL; // thread group if (javaVM->AttachCurrentThread(&jniEnv, &attachArgs) != JNI_OK) { Log(Log::Level::ERR) << "Failed to attach current thread to Java VM"; } if (!init()) { ::exit(EXIT_FAILURE); } start(); while (active) { if (!active || !renderer->process()) { break; } } if (javaVM->DetachCurrentThread() != JNI_OK) { Log(Log::Level::ERR) << "Failed to detach current thread from Java VM"; } ::exit(EXIT_SUCCESS); } } <commit_msg>Remove the active check<commit_after>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <cstdlib> #include <unistd.h> #include <android/window.h> #include "EngineAndroid.h" #include "utils/Log.h" static int looperCallback(int fd, int events, void* data) { if (events & ALOOPER_EVENT_INPUT) { char message; if (read(fd, &message, sizeof(message)) == -1) { ouzel::Log(ouzel::Log::Level::ERR) << "Failed to read from pipe"; return 1; } ouzel::EngineAndroid* engineAndroid = static_cast<ouzel::EngineAndroid*>(data); engineAndroid->executeAll(); } return 1; } namespace ouzel { EngineAndroid::EngineAndroid(JavaVM* aJavaVM): javaVM(aJavaVM) { std::fill(std::begin(fd), std::end(fd), 0); JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return; } uriClass = jniEnv->FindClass("android/net/Uri"); uriClass = static_cast<jclass>(jniEnv->NewGlobalRef(uriClass)); parseMethod = jniEnv->GetStaticMethodID(uriClass, "parse", "(Ljava/lang/String;)Landroid/net/Uri;"); intentClass = jniEnv->FindClass("android/content/Intent"); intentClass = static_cast<jclass>(jniEnv->NewGlobalRef(intentClass)); intentConstructor = jniEnv->GetMethodID(intentClass, "<init>", "(Ljava/lang/String;Landroid/net/Uri;)V"); } EngineAndroid::~EngineAndroid() { if (updateThread.joinable()) updateThread.join(); JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return; } if (mainActivity) jniEnv->DeleteGlobalRef(mainActivity); if (window) jniEnv->DeleteGlobalRef(window); if (surface) jniEnv->DeleteGlobalRef(surface); if (intentClass) jniEnv->DeleteGlobalRef(intentClass); if (uriClass) jniEnv->DeleteGlobalRef(uriClass); if (looper) ALooper_release(looper); if (fd[0]) close(fd[0]); if (fd[1]) close(fd[1]); } void EngineAndroid::onCreate(jobject aMainActivity) { JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return; } mainActivity = jniEnv->NewGlobalRef(aMainActivity); jclass mainActivityClass = jniEnv->GetObjectClass(mainActivity); startActivityMethod = jniEnv->GetMethodID(mainActivityClass, "startActivity", "(Landroid/content/Intent;)V"); // get asset manager jmethodID getAssetsMethod = jniEnv->GetMethodID(mainActivityClass, "getAssets", "()Landroid/content/res/AssetManager;"); jobject assetManagerObject = jniEnv->CallObjectMethod(mainActivity, getAssetsMethod); assetManager = AAssetManager_fromJava(jniEnv, assetManagerObject); // get window jmethodID getWindowMethod = jniEnv->GetMethodID(mainActivityClass, "getWindow", "()Landroid/view/Window;"); window = jniEnv->CallObjectMethod(mainActivity, getWindowMethod); window = jniEnv->NewGlobalRef(window); jclass windowClass = jniEnv->GetObjectClass(window); addFlagsMethod = jniEnv->GetMethodID(windowClass, "addFlags", "(I)V"); clearFlagsMethod = jniEnv->GetMethodID(windowClass, "clearFlags", "(I)V"); // File class jclass fileClass = jniEnv->FindClass("java/io/File"); jmethodID getAbsolutePathMethod = jniEnv->GetMethodID(fileClass, "getAbsolutePath", "()Ljava/lang/String;"); // dataDir jmethodID getFilesDirMethod = jniEnv->GetMethodID(mainActivityClass, "getFilesDir", "()Ljava/io/File;"); jobject filesDirFile = jniEnv->CallObjectMethod(mainActivity, getFilesDirMethod); jstring filesDirString = static_cast<jstring>(jniEnv->CallObjectMethod(filesDirFile, getAbsolutePathMethod)); const char* filesDirCString = jniEnv->GetStringUTFChars(filesDirString, 0); filesDirectory = filesDirCString; jniEnv->ReleaseStringUTFChars(filesDirString, filesDirCString); // cacheDir jmethodID getCacheDirMethod = jniEnv->GetMethodID(mainActivityClass, "getCacheDir", "()Ljava/io/File;"); jobject cacheDirFile = jniEnv->CallObjectMethod(mainActivity, getCacheDirMethod); jstring cacheDirString = static_cast<jstring>(jniEnv->CallObjectMethod(cacheDirFile, getAbsolutePathMethod)); const char* cacheDirCString = jniEnv->GetStringUTFChars(cacheDirString, 0); cacheDirectory = cacheDirCString; jniEnv->ReleaseStringUTFChars(cacheDirString, cacheDirCString); // looper looper = ALooper_forThread(); // this is called on main thread, so it is safe to get the looper here ALooper_acquire(looper); pipe(fd); ALooper_addFd(looper, fd[0], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, looperCallback, this); } void EngineAndroid::setSurface(jobject aSurface) { JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return; } surface = jniEnv->NewGlobalRef(aSurface); } int EngineAndroid::run() { updateThread = std::thread(&EngineAndroid::loop, this); return EXIT_SUCCESS; } void EngineAndroid::execute(const std::function<void(void)>& func) { { std::lock_guard<std::mutex> lock(executeMutex); executeQueue.push(func); } char message = 1; if (write(fd[1], &message, sizeof(message)) == -1) { Log(Log::Level::ERR) << "Failed to write to pipe"; } } bool EngineAndroid::openURL(const std::string& url) { JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return false; } jstring actionString = jniEnv->NewStringUTF("android.intent.action.VIEW"); jstring urlString = jniEnv->NewStringUTF(url.c_str()); jobject uri = jniEnv->CallStaticObjectMethod(uriClass, parseMethod, urlString); jobject intentObject = jniEnv->NewObject(intentClass, intentConstructor, actionString, uri); jniEnv->CallVoidMethod(mainActivity, startActivityMethod, intentObject); jniEnv->DeleteLocalRef(intentObject); jniEnv->DeleteLocalRef(uri); jniEnv->DeleteLocalRef(urlString); jniEnv->DeleteLocalRef(actionString); if (jniEnv->ExceptionCheck()) { Log(Log::Level::ERR) << "Failed to open URL"; jniEnv->ExceptionClear(); return false; } return true; } void EngineAndroid::setScreenSaverEnabled(bool newScreenSaverEnabled) { Engine::setScreenSaverEnabled(newScreenSaverEnabled); execute([newScreenSaverEnabled, this]() { JNIEnv* jniEnv; if (javaVM->GetEnv(reinterpret_cast<void**>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) { Log(Log::Level::ERR) << "Failed to get JNI environment"; return; } if (newScreenSaverEnabled) { jniEnv->CallVoidMethod(window, clearFlagsMethod, AWINDOW_FLAG_KEEP_SCREEN_ON); } else { jniEnv->CallVoidMethod(window, addFlagsMethod, AWINDOW_FLAG_KEEP_SCREEN_ON); } }); } void EngineAndroid::executeAll() { std::function<void(void)> func; { std::lock_guard<std::mutex> lock(executeMutex); if (!executeQueue.empty()) { func = std::move(executeQueue.front()); executeQueue.pop(); } } if (func) { func(); } } void EngineAndroid::main() { JNIEnv* jniEnv; JavaVMAttachArgs attachArgs; attachArgs.version = JNI_VERSION_1_6; attachArgs.name = NULL; // thread name attachArgs.group = NULL; // thread group if (javaVM->AttachCurrentThread(&jniEnv, &attachArgs) != JNI_OK) { Log(Log::Level::ERR) << "Failed to attach current thread to Java VM"; } Engine::main(); if (javaVM->DetachCurrentThread() != JNI_OK) { Log(Log::Level::ERR) << "Failed to detach current thread from Java VM"; } } void EngineAndroid::loop() { JNIEnv* jniEnv; JavaVMAttachArgs attachArgs; attachArgs.version = JNI_VERSION_1_6; attachArgs.name = NULL; // thread name attachArgs.group = NULL; // thread group if (javaVM->AttachCurrentThread(&jniEnv, &attachArgs) != JNI_OK) { Log(Log::Level::ERR) << "Failed to attach current thread to Java VM"; } if (!init()) { ::exit(EXIT_FAILURE); } start(); while (active) { if (!renderer->process()) { break; } } if (javaVM->DetachCurrentThread() != JNI_OK) { Log(Log::Level::ERR) << "Failed to detach current thread from Java VM"; } ::exit(EXIT_SUCCESS); } } <|endoftext|>
<commit_before><commit_msg>Updated platform utils<commit_after><|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at [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 version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "taslogger.h" #include "tasgesturerecognizers.h" const char* const DIST_ONE = "distance_1"; const char* const DIST_TWO = "distance_2"; const char* const DIFF = "differential"; const char* const TYPE = "type"; const char* const RADIUS = "radius"; const char* const ROTATE_DIRECTION = "rotate_direction"; #include "tasdeviceutils.h" /*! \class TasGestureRecognizer \brief Creates a TasGesture from the given data. TasGestures are created from the data passed from the testabilitydriver host. Recornizers are used to identify and create the correct gestures from the data. */ /*! \fn TasGesture* TasGestureRecognizer::create(TargetData data) Creates the TasGesture that matches the given data. */ QPoint TasGestureUtils::getPoint(TasCommand& command) { int x = command.parameter("x").toInt(); int y = command.parameter("y").toInt(); return QPoint(x,y); } QPoint TasGestureUtils::getTargetPoint(TasCommand& command) { QString targetId = command.parameter("targetId"); QPoint targetPoint; if(command.parameter("targetType") == TYPE_GRAPHICS_VIEW){ QGraphicsItem* targetItem = findGraphicsItem(targetId); if(targetItem){ viewPortAndPosition(targetItem, targetPoint); } } else{ QWidget* targetWidget = findWidget(targetId); if(targetWidget){ targetPoint = targetWidget->mapToGlobal(targetWidget->rect().center()); } } return targetPoint; } void TasGestureUtils::doTransform(QGraphicsItem* targetItem, QLineF& gestureLine) { if(targetItem){ QGraphicsView* view = TestabilityUtils::getViewForItem(targetItem); if(view && !view->viewportTransform().isIdentity()){ QTransform transform = view->viewportTransform(); QLineF transformedLine = transform.map(gestureLine); //set new angle and length based on transformation gestureLine.setLength(transformedLine.length()); gestureLine.setAngle(transformedLine.angle()); } } } int TasGestureUtils::getDistance(TasCommand& command) { return command.parameter("distance").toInt(); } int TasGestureUtils::getDirection(TasCommand& command) { int direction = command.parameter("direction").toInt(); int orientation = TasDeviceUtils::getOrientation(); if (orientation != -1) { direction += orientation; } direction -= 90; direction = direction * -1; return direction; } QLineF TasGestureUtils::makeLine(QPoint start, int length, int angle) { QLineF line; line.setP1(start); line.setLength(length); line.setAngle(angle); return line; } /*! \class LineTasGestureRecognizer \brief Creates a LineTasGesture from the given data. Creates a linear single touch gesture from the given data. */ LineTasGestureRecognizer::LineTasGestureRecognizer() { mTypes << "MouseGesture" << "MouseGestureTo" << "MouseGestureToCoordinates" << "MouseGestureFromCoordinates"; } /*! \fn TasGesture* bool TasGestureRecognizer::isSupportedType(const QString& gestureType) Return true if the given gesture type can be recognined and created by the recognizer. */ bool LineTasGestureRecognizer::isSupportedType(const QString& gestureType) { return mTypes.contains(gestureType); } TasGesture* LineTasGestureRecognizer::create(TargetData data) { TasCommand& command = *data.command; QPoint point = data.targetPoint; QLineF gestureLine; if(command.name() == "MouseGestureFromCoordinates"){ QPoint start = mUtils.getPoint(command); gestureLine.setP1(QPointF(start)); } else{ gestureLine.setP1(QPointF(point)); } if(command.name() == "MouseGesture" || command.name() == "MouseGestureFromCoordinates"){ gestureLine.setLength(mUtils.getDistance(command)); gestureLine.setAngle(mUtils.getDirection(command)); mUtils.doTransform(data.targetItem, gestureLine); } else{ QPoint end; if(command.name() == "MouseGestureTo"){ end = mUtils.getTargetPoint(command); } else{ end = mUtils.getPoint(command); } gestureLine.setP1(QPointF(point)); gestureLine.setP2(QPointF(end)); } return new LineTasGesture(data, gestureLine); } PointsTasGestureRecognizer::PointsTasGestureRecognizer() { } bool PointsTasGestureRecognizer::isSupportedType(const QString& gestureType) { return gestureType == "MouseGesturePoints"; } TasGesture* PointsTasGestureRecognizer::create(TargetData data) { TasCommand& command = *data.command; QWidget* target = data.target; QList<QPoint> gesturePoints; QList<int> gestureIntervals; QStringList points = command.text().split(";",QString::SkipEmptyParts); for(int i = 0 ; i < points.size(); i++){ QString rawPoint = points.at(i); QStringList pointData = rawPoint.split(",",QString::SkipEmptyParts); //skip invalid data //gestures done asynchronously so no possibility for error reporting if(pointData.size() >= 2){ int x = pointData.at(0).toInt(); int y = pointData.at(1).toInt(); QPoint windowPoint(x,y); if(target->window()){ gesturePoints.append(target->window()->mapToGlobal(windowPoint)); } else{ gesturePoints.append(windowPoint); } if(pointData.size() == 3){ gestureIntervals.append(pointData.at(2).toInt()); } } } PointsTasGesture* gesture = new PointsTasGesture(data, gesturePoints); gesture->setIntervals(gestureIntervals); return gesture; } PinchZoomTasGestureRecognizer::PinchZoomTasGestureRecognizer() {} bool PinchZoomTasGestureRecognizer::isSupportedType(const QString& gestureType) { return gestureType == "PinchZoom"; } TasGesture* PinchZoomTasGestureRecognizer::create(TargetData data) { TasCommand& command = *data.command; if(!validateZoomParams(command)){ return 0; } QPoint point = data.targetPoint; if(command.parameter("useCoordinates") == "true"){ point = mUtils.getPoint(command); } int distance_1 = command.parameter(DIST_ONE).toInt(); int distance_2 = command.parameter(DIST_TWO).toInt(); int differential = command.parameter(DIFF).toInt(); QLineF line1; QLineF line2; QPoint start1 = point; QPoint start2 = point; if(differential > 1){ QLineF line = mUtils.makeLine(point,differential/2, mUtils.getDirection(command)); start1 = line.p2().toPoint(); line.setAngle(mUtils.getDirection(command)+180); start2 = line.p2().toPoint(); } line1 = mUtils.makeLine(start1, distance_1, mUtils.getDirection(command)); line2 = mUtils.makeLine(start2, distance_2, mUtils.getDirection(command)+180); //this is the diff line if(command.parameter(TYPE) == "in"){ return new PinchZoomTasGesture(data, line1, line2); } else{ //flip the lines if zoom out return new PinchZoomTasGesture(data, QLineF(line1.p2(), line1.p1()), QLineF(line2.p2(), line2.p1())); } } bool PinchZoomTasGestureRecognizer::validateZoomParams(TasCommand& command) { bool valid = true; if(command.parameter(DIST_ONE).isEmpty() || command.parameter(DIST_TWO).isEmpty()) { TasLogger::logger()->error("MultitouchHandler::validateZoomParams invalid pinch command given invalid directions."); valid = false; } if(command.parameter(TYPE).isEmpty()){ TasLogger::logger()->error("MultitouchHandler::validateZoomParams no type defined."); valid = false; } if(command.parameter(DIFF).isEmpty()) { TasLogger::logger()->error("MultitouchHandler::validateZoomParams no differential defined."); valid = false; } return valid; } RotationTasGestureRecognizer::RotationTasGestureRecognizer() {} bool RotationTasGestureRecognizer::isSupportedType(const QString& gestureType) { return gestureType == "Rotate"; } TasGesture* RotationTasGestureRecognizer::create(TargetData data) { TasCommand& command = *data.command; if(!validateRotationParams(command)){ return false; } QPoint point = data.targetPoint; if(command.parameter("useCoordinates") == "true"){ point = mUtils.getPoint(command); TasLogger::logger()->debug("set point"); } int radius = command.parameter(RADIUS).toInt(); int distance = mUtils.getDistance(command); int direction = mUtils.getDirection(command); if(command.parameter(ROTATE_DIRECTION) == "Clockwise"){ distance = distance * -1; } QLineF line = mUtils.makeLine(point, radius, direction); if(command.parameter(TYPE) == "one_point"){ return new SectorTasGesture(data, line, distance); } else{ QLineF line2 = mUtils.makeLine(point, radius, direction+180); return new ArcsTasGesture(data, line, line2, distance); } } bool RotationTasGestureRecognizer::validateRotationParams(TasCommand& command) { bool valid = true; if(command.parameter(TYPE).isEmpty()){ TasLogger::logger()->error("MultitouchHandler::validateRotationParams no type defined."); valid = false; } if(command.parameter(RADIUS).isEmpty()) { TasLogger::logger()->error("MultitouchHandler::executeInteraction no radius defined."); valid = false; } if(command.parameter(ROTATE_DIRECTION).isEmpty()) { TasLogger::logger()->error("MultitouchHandler::executeInteraction no rotation direction defined."); valid = false; } return valid; } <commit_msg>Fix wrong return value<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at [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 version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "taslogger.h" #include "tasgesturerecognizers.h" const char* const DIST_ONE = "distance_1"; const char* const DIST_TWO = "distance_2"; const char* const DIFF = "differential"; const char* const TYPE = "type"; const char* const RADIUS = "radius"; const char* const ROTATE_DIRECTION = "rotate_direction"; #include "tasdeviceutils.h" /*! \class TasGestureRecognizer \brief Creates a TasGesture from the given data. TasGestures are created from the data passed from the testabilitydriver host. Recornizers are used to identify and create the correct gestures from the data. */ /*! \fn TasGesture* TasGestureRecognizer::create(TargetData data) Creates the TasGesture that matches the given data. */ QPoint TasGestureUtils::getPoint(TasCommand& command) { int x = command.parameter("x").toInt(); int y = command.parameter("y").toInt(); return QPoint(x,y); } QPoint TasGestureUtils::getTargetPoint(TasCommand& command) { QString targetId = command.parameter("targetId"); QPoint targetPoint; if(command.parameter("targetType") == TYPE_GRAPHICS_VIEW){ QGraphicsItem* targetItem = findGraphicsItem(targetId); if(targetItem){ viewPortAndPosition(targetItem, targetPoint); } } else{ QWidget* targetWidget = findWidget(targetId); if(targetWidget){ targetPoint = targetWidget->mapToGlobal(targetWidget->rect().center()); } } return targetPoint; } void TasGestureUtils::doTransform(QGraphicsItem* targetItem, QLineF& gestureLine) { if(targetItem){ QGraphicsView* view = TestabilityUtils::getViewForItem(targetItem); if(view && !view->viewportTransform().isIdentity()){ QTransform transform = view->viewportTransform(); QLineF transformedLine = transform.map(gestureLine); //set new angle and length based on transformation gestureLine.setLength(transformedLine.length()); gestureLine.setAngle(transformedLine.angle()); } } } int TasGestureUtils::getDistance(TasCommand& command) { return command.parameter("distance").toInt(); } int TasGestureUtils::getDirection(TasCommand& command) { int direction = command.parameter("direction").toInt(); int orientation = TasDeviceUtils::getOrientation(); if (orientation != -1) { direction += orientation; } direction -= 90; direction = direction * -1; return direction; } QLineF TasGestureUtils::makeLine(QPoint start, int length, int angle) { QLineF line; line.setP1(start); line.setLength(length); line.setAngle(angle); return line; } /*! \class LineTasGestureRecognizer \brief Creates a LineTasGesture from the given data. Creates a linear single touch gesture from the given data. */ LineTasGestureRecognizer::LineTasGestureRecognizer() { mTypes << "MouseGesture" << "MouseGestureTo" << "MouseGestureToCoordinates" << "MouseGestureFromCoordinates"; } /*! \fn TasGesture* bool TasGestureRecognizer::isSupportedType(const QString& gestureType) Return true if the given gesture type can be recognined and created by the recognizer. */ bool LineTasGestureRecognizer::isSupportedType(const QString& gestureType) { return mTypes.contains(gestureType); } TasGesture* LineTasGestureRecognizer::create(TargetData data) { TasCommand& command = *data.command; QPoint point = data.targetPoint; QLineF gestureLine; if(command.name() == "MouseGestureFromCoordinates"){ QPoint start = mUtils.getPoint(command); gestureLine.setP1(QPointF(start)); } else{ gestureLine.setP1(QPointF(point)); } if(command.name() == "MouseGesture" || command.name() == "MouseGestureFromCoordinates"){ gestureLine.setLength(mUtils.getDistance(command)); gestureLine.setAngle(mUtils.getDirection(command)); mUtils.doTransform(data.targetItem, gestureLine); } else{ QPoint end; if(command.name() == "MouseGestureTo"){ end = mUtils.getTargetPoint(command); } else{ end = mUtils.getPoint(command); } gestureLine.setP1(QPointF(point)); gestureLine.setP2(QPointF(end)); } return new LineTasGesture(data, gestureLine); } PointsTasGestureRecognizer::PointsTasGestureRecognizer() { } bool PointsTasGestureRecognizer::isSupportedType(const QString& gestureType) { return gestureType == "MouseGesturePoints"; } TasGesture* PointsTasGestureRecognizer::create(TargetData data) { TasCommand& command = *data.command; QWidget* target = data.target; QList<QPoint> gesturePoints; QList<int> gestureIntervals; QStringList points = command.text().split(";",QString::SkipEmptyParts); for(int i = 0 ; i < points.size(); i++){ QString rawPoint = points.at(i); QStringList pointData = rawPoint.split(",",QString::SkipEmptyParts); //skip invalid data //gestures done asynchronously so no possibility for error reporting if(pointData.size() >= 2){ int x = pointData.at(0).toInt(); int y = pointData.at(1).toInt(); QPoint windowPoint(x,y); if(target->window()){ gesturePoints.append(target->window()->mapToGlobal(windowPoint)); } else{ gesturePoints.append(windowPoint); } if(pointData.size() == 3){ gestureIntervals.append(pointData.at(2).toInt()); } } } PointsTasGesture* gesture = new PointsTasGesture(data, gesturePoints); gesture->setIntervals(gestureIntervals); return gesture; } PinchZoomTasGestureRecognizer::PinchZoomTasGestureRecognizer() {} bool PinchZoomTasGestureRecognizer::isSupportedType(const QString& gestureType) { return gestureType == "PinchZoom"; } TasGesture* PinchZoomTasGestureRecognizer::create(TargetData data) { TasCommand& command = *data.command; if(!validateZoomParams(command)){ return 0; } QPoint point = data.targetPoint; if(command.parameter("useCoordinates") == "true"){ point = mUtils.getPoint(command); } int distance_1 = command.parameter(DIST_ONE).toInt(); int distance_2 = command.parameter(DIST_TWO).toInt(); int differential = command.parameter(DIFF).toInt(); QLineF line1; QLineF line2; QPoint start1 = point; QPoint start2 = point; if(differential > 1){ QLineF line = mUtils.makeLine(point,differential/2, mUtils.getDirection(command)); start1 = line.p2().toPoint(); line.setAngle(mUtils.getDirection(command)+180); start2 = line.p2().toPoint(); } line1 = mUtils.makeLine(start1, distance_1, mUtils.getDirection(command)); line2 = mUtils.makeLine(start2, distance_2, mUtils.getDirection(command)+180); //this is the diff line if(command.parameter(TYPE) == "in"){ return new PinchZoomTasGesture(data, line1, line2); } else{ //flip the lines if zoom out return new PinchZoomTasGesture(data, QLineF(line1.p2(), line1.p1()), QLineF(line2.p2(), line2.p1())); } } bool PinchZoomTasGestureRecognizer::validateZoomParams(TasCommand& command) { bool valid = true; if(command.parameter(DIST_ONE).isEmpty() || command.parameter(DIST_TWO).isEmpty()) { TasLogger::logger()->error("MultitouchHandler::validateZoomParams invalid pinch command given invalid directions."); valid = false; } if(command.parameter(TYPE).isEmpty()){ TasLogger::logger()->error("MultitouchHandler::validateZoomParams no type defined."); valid = false; } if(command.parameter(DIFF).isEmpty()) { TasLogger::logger()->error("MultitouchHandler::validateZoomParams no differential defined."); valid = false; } return valid; } RotationTasGestureRecognizer::RotationTasGestureRecognizer() {} bool RotationTasGestureRecognizer::isSupportedType(const QString& gestureType) { return gestureType == "Rotate"; } TasGesture* RotationTasGestureRecognizer::create(TargetData data) { TasCommand& command = *data.command; if(!validateRotationParams(command)){ return 0; } QPoint point = data.targetPoint; if(command.parameter("useCoordinates") == "true"){ point = mUtils.getPoint(command); TasLogger::logger()->debug("set point"); } int radius = command.parameter(RADIUS).toInt(); int distance = mUtils.getDistance(command); int direction = mUtils.getDirection(command); if(command.parameter(ROTATE_DIRECTION) == "Clockwise"){ distance = distance * -1; } QLineF line = mUtils.makeLine(point, radius, direction); if(command.parameter(TYPE) == "one_point"){ return new SectorTasGesture(data, line, distance); } else{ QLineF line2 = mUtils.makeLine(point, radius, direction+180); return new ArcsTasGesture(data, line, line2, distance); } } bool RotationTasGestureRecognizer::validateRotationParams(TasCommand& command) { bool valid = true; if(command.parameter(TYPE).isEmpty()){ TasLogger::logger()->error("MultitouchHandler::validateRotationParams no type defined."); valid = false; } if(command.parameter(RADIUS).isEmpty()) { TasLogger::logger()->error("MultitouchHandler::executeInteraction no radius defined."); valid = false; } if(command.parameter(ROTATE_DIRECTION).isEmpty()) { TasLogger::logger()->error("MultitouchHandler::executeInteraction no rotation direction defined."); valid = false; } return valid; } <|endoftext|>
<commit_before>/* Copyright (C) 1998 by Jorrit Tyberghein Copyright (C) 2001 by Samuel Humphreys This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdarg.h> #include "cssysdef.h" #include "csutil/sysfunc.h" #include "csutil/scf.h" #include "ivaria/reporter.h" #include "csgeom/csrect.h" #include "xextshm.h" CS_IMPLEMENT_PLUGIN SCF_IMPLEMENT_FACTORY (csXExtSHM) SCF_IMPLEMENT_IBASE(csXExtSHM) SCF_IMPLEMENTS_INTERFACE(iXExtSHM) SCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent) SCF_IMPLEMENT_IBASE_END SCF_IMPLEMENT_EMBEDDED_IBASE (csXExtSHM::eiComponent) SCF_IMPLEMENTS_INTERFACE (iComponent) SCF_IMPLEMENT_EMBEDDED_IBASE_END csXExtSHM::csXExtSHM (iBase* parent) { SCF_CONSTRUCT_IBASE (parent); SCF_CONSTRUCT_EMBEDDED_IBASE (scfiComponent); dpy = 0; screen_num = 0; Width = Height = 0; shm_image = 0; shmi.shmaddr = (char*) -1; shmi.shmid = -1; } csXExtSHM::~csXExtSHM () { DestroyMemory (); SCF_DESTRUCT_EMBEDDED_IBASE (scfiComponent); SCF_DESTRUCT_IBASE(); } bool csXExtSHM::Initialize (iObjectRegistry *object_reg) { this->object_reg = object_reg; return true; } void csXExtSHM::Report (int severity, const char* msg, ...) { va_list arg; va_start (arg, msg); csRef<iReporter> rep (CS_QUERY_REGISTRY (object_reg, iReporter)); if (rep) rep->ReportV (severity, "crystalspace.window.x.extshm", msg, arg); else { csPrintfV (msg, arg); csPrintf ("\n"); } va_end (arg); } unsigned char *csXExtSHM::CreateMemory (int Width, int Height) { int disp_depth = DefaultDepth(dpy,screen_num); int bitmap_pad = (disp_depth + 7) / 8; DestroyMemory (); bitmap_pad = (bitmap_pad == 3) ? 32 : bitmap_pad*8; shm_image = XShmCreateImage(dpy, DefaultVisual(dpy,screen_num), disp_depth, ZPixmap, 0, &shmi, Width, Height); if (!shm_image) { Report (CS_REPORTER_SEVERITY_ERROR, "XShmCreateImage failed!"); return 0; } shmi.shmid = shmget (IPC_PRIVATE, shm_image->bytes_per_line*shm_image->height, IPC_CREAT | 0777); if (shmi.shmid == -1) { DestroyMemory (); Report (CS_REPORTER_SEVERITY_ERROR, "shmget failed!"); return 0; } shm_image->data = shmi.shmaddr = (char*)shmat (shmi.shmid, 0, 0); if (shmi.shmaddr == (char*) -1) { DestroyMemory (); Report (CS_REPORTER_SEVERITY_ERROR, "shmat failed!"); return 0; } shmi.readOnly = FALSE; XShmAttach (dpy, &shmi); // Delete memory segment. The memory stays available until // the last client detaches from it. XSync (dpy, False); shmctl (shmi.shmid, IPC_RMID, 0); shm_image->obdata = (char *)&shmi; this->Width = Width; this->Height = Height; return (unsigned char *)shmi.shmaddr; } void csXExtSHM::DestroyMemory () { if (shmi.shmaddr != (char*) -1) XShmDetach (dpy, &shmi); if (shm_image) XDestroyImage (shm_image); if (shmi.shmaddr != (char*) -1) shmdt (shmi.shmaddr); if (shmi.shmid != -1) shmctl (shmi.shmid, IPC_RMID, 0); shmi.shmaddr = (char*) -1; shmi.shmid = -1; shm_image = 0; } void csXExtSHM::Print (Window window, GC gc, csRect const* area) { if (area) XShmPutImage (dpy, window, gc, shm_image, area->xmin, area->ymin, area->xmin, area->ymin, area->Width (), area->Height (), False); else XShmPutImage (dpy, window, gc, shm_image, 0, 0, 0, 0, Width, Height, False); XSync (dpy, False); } <commit_msg>Fixed a compile error with the use of FALSE in xextshm.cpp<commit_after>/* Copyright (C) 1998 by Jorrit Tyberghein Copyright (C) 2001 by Samuel Humphreys This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdarg.h> #include "cssysdef.h" #include "csutil/sysfunc.h" #include "csutil/scf.h" #include "ivaria/reporter.h" #include "csgeom/csrect.h" #include "xextshm.h" CS_IMPLEMENT_PLUGIN SCF_IMPLEMENT_FACTORY (csXExtSHM) SCF_IMPLEMENT_IBASE(csXExtSHM) SCF_IMPLEMENTS_INTERFACE(iXExtSHM) SCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent) SCF_IMPLEMENT_IBASE_END SCF_IMPLEMENT_EMBEDDED_IBASE (csXExtSHM::eiComponent) SCF_IMPLEMENTS_INTERFACE (iComponent) SCF_IMPLEMENT_EMBEDDED_IBASE_END csXExtSHM::csXExtSHM (iBase* parent) { SCF_CONSTRUCT_IBASE (parent); SCF_CONSTRUCT_EMBEDDED_IBASE (scfiComponent); dpy = 0; screen_num = 0; Width = Height = 0; shm_image = 0; shmi.shmaddr = (char*) -1; shmi.shmid = -1; } csXExtSHM::~csXExtSHM () { DestroyMemory (); SCF_DESTRUCT_EMBEDDED_IBASE (scfiComponent); SCF_DESTRUCT_IBASE(); } bool csXExtSHM::Initialize (iObjectRegistry *object_reg) { this->object_reg = object_reg; return true; } void csXExtSHM::Report (int severity, const char* msg, ...) { va_list arg; va_start (arg, msg); csRef<iReporter> rep (CS_QUERY_REGISTRY (object_reg, iReporter)); if (rep) rep->ReportV (severity, "crystalspace.window.x.extshm", msg, arg); else { csPrintfV (msg, arg); csPrintf ("\n"); } va_end (arg); } unsigned char *csXExtSHM::CreateMemory (int Width, int Height) { int disp_depth = DefaultDepth(dpy,screen_num); int bitmap_pad = (disp_depth + 7) / 8; DestroyMemory (); bitmap_pad = (bitmap_pad == 3) ? 32 : bitmap_pad*8; shm_image = XShmCreateImage(dpy, DefaultVisual(dpy,screen_num), disp_depth, ZPixmap, 0, &shmi, Width, Height); if (!shm_image) { Report (CS_REPORTER_SEVERITY_ERROR, "XShmCreateImage failed!"); return 0; } shmi.shmid = shmget (IPC_PRIVATE, shm_image->bytes_per_line*shm_image->height, IPC_CREAT | 0777); if (shmi.shmid == -1) { DestroyMemory (); Report (CS_REPORTER_SEVERITY_ERROR, "shmget failed!"); return 0; } shm_image->data = shmi.shmaddr = (char*)shmat (shmi.shmid, 0, 0); if (shmi.shmaddr == (char*) -1) { DestroyMemory (); Report (CS_REPORTER_SEVERITY_ERROR, "shmat failed!"); return 0; } shmi.readOnly = false; XShmAttach (dpy, &shmi); // Delete memory segment. The memory stays available until // the last client detaches from it. XSync (dpy, False); shmctl (shmi.shmid, IPC_RMID, 0); shm_image->obdata = (char *)&shmi; this->Width = Width; this->Height = Height; return (unsigned char *)shmi.shmaddr; } void csXExtSHM::DestroyMemory () { if (shmi.shmaddr != (char*) -1) XShmDetach (dpy, &shmi); if (shm_image) XDestroyImage (shm_image); if (shmi.shmaddr != (char*) -1) shmdt (shmi.shmaddr); if (shmi.shmid != -1) shmctl (shmi.shmid, IPC_RMID, 0); shmi.shmaddr = (char*) -1; shmi.shmid = -1; shm_image = 0; } void csXExtSHM::Print (Window window, GC gc, csRect const* area) { if (area) XShmPutImage (dpy, window, gc, shm_image, area->xmin, area->ymin, area->xmin, area->ymin, area->Width (), area->Height (), False); else XShmPutImage (dpy, window, gc, shm_image, 0, 0, 0, 0, Width, Height, False); XSync (dpy, False); } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015-2016 Morwenn * * 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 <cstddef> #include <functional> #include <iterator> #include <type_traits> #include <cpp-sort/sorter_facade.h> #include <cpp-sort/sorter_traits.h> #include <cpp-sort/utility/iter_move.h> #include <cpp-sort/utility/size.h> namespace detail { template< typename ForwardIterator, typename StrictWeakOrdering > auto bubble_sort(ForwardIterator first, std::size_t size, StrictWeakOrdering compare) -> void { if (size < 2) return; while (--size) { ForwardIterator current = first; ForwardIterator next = std::next(current); for (std::size_t i = 0 ; i < size ; ++i) { if (compare(*next, *current)) { using cppsort::utility::iter_swap; iter_swap(current, next); } ++next; ++current; } } } struct bubble_sorter_impl { // Pair of iterators overload template< typename ForwardIterator, typename StrictWeakOrdering = std::less<>, typename = std::enable_if_t<not cppsort::is_projection_iterator< StrictWeakOrdering, ForwardIterator >> > auto operator()(ForwardIterator first, ForwardIterator last, StrictWeakOrdering compare={}) const -> void { static_assert( std::is_base_of< std::forward_iterator_tag, typename std::iterator_traits<ForwardIterator>::iterator_category >::value, "bubble_sorter requires at least forward iterators" ); bubble_sort(first, std::distance(first, last), compare); } // Iterable overload template< typename ForwardIterable, typename StrictWeakOrdering = std::less<>, typename = std::enable_if_t<not cppsort::is_projection< StrictWeakOrdering, ForwardIterable >> > auto operator()(ForwardIterable& iterable, StrictWeakOrdering compare={}) const -> void { static_assert( std::is_base_of< std::forward_iterator_tag, typename std::iterator_traits<decltype(std::begin(iterable))>::iterator_category >::value, "bubble_sorter requires at least forward iterators" ); bubble_sort(std::begin(iterable), cppsort::utility::size(iterable), compare); } // Sorter traits using iterator_category = std::forward_iterator_tag; using is_stable = std::true_type; }; } struct bubble_sorter: cppsort::sorter_facade<detail::bubble_sorter_impl> {}; #include <algorithm> #include <array> #include <cassert> #include <numeric> #include <cpp-sort/sort.h> int main() { // Check that the bubble_sorter can sort any permutation // of an array of 8 values // Fill the collection in sorted order std::array<int, 8> collection; std::iota(std::begin(collection), std::end(collection), 0); // Projection to sort in descending order auto projection = [](int n) { return -n; }; // For each possible permutation of collection do { auto to_sort = collection; // Bubble sort the collection cppsort::sort(to_sort, bubble_sorter{}, projection); // Check that it is sorted in descending order assert(std::is_sorted(std::begin(to_sort), std::end(to_sort), std::greater<>{})); } while (std::next_permutation(std::begin(collection), std::end(collection))); } <commit_msg>Instantiate bubble_sorter.<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015-2016 Morwenn * * 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 <cstddef> #include <functional> #include <iterator> #include <type_traits> #include <cpp-sort/sorter_facade.h> #include <cpp-sort/sorter_traits.h> #include <cpp-sort/utility/iter_move.h> #include <cpp-sort/utility/size.h> #include <cpp-sort/utility/static_const.h> namespace detail { template< typename ForwardIterator, typename StrictWeakOrdering > auto bubble_sort(ForwardIterator first, std::size_t size, StrictWeakOrdering compare) -> void { if (size < 2) return; while (--size) { ForwardIterator current = first; ForwardIterator next = std::next(current); for (std::size_t i = 0 ; i < size ; ++i) { if (compare(*next, *current)) { using cppsort::utility::iter_swap; iter_swap(current, next); } ++next; ++current; } } } struct bubble_sorter_impl { // Pair of iterators overload template< typename ForwardIterator, typename StrictWeakOrdering = std::less<>, typename = std::enable_if_t<not cppsort::is_projection_iterator< StrictWeakOrdering, ForwardIterator >> > auto operator()(ForwardIterator first, ForwardIterator last, StrictWeakOrdering compare={}) const -> void { static_assert( std::is_base_of< std::forward_iterator_tag, typename std::iterator_traits<ForwardIterator>::iterator_category >::value, "bubble_sorter requires at least forward iterators" ); bubble_sort(first, std::distance(first, last), compare); } // Iterable overload template< typename ForwardIterable, typename StrictWeakOrdering = std::less<>, typename = std::enable_if_t<not cppsort::is_projection< StrictWeakOrdering, ForwardIterable >> > auto operator()(ForwardIterable& iterable, StrictWeakOrdering compare={}) const -> void { static_assert( std::is_base_of< std::forward_iterator_tag, typename std::iterator_traits<decltype(std::begin(iterable))>::iterator_category >::value, "bubble_sorter requires at least forward iterators" ); bubble_sort(std::begin(iterable), cppsort::utility::size(iterable), compare); } // Sorter traits using iterator_category = std::forward_iterator_tag; using is_stable = std::true_type; }; } struct bubble_sorter: cppsort::sorter_facade<detail::bubble_sorter_impl> {}; namespace { constexpr auto&& bubble_sort = cppsort::utility::static_const<bubble_sorter>::value; } #include <algorithm> #include <array> #include <cassert> #include <numeric> int main() { // Check that the bubble_sorter can sort any permutation // of an array of 8 values // Fill the collection in sorted order std::array<int, 8> collection; std::iota(std::begin(collection), std::end(collection), 0); // Projection to sort in descending order auto projection = [](int n) { return -n; }; // For each possible permutation of collection do { auto to_sort = collection; // Bubble sort the collection bubble_sort(to_sort, projection); // Check that it is sorted in descending order assert(std::is_sorted(std::begin(to_sort), std::end(to_sort), std::greater<>{})); } while (std::next_permutation(std::begin(collection), std::end(collection))); } <|endoftext|>
<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #include <system_error> #ifdef _WIN32 # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <WinSock2.h> # include <WS2tcpip.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #else # include <sys/socket.h> # include <netinet/in.h> # include <errno.h> # include <poll.h> # include <netdb.h> # include <unistd.h> #endif #include "Network.hpp" #include "Client.hpp" namespace ouzel { namespace network { Network::Network() { #ifdef _WIN32 WORD sockVersion = MAKEWORD(2, 2); WSADATA wsaData; int error = WSAStartup(sockVersion, &wsaData); if (error != 0) throw std::system_error(error, std::system_category(), "Failed to start WinSock failed"); wsaStarted = true; if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) throw std::runtime_error("Invalid WinSock version"); #endif } Network::~Network() { #ifdef _WIN32 if (wsaStarted) WSACleanup(); #endif } uint32_t Network::getAddress(const std::string& address) { addrinfo* info; int ret = getaddrinfo(address.c_str(), nullptr, nullptr, &info); if (ret != 0) throw std::system_error(errno, std::system_category(), "Failed to get address info of " + address); sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(info->ai_addr); uint32_t result = ntohl(addr->sin_addr.s_addr); freeaddrinfo(info); return result; } } // namespace network } // namespace ouzel <commit_msg>Clean up WSA if the version is incorrect<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #include <system_error> #ifdef _WIN32 # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <WinSock2.h> # include <WS2tcpip.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #else # include <sys/socket.h> # include <netinet/in.h> # include <errno.h> # include <poll.h> # include <netdb.h> # include <unistd.h> #endif #include "Network.hpp" #include "Client.hpp" namespace ouzel { namespace network { Network::Network() { #ifdef _WIN32 WORD sockVersion = MAKEWORD(2, 2); WSADATA wsaData; int error = WSAStartup(sockVersion, &wsaData); if (error != 0) throw std::system_error(error, std::system_category(), "Failed to start WinSock failed"); if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); throw std::runtime_error("Invalid WinSock version"); } wsaStarted = true; #endif } Network::~Network() { #ifdef _WIN32 if (wsaStarted) WSACleanup(); #endif } uint32_t Network::getAddress(const std::string& address) { addrinfo* info; int ret = getaddrinfo(address.c_str(), nullptr, nullptr, &info); if (ret != 0) throw std::system_error(errno, std::system_category(), "Failed to get address info of " + address); sockaddr_in* addr = reinterpret_cast<sockaddr_in*>(info->ai_addr); uint32_t result = ntohl(addr->sin_addr.s_addr); freeaddrinfo(info); return result; } } // namespace network } // namespace ouzel <|endoftext|>
<commit_before>/* -*- C++ -*- This file is part of ThreadWeaver. Author: Mirko Boehm Copyright: (C) 2005-2014 Mirko Boehm Contact: [email protected] http://www.kde.org http://creative-destruction.me This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <algorithm> //for transform #include <numeric> //for accumulate #include <QtDebug> #include <QStringList> #include <QDir> #include <QFileInfo> #include <QFileInfoList> #include <QMutexLocker> #include <ThreadWeaver/ThreadWeaver> #include <ThreadWeaver/Exception> #include <ThreadWeaver/DebuggingAids> #include "Model.h" #include "PriorityDecorator.h" #include "FileLoaderJob.h" #include "ImageLoaderJob.h" #include "ComputeThumbNailJob.h" using namespace std; using namespace ThreadWeaver; Model::Model(QObject *parent) : QAbstractListModel(parent) , m_fileLoaderRestriction(4) , m_imageLoaderRestriction(4) , m_imageScalerRestriction(4) , m_fileWriterRestriction(4) { ThreadWeaver::setDebugLevel(true, 0); connect(this, SIGNAL(signalElementChanged(int)), this, SLOT(slotElementChanged(int))); } int Model::fileLoaderCap() const { return m_fileLoaderRestriction.cap(); } void Model::setFileLoaderCap(int cap) { m_fileLoaderRestriction.setCap(cap); Queue::instance()->reschedule(); } int Model::imageLoaderCap() const { return m_imageLoaderRestriction.cap(); } void Model::setImageLoaderCap(int cap) { m_imageLoaderRestriction.setCap(cap); Queue::instance()->reschedule(); } int Model::computeThumbNailCap() const { return m_imageScalerRestriction.cap(); } void Model::setComputeThumbNailCap(int cap) { m_imageScalerRestriction.setCap(cap); } int Model::saveThumbNailCap() const { return m_fileWriterRestriction.cap(); } void Model::setSaveThumbNailCap(int cap) { m_imageScalerRestriction.setCap(cap); } void Model::clear() { beginResetModel(); m_images.clear(); endResetModel(); } void Model::prepareConversions(const QFileInfoList &filenames, const QString &outputDirectory) { beginResetModel(); Q_ASSERT(m_images.isEmpty()); m_images.resize(filenames.size()); int counter = 0; auto initializeImage = [=, &counter] (const QFileInfo& file) { auto const out = QFileInfo(outputDirectory, file.fileName()).absoluteFilePath(); return Image(file.absoluteFilePath(), out, this, counter++); }; for (const auto& filename : filenames) { m_images << initializeImage(filename); } endResetModel(); } bool Model::computeThumbNailsBlockingInLoop() { for (auto it = m_images.begin(); it != m_images.end(); ++it) { Image& image = *it; try { image.loadFile(); image.loadImage(); image.computeThumbNail(); image.saveThumbNail(); } catch (const ThreadWeaver::Exception& ex) { qDebug() << ex.message(); return false; } } return true; } bool Model::computeThumbNailsBlockingConcurrent() { auto queue = stream(); for (auto it = m_images.begin(); it != m_images.end(); ++it) { Image& image = *it; auto sequence = new Sequence(); *sequence << make_job( [&image]() { image.loadFile(); } ); *sequence << make_job( [&image]() { image.loadImage(); } ); *sequence << make_job( [&image]() { image.computeThumbNail(); } ); *sequence << make_job( [&image]() { image.saveThumbNail(); } ); queue << sequence; } queue.flush(); Queue::instance()->finish(); // figure out result: foreach (const Image& image, m_images) { if (image.progress().first != Image::Step_NumberOfSteps) return false; } return true; } void Model::queueUpConversion(const QStringList &files, const QString &outputDirectory) { QFileInfoList fileInfos; transform(files.begin(), files.end(), back_inserter(fileInfos), [](const QString& file) { return QFileInfo(file); } ); prepareConversions(fileInfos, outputDirectory); //FIXME duplicated code auto queue = stream(); for (auto it = m_images.begin(); it != m_images.end(); ++it) { Image& image = *it; auto saveThumbNail = [&image]() { image.saveThumbNail(); }; auto saveThumbNailJob = new Lambda<decltype(saveThumbNail)>(saveThumbNail); { QMutexLocker l(saveThumbNailJob->mutex()); saveThumbNailJob->assignQueuePolicy(&m_fileWriterRestriction); } auto sequence = new Sequence(); *sequence << new FileLoaderJob(&image, &m_fileLoaderRestriction) << new ImageLoaderJob(&image, &m_imageLoaderRestriction) << new ComputeThumbNailJob(&image, &m_imageScalerRestriction) << new PriorityDecorator(Image::Step_SaveThumbNail, saveThumbNailJob); queue << sequence; } } Progress Model::progress() const { auto sumItUp = [](const Progress& sum, const Image& image) { auto const values = image.progress(); return qMakePair(sum.first + values.first, sum.second + values.second); }; auto const soFar = accumulate(m_images.begin(), m_images.end(), Progress(), sumItUp); return soFar; } void Model::progressChanged() { auto const p = progress(); emit progress(p.first, p.second); } void Model::elementChanged(int id) { signalElementChanged(id); } int Model::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_images.size(); } QVariant Model::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() < 0 || index.row() >= rowCount()) return QVariant(); const Image& image = m_images.at(index.row()); if (role == Qt::DisplayRole) { return image.description(); } else if (role == Role_SortRole) { return -image.processingOrder(); } else if (role == Role_ImageRole) { return QVariant::fromValue(&image); } else if (role == Role_StepRole) { return QVariant::fromValue(image.progress().first); } return QVariant(); } QVariant Model::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(section); Q_UNUSED(orientation); Q_UNUSED(role); return QVariant(); } void Model::slotElementChanged(int id) { if (id >= 0 && id < m_images.count()) { auto const i = index(id, 0); emit dataChanged(i, i); } } <commit_msg>Fixup parent commit<commit_after>/* -*- C++ -*- This file is part of ThreadWeaver. Author: Mirko Boehm Copyright: (C) 2005-2014 Mirko Boehm Contact: [email protected] http://www.kde.org http://creative-destruction.me This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <algorithm> //for transform #include <numeric> //for accumulate #include <QtDebug> #include <QStringList> #include <QDir> #include <QFileInfo> #include <QFileInfoList> #include <QMutexLocker> #include <ThreadWeaver/ThreadWeaver> #include <ThreadWeaver/Exception> #include <ThreadWeaver/DebuggingAids> #include "Model.h" #include "PriorityDecorator.h" #include "FileLoaderJob.h" #include "ImageLoaderJob.h" #include "ComputeThumbNailJob.h" using namespace std; using namespace ThreadWeaver; Model::Model(QObject *parent) : QAbstractListModel(parent) , m_fileLoaderRestriction(4) , m_imageLoaderRestriction(4) , m_imageScalerRestriction(4) , m_fileWriterRestriction(4) { ThreadWeaver::setDebugLevel(true, 0); connect(this, SIGNAL(signalElementChanged(int)), this, SLOT(slotElementChanged(int))); } int Model::fileLoaderCap() const { return m_fileLoaderRestriction.cap(); } void Model::setFileLoaderCap(int cap) { m_fileLoaderRestriction.setCap(cap); Queue::instance()->reschedule(); } int Model::imageLoaderCap() const { return m_imageLoaderRestriction.cap(); } void Model::setImageLoaderCap(int cap) { m_imageLoaderRestriction.setCap(cap); Queue::instance()->reschedule(); } int Model::computeThumbNailCap() const { return m_imageScalerRestriction.cap(); } void Model::setComputeThumbNailCap(int cap) { m_imageScalerRestriction.setCap(cap); } int Model::saveThumbNailCap() const { return m_fileWriterRestriction.cap(); } void Model::setSaveThumbNailCap(int cap) { m_imageScalerRestriction.setCap(cap); } void Model::clear() { beginResetModel(); m_images.clear(); endResetModel(); } void Model::prepareConversions(const QFileInfoList &filenames, const QString &outputDirectory) { beginResetModel(); Q_ASSERT(m_images.isEmpty()); m_images.reserve(filenames.size()); int counter = 0; auto initializeImage = [=, &counter] (const QFileInfo& file) { auto const out = QFileInfo(outputDirectory, file.fileName()).absoluteFilePath(); return Image(file.absoluteFilePath(), out, this, counter++); }; for (const auto& filename : filenames) { m_images << initializeImage(filename); } endResetModel(); } bool Model::computeThumbNailsBlockingInLoop() { for (auto it = m_images.begin(); it != m_images.end(); ++it) { Image& image = *it; try { image.loadFile(); image.loadImage(); image.computeThumbNail(); image.saveThumbNail(); } catch (const ThreadWeaver::Exception& ex) { qDebug() << ex.message(); return false; } } return true; } bool Model::computeThumbNailsBlockingConcurrent() { auto queue = stream(); for (auto it = m_images.begin(); it != m_images.end(); ++it) { Image& image = *it; auto sequence = new Sequence(); *sequence << make_job( [&image]() { image.loadFile(); } ); *sequence << make_job( [&image]() { image.loadImage(); } ); *sequence << make_job( [&image]() { image.computeThumbNail(); } ); *sequence << make_job( [&image]() { image.saveThumbNail(); } ); queue << sequence; } queue.flush(); Queue::instance()->finish(); // figure out result: foreach (const Image& image, m_images) { if (image.progress().first != Image::Step_NumberOfSteps) return false; } return true; } void Model::queueUpConversion(const QStringList &files, const QString &outputDirectory) { QFileInfoList fileInfos; transform(files.begin(), files.end(), back_inserter(fileInfos), [](const QString& file) { return QFileInfo(file); } ); prepareConversions(fileInfos, outputDirectory); //FIXME duplicated code auto queue = stream(); for (auto it = m_images.begin(); it != m_images.end(); ++it) { Image& image = *it; auto saveThumbNail = [&image]() { image.saveThumbNail(); }; auto saveThumbNailJob = new Lambda<decltype(saveThumbNail)>(saveThumbNail); { QMutexLocker l(saveThumbNailJob->mutex()); saveThumbNailJob->assignQueuePolicy(&m_fileWriterRestriction); } auto sequence = new Sequence(); *sequence << new FileLoaderJob(&image, &m_fileLoaderRestriction) << new ImageLoaderJob(&image, &m_imageLoaderRestriction) << new ComputeThumbNailJob(&image, &m_imageScalerRestriction) << new PriorityDecorator(Image::Step_SaveThumbNail, saveThumbNailJob); queue << sequence; } } Progress Model::progress() const { auto sumItUp = [](const Progress& sum, const Image& image) { auto const values = image.progress(); return qMakePair(sum.first + values.first, sum.second + values.second); }; auto const soFar = accumulate(m_images.begin(), m_images.end(), Progress(), sumItUp); return soFar; } void Model::progressChanged() { auto const p = progress(); emit progress(p.first, p.second); } void Model::elementChanged(int id) { signalElementChanged(id); } int Model::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_images.size(); } QVariant Model::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() < 0 || index.row() >= rowCount()) return QVariant(); const Image& image = m_images.at(index.row()); if (role == Qt::DisplayRole) { return image.description(); } else if (role == Role_SortRole) { return -image.processingOrder(); } else if (role == Role_ImageRole) { return QVariant::fromValue(&image); } else if (role == Role_StepRole) { return QVariant::fromValue(image.progress().first); } return QVariant(); } QVariant Model::headerData(int section, Qt::Orientation orientation, int role) const { Q_UNUSED(section); Q_UNUSED(orientation); Q_UNUSED(role); return QVariant(); } void Model::slotElementChanged(int id) { if (id >= 0 && id < m_images.count()) { auto const i = index(id, 0); emit dataChanged(i, i); } } <|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/ * Copyright (C) 2008 Brian Aker, Eric Day * 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. * * * The names of its contributors may not 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. * */ /** * @file * @brief libmemcached Queue Storage Definitions */ #include <libgearman-server/plugins/queue/libmemcached/queue.h> #if defined(GEARMAND_PLUGINS_QUEUE_LIBMEMCACHED_H) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" using namespace gearmand; /** * @addtogroup gearmand::plugins::queue::Libmemcachedatic Static libmemcached Queue Storage Functions * @ingroup gearman_queue_libmemcached * @{ */ /** * Default values. */ static constexpr const char GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX[] = "gear_"; namespace gearmand { namespace plugins { namespace queue { class Libmemcached; }}} namespace gearmand { namespace queue { class LibmemcachedQueue : public gearmand::queue::Context { public: LibmemcachedQueue(memcached_server_st* servers): memc_(nullptr) { memc_= memcached_create(nullptr); memcached_server_push(memc_, servers); } bool init() { return bool(bool(memc_) and memcached_server_count(memc_)); } ~LibmemcachedQueue() { memcached_free(memc_); memc_= nullptr; } gearmand_error_t add(gearman_server_st *server, const char *unique, size_t unique_size, const char *function_name, size_t function_name_size, const void *data, size_t data_size, gearman_job_priority_t priority, int64_t when); gearmand_error_t flush(gearman_server_st *server); gearmand_error_t done(gearman_server_st *server, const char *unique, size_t unique_size, const char *function_name, size_t function_name_size); gearmand_error_t replay(gearman_server_st *server); private: memcached_st* memc_; }; } // namespace queue } // namespace gearmand namespace gearmand { namespace plugins { namespace queue { class Libmemcached : public gearmand::plugins::Queue { public: Libmemcached (); ~Libmemcached (); gearmand_error_t initialize(); std::string server_list; private: }; Libmemcached::Libmemcached() : Queue("libmemcached") { command_line_options().add_options() ("libmemcached-servers", boost::program_options::value(&server_list), "List of Memcached servers to use."); } Libmemcached::~Libmemcached() { } gearmand_error_t Libmemcached::initialize() { gearmand_info("Initializing libmemcached module"); memcached_server_st *servers= memcached_servers_parse(server_list.c_str()); if (!servers) { return gearmand_gerror("memcached_servers_parse", GEARMAND_QUEUE_ERROR); } gearmand::queue::LibmemcachedQueue* exec_queue = new gearmand::queue::LibmemcachedQueue { servers }; if (exec_queue and exec_queue->init()) { gearman_server_set_queue(Gearmand()->server, exec_queue); memcached_server_list_free(servers); return GEARMAND_SUCCESS; } return gearmand_gerror("Libmemcached::initialize()", GEARMAND_QUEUE_ERROR); } void initialize_libmemcached() { static Libmemcached local_instance {}; } } // namespace queue } // namespace plugins } // namespace gearmand /* Queue callback functions. */ namespace gearmand { namespace queue { gearmand_error_t LibmemcachedQueue::add(gearman_server_st *server, const char *unique, size_t unique_size, const char *function_name, size_t function_name_size, const void *data, size_t data_size, gearman_job_priority_t priority, int64_t when) { if (when) // No support for EPOCH jobs { return gearmand_gerror("libmemcached queue does not support epoch jobs", GEARMAND_QUEUE_ERROR); } (void)server; gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "libmemcached add: %.*s", (uint32_t)unique_size, (char *)unique); char key[MEMCACHED_MAX_KEY]; size_t key_length= (size_t)snprintf(key, MEMCACHED_MAX_KEY, "%s%.*s-%.*s", GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX, (int)function_name_size, (const char *)function_name, (int)unique_size, (const char *)unique); memcached_return_t rc= memcached_set(memc_, (const char *)key, key_length, (const char *)data, data_size, 0, (uint32_t)priority); if (rc != MEMCACHED_SUCCESS) { return gearmand_gerror(memcached_last_error_message(memc_), GEARMAND_QUEUE_ERROR); } return GEARMAND_SUCCESS; } gearmand_error_t LibmemcachedQueue::flush(gearman_server_st *) { gearmand_debug("libmemcached flush"); return GEARMAND_SUCCESS; } gearmand_error_t LibmemcachedQueue::done(gearman_server_st*, const char *unique, size_t unique_size, const char *function_name, size_t function_name_size) { char key[MEMCACHED_MAX_KEY]; gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "libmemcached done: %.*s", (uint32_t)unique_size, (char *)unique); size_t key_length= (size_t)snprintf(key, MEMCACHED_MAX_KEY, "%s%.*s-%.*s", GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX, (int)function_name_size, (const char *)function_name, (int)unique_size, (const char *)unique); /* For the moment we will assume it happened */ memcached_return_t rc= memcached_delete(memc_, (const char *)key, key_length, 0); if (rc != MEMCACHED_SUCCESS) { return gearmand_gerror(memcached_last_error_message(memc_), GEARMAND_QUEUE_ERROR); } return GEARMAND_SUCCESS; } class Replay { public: Replay(gearman_server_st* server_arg, memcached_st* _memc) : server_(server_arg), memc_(nullptr) { memc_= memcached_clone(nullptr, _memc); } ~Replay() { memcached_free(memc_); memc_= nullptr; } bool init() { return bool(memc_); } memcached_st* memc() { assert(memc_); return memc_; } gearman_server_st* server() { return server_; } private: gearman_server_st* server_; memcached_st* memc_; }; static memcached_return_t callback_loader(const memcached_st*, memcached_result_st* result, void *context) { Replay* replay= (Replay*)context; const char *key= memcached_result_key_value(result); if (strncmp(key, GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX, strlen(GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX)) != 0) { gearmand_debug("memcached key did not match GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX"); return MEMCACHED_SUCCESS; } const char* function= key +strlen(GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX); const char* unique= index(function, '-'); if (!unique) { gearmand_debug("memcached key was malformed was not found"); return MEMCACHED_SUCCESS; } size_t function_len= size_t(unique -function); unique++; size_t unique_size= strlen(unique); assert(function); assert(function_len); /* need to make a copy here ... gearman_server_job_free will free it later */ char* data= (char*)malloc(memcached_result_length(result)); if (!data) { gearmand_perror(errno, "malloc"); return MEMCACHED_MEMORY_ALLOCATION_FAILURE; } memcpy(data, memcached_result_value(result), memcached_result_length(result)); gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "libmemcached replay_add: %.*s", (uint32_t)unique_size, (char *)unique); /* Currently not looking at failure cases */ LibmemcachedQueue::replay_add(replay->server(), nullptr, unique, unique_size, function, function_len, data, memcached_result_length(result), static_cast<gearman_job_priority_t>(memcached_result_flags(result)), int64_t(0)); return MEMCACHED_SUCCESS; } /* Grab the object and load it into the loader */ static memcached_return_t callback_for_key(const memcached_st*, const char *key, size_t key_length, void *context) { Replay* replay= (Replay*)context; memcached_execute_fn callbacks{(memcached_execute_fn)&callback_loader}; char *passable{(char *)key}; if (memcached_success(memcached_mget(replay->memc(), &passable, &key_length, 1))) { gearmand_debug(memcached_last_error_message(replay->memc())); } /* Just void errors for the moment, since other treads might have picked up the object. */ (void)memcached_fetch_execute(replay->memc(), &callbacks, replay, 1); return MEMCACHED_SUCCESS; } /* If we have any failures for loading values back into replay we just ignore them. */ gearmand_error_t LibmemcachedQueue::replay(gearman_server_st *server) { memcached_dump_fn callbacks{(memcached_dump_fn)&callback_for_key}; gearmand_debug("libmemcached replay start"); memcached_st* local_clone= memcached_clone(nullptr, memc_); if (local_clone) { Replay replay_exec(server, memc_); if (replay_exec.init()) { (void)memcached_dump(local_clone, &callbacks, (void *)&replay_exec, 1); } else { gearmand_debug("libmemcached failed to init() Replay"); } memcached_free(local_clone); local_clone= nullptr; } gearmand_debug("libmemcached replay stop"); return GEARMAND_SUCCESS; } } // queue } // gearmand #pragma GCC diagnostic pop #endif // defined(GEARMAND_PLUGINS_QUEUE_LIBMEMCACHED_H) <commit_msg>replace memcached_last_error_message by memcached_strerror<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/ * Copyright (C) 2008 Brian Aker, Eric Day * 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. * * * The names of its contributors may not 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. * */ /** * @file * @brief libmemcached Queue Storage Definitions */ #include <libgearman-server/plugins/queue/libmemcached/queue.h> #if defined(GEARMAND_PLUGINS_QUEUE_LIBMEMCACHED_H) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" using namespace gearmand; /** * @addtogroup gearmand::plugins::queue::Libmemcachedatic Static libmemcached Queue Storage Functions * @ingroup gearman_queue_libmemcached * @{ */ /** * Default values. */ static constexpr const char GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX[] = "gear_"; namespace gearmand { namespace plugins { namespace queue { class Libmemcached; }}} namespace gearmand { namespace queue { class LibmemcachedQueue : public gearmand::queue::Context { public: LibmemcachedQueue(memcached_server_st* servers): memc_(nullptr) { memc_= memcached_create(nullptr); memcached_server_push(memc_, servers); } bool init() { return bool(bool(memc_) and memcached_server_count(memc_)); } ~LibmemcachedQueue() { memcached_free(memc_); memc_= nullptr; } gearmand_error_t add(gearman_server_st *server, const char *unique, size_t unique_size, const char *function_name, size_t function_name_size, const void *data, size_t data_size, gearman_job_priority_t priority, int64_t when); gearmand_error_t flush(gearman_server_st *server); gearmand_error_t done(gearman_server_st *server, const char *unique, size_t unique_size, const char *function_name, size_t function_name_size); gearmand_error_t replay(gearman_server_st *server); private: memcached_st* memc_; }; } // namespace queue } // namespace gearmand namespace gearmand { namespace plugins { namespace queue { class Libmemcached : public gearmand::plugins::Queue { public: Libmemcached (); ~Libmemcached (); gearmand_error_t initialize(); std::string server_list; private: }; Libmemcached::Libmemcached() : Queue("libmemcached") { command_line_options().add_options() ("libmemcached-servers", boost::program_options::value(&server_list), "List of Memcached servers to use."); } Libmemcached::~Libmemcached() { } gearmand_error_t Libmemcached::initialize() { gearmand_info("Initializing libmemcached module"); memcached_server_st *servers= memcached_servers_parse(server_list.c_str()); if (!servers) { return gearmand_gerror("memcached_servers_parse", GEARMAND_QUEUE_ERROR); } gearmand::queue::LibmemcachedQueue* exec_queue = new gearmand::queue::LibmemcachedQueue { servers }; if (exec_queue and exec_queue->init()) { gearman_server_set_queue(Gearmand()->server, exec_queue); memcached_server_list_free(servers); return GEARMAND_SUCCESS; } return gearmand_gerror("Libmemcached::initialize()", GEARMAND_QUEUE_ERROR); } void initialize_libmemcached() { static Libmemcached local_instance {}; } } // namespace queue } // namespace plugins } // namespace gearmand /* Queue callback functions. */ namespace gearmand { namespace queue { gearmand_error_t LibmemcachedQueue::add(gearman_server_st *server, const char *unique, size_t unique_size, const char *function_name, size_t function_name_size, const void *data, size_t data_size, gearman_job_priority_t priority, int64_t when) { if (when) // No support for EPOCH jobs { return gearmand_gerror("libmemcached queue does not support epoch jobs", GEARMAND_QUEUE_ERROR); } (void)server; gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "libmemcached add: %.*s", (uint32_t)unique_size, (char *)unique); char key[MEMCACHED_MAX_KEY]; size_t key_length= (size_t)snprintf(key, MEMCACHED_MAX_KEY, "%s%.*s-%.*s", GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX, (int)function_name_size, (const char *)function_name, (int)unique_size, (const char *)unique); memcached_return_t rc= memcached_set(memc_, (const char *)key, key_length, (const char *)data, data_size, 0, (uint32_t)priority); if (rc != MEMCACHED_SUCCESS) { return gearmand_gerror(memcached_last_error_message(memc_), GEARMAND_QUEUE_ERROR); } return GEARMAND_SUCCESS; } gearmand_error_t LibmemcachedQueue::flush(gearman_server_st *) { gearmand_debug("libmemcached flush"); return GEARMAND_SUCCESS; } gearmand_error_t LibmemcachedQueue::done(gearman_server_st*, const char *unique, size_t unique_size, const char *function_name, size_t function_name_size) { char key[MEMCACHED_MAX_KEY]; gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "libmemcached done: %.*s", (uint32_t)unique_size, (char *)unique); size_t key_length= (size_t)snprintf(key, MEMCACHED_MAX_KEY, "%s%.*s-%.*s", GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX, (int)function_name_size, (const char *)function_name, (int)unique_size, (const char *)unique); /* For the moment we will assume it happened */ memcached_return_t rc= memcached_delete(memc_, (const char *)key, key_length, 0); if (rc != MEMCACHED_SUCCESS) { return gearmand_gerror(memcached_last_error_message(memc_), GEARMAND_QUEUE_ERROR); } return GEARMAND_SUCCESS; } class Replay { public: Replay(gearman_server_st* server_arg, memcached_st* _memc) : server_(server_arg), memc_(nullptr) { memc_= memcached_clone(nullptr, _memc); } ~Replay() { memcached_free(memc_); memc_= nullptr; } bool init() { return bool(memc_); } memcached_st* memc() { assert(memc_); return memc_; } gearman_server_st* server() { return server_; } private: gearman_server_st* server_; memcached_st* memc_; }; static memcached_return_t callback_loader(const memcached_st*, memcached_result_st* result, void *context) { Replay* replay= (Replay*)context; const char *key= memcached_result_key_value(result); if (strncmp(key, GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX, strlen(GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX)) != 0) { gearmand_debug("memcached key did not match GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX"); return MEMCACHED_SUCCESS; } const char* function= key +strlen(GEARMAND_QUEUE_LIBMEMCACHED_DEFAULT_PREFIX); const char* unique= index(function, '-'); if (!unique) { gearmand_debug("memcached key was malformed was not found"); return MEMCACHED_SUCCESS; } size_t function_len= size_t(unique -function); unique++; size_t unique_size= strlen(unique); assert(function); assert(function_len); /* need to make a copy here ... gearman_server_job_free will free it later */ char* data= (char*)malloc(memcached_result_length(result)); if (!data) { gearmand_perror(errno, "malloc"); return MEMCACHED_MEMORY_ALLOCATION_FAILURE; } memcpy(data, memcached_result_value(result), memcached_result_length(result)); gearmand_log_debug(GEARMAN_DEFAULT_LOG_PARAM, "libmemcached replay_add: %.*s", (uint32_t)unique_size, (char *)unique); /* Currently not looking at failure cases */ LibmemcachedQueue::replay_add(replay->server(), nullptr, unique, unique_size, function, function_len, data, memcached_result_length(result), static_cast<gearman_job_priority_t>(memcached_result_flags(result)), int64_t(0)); return MEMCACHED_SUCCESS; } /* Grab the object and load it into the loader */ static memcached_return_t callback_for_key(const memcached_st*, const char *key, size_t key_length, void *context) { Replay* replay= (Replay*)context; memcached_execute_fn callbacks{(memcached_execute_fn)&callback_loader}; char *passable{(char *)key}; memcached_return_t rc = memcached_mget(replay->memc(), &passable, &key_length, 1); if (memcached_success(rc)) { gearmand_debug(memcached_strerror(replay->memc(), rc)); } /* Just void errors for the moment, since other treads might have picked up the object. */ (void)memcached_fetch_execute(replay->memc(), &callbacks, replay, 1); return MEMCACHED_SUCCESS; } /* If we have any failures for loading values back into replay we just ignore them. */ gearmand_error_t LibmemcachedQueue::replay(gearman_server_st *server) { memcached_dump_fn callbacks{(memcached_dump_fn)&callback_for_key}; gearmand_debug("libmemcached replay start"); memcached_st* local_clone= memcached_clone(nullptr, memc_); if (local_clone) { Replay replay_exec(server, memc_); if (replay_exec.init()) { (void)memcached_dump(local_clone, &callbacks, (void *)&replay_exec, 1); } else { gearmand_debug("libmemcached failed to init() Replay"); } memcached_free(local_clone); local_clone= nullptr; } gearmand_debug("libmemcached replay stop"); return GEARMAND_SUCCESS; } } // queue } // gearmand #pragma GCC diagnostic pop #endif // defined(GEARMAND_PLUGINS_QUEUE_LIBMEMCACHED_H) <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/options/content_page_view.h" #include <windows.h> #include <shlobj.h> #include <vsstyle.h> #include <vssym32.h> #include "app/gfx/canvas.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/command_line.h" #include "base/gfx/native_theme.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/views/clear_browsing_data.h" #include "chrome/browser/views/importer_view.h" #include "chrome/browser/views/options/options_group_view.h" #include "chrome/browser/views/options/passwords_exceptions_window_view.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "grit/generated_resources.h" #include "views/controls/button/radio_button.h" #include "views/grid_layout.h" #include "views/standard_layout.h" #include "views/widget/widget.h" namespace { const int kPopupBlockingRadioGroup = 1; const int kPasswordSavingRadioGroup = 2; } // namespace ContentPageView::ContentPageView(Profile* profile) : passwords_exceptions_button_(NULL), passwords_group_(NULL), passwords_asktosave_radio_(NULL), passwords_neversave_radio_(NULL), themes_group_(NULL), themes_reset_button_(NULL), import_group_(NULL), import_label_(NULL), import_button_(NULL), clear_data_group_(NULL), clear_data_label_(NULL), clear_data_button_(NULL), OptionsPageView(profile) { } ContentPageView::~ContentPageView() { } /////////////////////////////////////////////////////////////////////////////// // ContentPageView, views::ButtonListener implementation: void ContentPageView::ButtonPressed(views::Button* sender) { if (sender == passwords_asktosave_radio_ || sender == passwords_neversave_radio_) { bool enabled = passwords_asktosave_radio_->checked(); if (enabled) { UserMetricsRecordAction(L"Options_PasswordManager_Enable", profile()->GetPrefs()); } else { UserMetricsRecordAction(L"Options_PasswordManager_Disable", profile()->GetPrefs()); } ask_to_save_passwords_.SetValue(enabled); } else if (sender == passwords_exceptions_button_) { UserMetricsRecordAction(L"Options_ShowPasswordsExceptions", NULL); PasswordsExceptionsWindowView::Show(profile()); } else if (sender == form_autofill_checkbox_) { bool enabled = form_autofill_checkbox_->checked(); if (enabled) { UserMetricsRecordAction(L"Options_FormAutofill_Enable", profile()->GetPrefs()); } else { UserMetricsRecordAction(L"Options_FormAutofill_Disable", profile()->GetPrefs()); } form_autofill_.SetValue(enabled); } else if (sender == themes_reset_button_) { UserMetricsRecordAction(L"Options_ThemesReset", profile()->GetPrefs()); profile()->ClearTheme(); } else if (sender == import_button_) { views::Window::CreateChromeWindow( GetWindow()->GetNativeWindow(), gfx::Rect(), new ImporterView(profile()))->Show(); } else if (sender == clear_data_button_) { views::Window::CreateChromeWindow( GetWindow()->GetNativeWindow(), gfx::Rect(), new ClearBrowsingDataView(profile()))->Show(); } } //////////////////////////////////////////////////////////////////////////////// // ContentPageView, OptionsPageView implementation: void ContentPageView::InitControlLayout() { using views::GridLayout; using views::ColumnSet; GridLayout* layout = new GridLayout(this); layout->SetInsets(5, 5, 5, 5); SetLayoutManager(layout); const int single_column_view_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); InitPasswordSavingGroup(); layout->AddView(passwords_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); InitFormAutofillGroup(); layout->AddView(form_autofill_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); InitImportGroup(); layout->AddView(import_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); InitClearDataGroup(); layout->AddView(clear_data_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); if (CommandLine::ForCurrentProcess()-> HasSwitch(switches::kEnableExtensions)) { layout->StartRow(0, single_column_view_set_id); InitThemesGroup(); layout->AddView(themes_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } // Init member prefs so we can update the controls if prefs change. ask_to_save_passwords_.Init(prefs::kPasswordManagerEnabled, profile()->GetPrefs(), this); form_autofill_.Init(prefs::kFormAutofillEnabled, profile()->GetPrefs(), this); } void ContentPageView::NotifyPrefChanged(const std::wstring* pref_name) { if (!pref_name || *pref_name == prefs::kPasswordManagerEnabled) { if (ask_to_save_passwords_.GetValue()) { passwords_asktosave_radio_->SetChecked(true); } else { passwords_neversave_radio_->SetChecked(true); } } if (!pref_name || *pref_name == prefs::kFormAutofillEnabled) { form_autofill_checkbox_->SetChecked(form_autofill_.GetValue()); } } /////////////////////////////////////////////////////////////////////////////// // ContentsPageView, views::View overrides: void ContentPageView::Layout() { // We need to Layout twice - once to get the width of the contents box... View::Layout(); passwords_asktosave_radio_->SetBounds( 0, 0, passwords_group_->GetContentsWidth(), 0); passwords_neversave_radio_->SetBounds( 0, 0, passwords_group_->GetContentsWidth(), 0); import_label_->SetBounds(0, 0, import_group_->GetContentsWidth(), 0); clear_data_label_->SetBounds(0, 0, clear_data_group_->GetContentsWidth(), 0); // ... and twice to get the height of multi-line items correct. View::Layout(); } /////////////////////////////////////////////////////////////////////////////// // ContentPageView, private: void ContentPageView::InitPasswordSavingGroup() { passwords_asktosave_radio_ = new views::RadioButton( l10n_util::GetString(IDS_OPTIONS_PASSWORDS_ASKTOSAVE), kPasswordSavingRadioGroup); passwords_asktosave_radio_->set_listener(this); passwords_asktosave_radio_->SetMultiLine(true); passwords_neversave_radio_ = new views::RadioButton( l10n_util::GetString(IDS_OPTIONS_PASSWORDS_NEVERSAVE), kPasswordSavingRadioGroup); passwords_neversave_radio_->set_listener(this); passwords_neversave_radio_->SetMultiLine(true); passwords_exceptions_button_ = new views::NativeButton( this, l10n_util::GetString(IDS_OPTIONS_PASSWORDS_EXCEPTIONS)); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 1; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); const int double_column_view_set_id = 0; column_set = layout->AddColumnSet(double_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); layout->AddView(passwords_asktosave_radio_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); layout->AddView(passwords_neversave_radio_); layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); layout->AddView(passwords_exceptions_button_); passwords_group_ = new OptionsGroupView( contents, l10n_util::GetString(IDS_OPTIONS_PASSWORDS_GROUP_NAME), L"", true); } void ContentPageView::InitFormAutofillGroup() { form_autofill_checkbox_ = new views::Checkbox( l10n_util::GetString(IDS_AUTOFILL_SAVEFORMS)); form_autofill_checkbox_->set_listener(this); form_autofill_checkbox_->SetMultiLine(true); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 1; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); layout->AddView(form_autofill_checkbox_); form_autofill_group_ = new OptionsGroupView( contents, l10n_util::GetString(IDS_AUTOFILL_SETTING_WINDOWS_GROUP_NAME), L"", true); } void ContentPageView::InitThemesGroup() { themes_reset_button_ = new views::NativeButton(this, l10n_util::GetString(IDS_THEMES_RESET_BUTTON)); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 1; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); layout->AddView(themes_reset_button_); themes_group_ = new OptionsGroupView( contents, l10n_util::GetString(IDS_THEMES_GROUP_NAME), L"", false); } void ContentPageView::InitClearDataGroup() { clear_data_button_ = new views::NativeButton(this, l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_BUTTON)); clear_data_label_ = new views::Label( l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_INFO)); clear_data_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); clear_data_label_->SetMultiLine(true); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 1; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); layout->AddView(clear_data_label_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); layout->AddView(clear_data_button_); clear_data_group_ = new OptionsGroupView( contents, l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_GROUP_NAME), L"", true); } void ContentPageView::InitImportGroup() { import_button_ = new views::NativeButton(this, l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_BUTTON)); import_label_ = new views::Label( l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_INFO)); import_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); import_label_->SetMultiLine(true); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 1; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); layout->AddView(import_label_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); layout->AddView(import_button_); import_group_ = new OptionsGroupView( contents, l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_GROUP_NAME), L"", true); } <commit_msg>Now that themes are enabled by default, the option should be visible by default.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/options/content_page_view.h" #include <windows.h> #include <shlobj.h> #include <vsstyle.h> #include <vssym32.h> #include "app/gfx/canvas.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/gfx/native_theme.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/views/clear_browsing_data.h" #include "chrome/browser/views/importer_view.h" #include "chrome/browser/views/options/options_group_view.h" #include "chrome/browser/views/options/passwords_exceptions_window_view.h" #include "chrome/common/pref_names.h" #include "grit/generated_resources.h" #include "views/controls/button/radio_button.h" #include "views/grid_layout.h" #include "views/standard_layout.h" #include "views/widget/widget.h" namespace { const int kPopupBlockingRadioGroup = 1; const int kPasswordSavingRadioGroup = 2; } // namespace ContentPageView::ContentPageView(Profile* profile) : passwords_exceptions_button_(NULL), passwords_group_(NULL), passwords_asktosave_radio_(NULL), passwords_neversave_radio_(NULL), themes_group_(NULL), themes_reset_button_(NULL), import_group_(NULL), import_label_(NULL), import_button_(NULL), clear_data_group_(NULL), clear_data_label_(NULL), clear_data_button_(NULL), OptionsPageView(profile) { } ContentPageView::~ContentPageView() { } /////////////////////////////////////////////////////////////////////////////// // ContentPageView, views::ButtonListener implementation: void ContentPageView::ButtonPressed(views::Button* sender) { if (sender == passwords_asktosave_radio_ || sender == passwords_neversave_radio_) { bool enabled = passwords_asktosave_radio_->checked(); if (enabled) { UserMetricsRecordAction(L"Options_PasswordManager_Enable", profile()->GetPrefs()); } else { UserMetricsRecordAction(L"Options_PasswordManager_Disable", profile()->GetPrefs()); } ask_to_save_passwords_.SetValue(enabled); } else if (sender == passwords_exceptions_button_) { UserMetricsRecordAction(L"Options_ShowPasswordsExceptions", NULL); PasswordsExceptionsWindowView::Show(profile()); } else if (sender == form_autofill_checkbox_) { bool enabled = form_autofill_checkbox_->checked(); if (enabled) { UserMetricsRecordAction(L"Options_FormAutofill_Enable", profile()->GetPrefs()); } else { UserMetricsRecordAction(L"Options_FormAutofill_Disable", profile()->GetPrefs()); } form_autofill_.SetValue(enabled); } else if (sender == themes_reset_button_) { UserMetricsRecordAction(L"Options_ThemesReset", profile()->GetPrefs()); profile()->ClearTheme(); } else if (sender == import_button_) { views::Window::CreateChromeWindow( GetWindow()->GetNativeWindow(), gfx::Rect(), new ImporterView(profile()))->Show(); } else if (sender == clear_data_button_) { views::Window::CreateChromeWindow( GetWindow()->GetNativeWindow(), gfx::Rect(), new ClearBrowsingDataView(profile()))->Show(); } } //////////////////////////////////////////////////////////////////////////////// // ContentPageView, OptionsPageView implementation: void ContentPageView::InitControlLayout() { using views::GridLayout; using views::ColumnSet; GridLayout* layout = new GridLayout(this); layout->SetInsets(5, 5, 5, 5); SetLayoutManager(layout); const int single_column_view_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); InitPasswordSavingGroup(); layout->AddView(passwords_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); InitFormAutofillGroup(); layout->AddView(form_autofill_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); InitImportGroup(); layout->AddView(import_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); InitClearDataGroup(); layout->AddView(clear_data_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); InitThemesGroup(); layout->AddView(themes_group_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); // Init member prefs so we can update the controls if prefs change. ask_to_save_passwords_.Init(prefs::kPasswordManagerEnabled, profile()->GetPrefs(), this); form_autofill_.Init(prefs::kFormAutofillEnabled, profile()->GetPrefs(), this); } void ContentPageView::NotifyPrefChanged(const std::wstring* pref_name) { if (!pref_name || *pref_name == prefs::kPasswordManagerEnabled) { if (ask_to_save_passwords_.GetValue()) { passwords_asktosave_radio_->SetChecked(true); } else { passwords_neversave_radio_->SetChecked(true); } } if (!pref_name || *pref_name == prefs::kFormAutofillEnabled) { form_autofill_checkbox_->SetChecked(form_autofill_.GetValue()); } } /////////////////////////////////////////////////////////////////////////////// // ContentsPageView, views::View overrides: void ContentPageView::Layout() { // We need to Layout twice - once to get the width of the contents box... View::Layout(); passwords_asktosave_radio_->SetBounds( 0, 0, passwords_group_->GetContentsWidth(), 0); passwords_neversave_radio_->SetBounds( 0, 0, passwords_group_->GetContentsWidth(), 0); import_label_->SetBounds(0, 0, import_group_->GetContentsWidth(), 0); clear_data_label_->SetBounds(0, 0, clear_data_group_->GetContentsWidth(), 0); // ... and twice to get the height of multi-line items correct. View::Layout(); } /////////////////////////////////////////////////////////////////////////////// // ContentPageView, private: void ContentPageView::InitPasswordSavingGroup() { passwords_asktosave_radio_ = new views::RadioButton( l10n_util::GetString(IDS_OPTIONS_PASSWORDS_ASKTOSAVE), kPasswordSavingRadioGroup); passwords_asktosave_radio_->set_listener(this); passwords_asktosave_radio_->SetMultiLine(true); passwords_neversave_radio_ = new views::RadioButton( l10n_util::GetString(IDS_OPTIONS_PASSWORDS_NEVERSAVE), kPasswordSavingRadioGroup); passwords_neversave_radio_->set_listener(this); passwords_neversave_radio_->SetMultiLine(true); passwords_exceptions_button_ = new views::NativeButton( this, l10n_util::GetString(IDS_OPTIONS_PASSWORDS_EXCEPTIONS)); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 1; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); const int double_column_view_set_id = 0; column_set = layout->AddColumnSet(double_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); layout->AddView(passwords_asktosave_radio_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); layout->AddView(passwords_neversave_radio_); layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); layout->AddView(passwords_exceptions_button_); passwords_group_ = new OptionsGroupView( contents, l10n_util::GetString(IDS_OPTIONS_PASSWORDS_GROUP_NAME), L"", true); } void ContentPageView::InitFormAutofillGroup() { form_autofill_checkbox_ = new views::Checkbox( l10n_util::GetString(IDS_AUTOFILL_SAVEFORMS)); form_autofill_checkbox_->set_listener(this); form_autofill_checkbox_->SetMultiLine(true); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 1; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); layout->AddView(form_autofill_checkbox_); form_autofill_group_ = new OptionsGroupView( contents, l10n_util::GetString(IDS_AUTOFILL_SETTING_WINDOWS_GROUP_NAME), L"", true); } void ContentPageView::InitThemesGroup() { themes_reset_button_ = new views::NativeButton(this, l10n_util::GetString(IDS_THEMES_RESET_BUTTON)); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 1; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); layout->AddView(themes_reset_button_); themes_group_ = new OptionsGroupView( contents, l10n_util::GetString(IDS_THEMES_GROUP_NAME), L"", false); } void ContentPageView::InitClearDataGroup() { clear_data_button_ = new views::NativeButton(this, l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_BUTTON)); clear_data_label_ = new views::Label( l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_INFO)); clear_data_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); clear_data_label_->SetMultiLine(true); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 1; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); layout->AddView(clear_data_label_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); layout->AddView(clear_data_button_); clear_data_group_ = new OptionsGroupView( contents, l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_GROUP_NAME), L"", true); } void ContentPageView::InitImportGroup() { import_button_ = new views::NativeButton(this, l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_BUTTON)); import_label_ = new views::Label( l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_INFO)); import_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); import_label_->SetMultiLine(true); using views::GridLayout; using views::ColumnSet; views::View* contents = new views::View; GridLayout* layout = new GridLayout(contents); contents->SetLayoutManager(layout); const int single_column_view_set_id = 1; ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_view_set_id); layout->AddView(import_label_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_view_set_id); layout->AddView(import_button_); import_group_ = new OptionsGroupView( contents, l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_GROUP_NAME), L"", true); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include "Network.hpp" #include <swift2d/utils/Logger.hpp> #include <../../third_party/raknet/src/MessageIdentifiers.h> #include <../../third_party/raknet/src/RakNetTypes.h> #include <../../third_party/raknet/src/RakPeerInterface.h> #include <../../third_party/raknet/src/BitStream.h> #include <../../third_party/raknet/src/FullyConnectedMesh2.h> #include <../../third_party/raknet/src/PacketLogger.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <sstream> namespace swift { //////////////////////////////////////////////////////////////////////////////// Network::Network() : phase_(OPENING_UPNP) { update_timer_.start(); Logger::LOG_MESSAGE << "We are " << peer_.get_guid() << std::endl; } //////////////////////////////////////////////////////////////////////////////// void Network::connect(std::string const& game_ID) { game_ID_ = game_ID; http_.on_response.connect([&](std::string const& response) { switch (phase_) { // ----------------------------------------------------------------------- case SEARCHING_FOR_OTHER_INSTANCES: { Logger::LOG_MESSAGE << "Got response from master server." << std::endl; bool found_other_game(false); try { boost::property_tree::ptree tree; std::istringstream is(response); boost::property_tree::read_json(is, tree); if (tree.get_child("GET").size() > 0) { host_guid_ = tree.get_child("GET").front().second.get<uint64_t>("guid"); found_other_game = true; } } catch(std::runtime_error const& e) { Logger::LOG_WARNING << "Failed to parse response: " << e.what() << std::endl; } if (found_other_game) enter_phase(CONNECTING_TO_HOST); else enter_phase(STARTING_NEW_INSTANCE); } break; // ----------------------------------------------------------------------- case STARTING_NEW_INSTANCE: Logger::LOG_MESSAGE << "Successfully registered new instance." << std::endl; enter_phase(HOSTING_INSTANCE); break; // ----------------------------------------------------------------------- case HOSTING_INSTANCE: // ignore reply break; // ----------------------------------------------------------------------- default: Logger::LOG_WARNING << "Got unexpected HTTP response." << std::endl; break; } }); upnp_.on_success.connect([&](){ Logger::LOG_MESSAGE << "Successfully opened UPNP." << std::endl; enter_phase(SEARCHING_FOR_OTHER_INSTANCES); }); upnp_.on_fail.connect([&](){ Logger::LOG_MESSAGE << "Failed to open UPNP. Using NAT punch through." << std::endl; enter_phase(SEARCHING_FOR_OTHER_INSTANCES); }); enter_phase(CONNECTING_TO_SERVER); } //////////////////////////////////////////////////////////////////////////////// void Network::update() { http_.update(); if (phase_ == HOSTING_INSTANCE && update_timer_.get_elapsed() > 20.0) { upload_game(); update_timer_.reset(); } for (RakNet::Packet* packet=peer_.peer_->Receive(); packet; peer_.peer_->DeallocatePacket(packet), packet=peer_.peer_->Receive()) { switch (packet->data[0]) { // ##################### BASIC PACKETS ################################### // ----------------------------------------------------------------------- case ID_NEW_INCOMING_CONNECTION: // Logger::LOG_MESSAGE << "Incoming connection from " << packet->guid.ToString() << "." << std::endl; break; // ----------------------------------------------------------------------- case ID_REMOTE_NEW_INCOMING_CONNECTION: // Logger::LOG_MESSAGE << "New remote incoming connection from " << packet->guid.ToString() << "." << std::endl; break; // ----------------------------------------------------------------------- case ID_CONNECTION_REQUEST_ACCEPTED: if (phase_ == CONNECTING_TO_SERVER) { Logger::LOG_MESSAGE << "Connected to NAT server." << std::endl; nat_server_address_ = packet->systemAddress.ToString(); enter_phase(OPENING_UPNP); } else if (phase_ == CONNECTING_TO_HOST) { Logger::LOG_MESSAGE << "Connected to host " << packet->guid.ToString() << ". Sending join request." << std::endl; peer_.request_join(packet->guid.g); } else if (phase_ == HOSTING_INSTANCE) { Logger::LOG_MESSAGE << "Connected to client " << packet->guid.ToString() << "." << std::endl; } break; // ----------------------------------------------------------------------- case ID_DISCONNECTION_NOTIFICATION: Logger::LOG_MESSAGE << packet->guid.ToString() << " disconnected." << std::endl; break; // ################ NAT PUNCH THROUGH PACKETS ############################ // ----------------------------------------------------------------------- case ID_NAT_PUNCHTHROUGH_SUCCEEDED: if (phase_ == CONNECTING_TO_HOST) { Logger::LOG_MESSAGE << "Found route to host. Connecting..." << std::endl; peer_.connect(packet->systemAddress.ToString(false), packet->systemAddress.GetPort()); } break; // ----------------------------------------------------------------------- case ID_NAT_PUNCHTHROUGH_FAILED: Logger::LOG_MESSAGE << "Found no route to host." << std::endl; break; // ----------------------------------------------------------------------- case ID_NAT_RESPOND_BOUND_ADDRESSES: // ignore packet break; // ################## FULLY CONNECTED MESH ############################### // ----------------------------------------------------------------------- case ID_FCM2_NEW_HOST: if (packet->guid.g == peer_.get_guid()) { if (phase_ != HOSTING_INSTANCE) { enter_phase(HOSTING_INSTANCE); } } else { Logger::LOG_MESSAGE << packet->guid.ToString() << " is host now." << std::endl; RakNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(1); RakNet::RakNetGUID old_host; bs.Read(old_host); if (old_host != RakNet::UNASSIGNED_RAKNET_GUID) { Logger::LOG_MESSAGE << "Old host was " << old_host.ToString() << std::endl; } else { Logger::LOG_MESSAGE << "There was no host before." << std::endl; } } break; // ----------------------------------------------------------------------- case (ID_USER_PACKET_ENUM + REQUEST_JOIN): Logger::LOG_MESSAGE << "Got join request from " << packet->guid.ToString() << "." << std::endl; peer_.start_join(packet->guid.g); break; // ----------------------------------------------------------------------- case ID_FCM2_VERIFIED_JOIN_CAPABLE: Logger::LOG_MESSAGE << "ID_FCM2_VERIFIED_JOIN_CAPABLE." << std::endl; peer_.mesh_->RespondOnVerifiedJoinCapable(packet, true, 0); break; // ----------------------------------------------------------------------- case ID_FCM2_VERIFIED_JOIN_ACCEPTED: { DataStructures::List<RakNet::RakNetGUID> accepted_systems; bool this_was_accepted; peer_.mesh_->GetVerifiedJoinAcceptedAdditionalData(packet, &this_was_accepted, accepted_systems, 0); if (this_was_accepted) { Logger::LOG_MESSAGE << "Join accepted." << std::endl; } else { Logger::LOG_MESSAGE << "Peer " << accepted_systems[0].ToString() << " joined the game." << std::endl; } if (this_was_accepted) { enter_phase(PARTICIPATING); } } break; // ----------------------------------------------------------------------- case ID_FCM2_VERIFIED_JOIN_REJECTED: Logger::LOG_MESSAGE << "Join rejected." << std::endl; peer_.peer_->CloseConnection(packet->guid, true); break; // ----------------------------------------------------------------------- case ID_FCM2_VERIFIED_JOIN_FAILED: Logger::LOG_MESSAGE << "Join failed." << std::endl; break; // ----------------------------------------------------------------------- case ID_FCM2_VERIFIED_JOIN_START: enter_phase(CONNECTING_TO_PEERS); peer_.join(packet->guid.g, nat_server_address_); break; // ##################### OTHER PACKETS ################################### // ----------------------------------------------------------------------- default: Logger::LOG_DEBUG << "Got " << RakNet::PacketLogger::BaseIDTOString(packet->data[0]) << " from " << packet->guid.ToString() << std::endl; break; } } } //////////////////////////////////////////////////////////////////////////////// void Network::enter_phase(Phase phase) { phase_ = phase; switch (phase) { // ------------------------------------------------------------------------- case CONNECTING_TO_SERVER: Logger::LOG_MESSAGE << "Connecting to NAT server..." << std::endl; peer_.connect("natpunch.jenkinssoftware.com", 61111); break; // ------------------------------------------------------------------------- case OPENING_UPNP: Logger::LOG_MESSAGE << "Opening UPNP..." << std::endl; upnp_.open(peer_); break; // ------------------------------------------------------------------------- case SEARCHING_FOR_OTHER_INSTANCES: Logger::LOG_MESSAGE << "Downloading running instances from " << "master server..." << std::endl; http_.get("masterserver2.raknet.com/testServer?__gameId=" + game_ID_, "masterserver2.raknet.com", 80); break; // ------------------------------------------------------------------------- case CONNECTING_TO_HOST: Logger::LOG_MESSAGE << "Found running instance. Searching route to host " << host_guid_ << "..." << std::endl; peer_.open_nat(host_guid_, nat_server_address_); break; // ------------------------------------------------------------------------- case STARTING_NEW_INSTANCE: Logger::LOG_MESSAGE << "No running instances found. " << "Starting new instance..." << std::endl; peer_.mesh_->ResetHostCalculation(); upload_game(); update_timer_.reset(); break; // ------------------------------------------------------------------------- case HOSTING_INSTANCE: Logger::LOG_MESSAGE << "We are host now..." << std::endl; upload_game(); update_timer_.reset(); break; // ------------------------------------------------------------------------- case PARTICIPATING: Logger::LOG_MESSAGE << "Participating game..." << std::endl; break; // ------------------------------------------------------------------------- case CONNECTING_TO_PEERS: break; } } //////////////////////////////////////////////////////////////////////////////// void Network::upload_game() { std::stringstream game_descriptor; game_descriptor << "{'__gameId': '" << game_ID_ << "', '__clientReqId': '0', " << "'__rowId': '0', '__timeoutSec': '45', " << "'guid': '" << peer_.peer_->GetMyGUID().ToString() << "' }"; http_.post("masterserver2.raknet.com/testServer", game_descriptor.str(), "masterserver2.raknet.com", 80); } //////////////////////////////////////////////////////////////////////////////// } <commit_msg>did something<commit_after>//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include "Network.hpp" #include <swift2d/utils/Logger.hpp> #include <../../third_party/raknet/src/MessageIdentifiers.h> #include <../../third_party/raknet/src/RakNetTypes.h> #include <../../third_party/raknet/src/RakPeerInterface.h> #include <../../third_party/raknet/src/BitStream.h> #include <../../third_party/raknet/src/FullyConnectedMesh2.h> #include <../../third_party/raknet/src/PacketLogger.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <sstream> namespace swift { //////////////////////////////////////////////////////////////////////////////// Network::Network() : phase_(OPENING_UPNP) { update_timer_.start(); Logger::LOG_MESSAGE << "We are " << peer_.get_guid() << std::endl; } //////////////////////////////////////////////////////////////////////////////// void Network::connect(std::string const& game_ID) { game_ID_ = game_ID; http_.on_response.connect([&](std::string const& response) { switch (phase_) { // ----------------------------------------------------------------------- case SEARCHING_FOR_OTHER_INSTANCES: { Logger::LOG_MESSAGE << "Got response from master server." << std::endl; bool found_other_game(false); try { boost::property_tree::ptree tree; std::istringstream is(response); boost::property_tree::read_json(is, tree); if (tree.get_child("GET").size() > 0) { host_guid_ = tree.get_child("GET").front().second.get<uint64_t>("guid"); found_other_game = true; } } catch(std::runtime_error const& e) { Logger::LOG_WARNING << "Failed to parse response: " << e.what() << std::endl; } if (found_other_game) enter_phase(CONNECTING_TO_HOST); else enter_phase(STARTING_NEW_INSTANCE); } break; // ----------------------------------------------------------------------- case STARTING_NEW_INSTANCE: Logger::LOG_MESSAGE << "Successfully registered new instance." << std::endl; enter_phase(HOSTING_INSTANCE); break; // ----------------------------------------------------------------------- case HOSTING_INSTANCE: // ignore reply break; // ----------------------------------------------------------------------- default: Logger::LOG_WARNING << "Got unexpected HTTP response." << std::endl; break; } }); upnp_.on_success.connect([&](){ Logger::LOG_MESSAGE << "Successfully opened UPNP." << std::endl; enter_phase(SEARCHING_FOR_OTHER_INSTANCES); }); upnp_.on_fail.connect([&](){ Logger::LOG_MESSAGE << "Failed to open UPNP. Using NAT punch through." << std::endl; enter_phase(OPENING_UPNP); }); enter_phase(CONNECTING_TO_SERVER); } //////////////////////////////////////////////////////////////////////////////// void Network::update() { http_.update(); if (phase_ == HOSTING_INSTANCE && update_timer_.get_elapsed() > 20.0) { upload_game(); update_timer_.reset(); } for (RakNet::Packet* packet=peer_.peer_->Receive(); packet; peer_.peer_->DeallocatePacket(packet), packet=peer_.peer_->Receive()) { switch (packet->data[0]) { // ##################### BASIC PACKETS ################################### // ----------------------------------------------------------------------- case ID_NEW_INCOMING_CONNECTION: // Logger::LOG_MESSAGE << "Incoming connection from " << packet->guid.ToString() << "." << std::endl; break; // ----------------------------------------------------------------------- case ID_REMOTE_NEW_INCOMING_CONNECTION: // Logger::LOG_MESSAGE << "New remote incoming connection from " << packet->guid.ToString() << "." << std::endl; break; // ----------------------------------------------------------------------- case ID_CONNECTION_REQUEST_ACCEPTED: if (phase_ == CONNECTING_TO_SERVER) { Logger::LOG_MESSAGE << "Connected to NAT server." << std::endl; nat_server_address_ = packet->systemAddress.ToString(); enter_phase(OPENING_UPNP); } else if (phase_ == CONNECTING_TO_HOST) { Logger::LOG_MESSAGE << "Connected to host " << packet->guid.ToString() << ". Sending join request." << std::endl; peer_.request_join(packet->guid.g); } else if (phase_ == HOSTING_INSTANCE) { Logger::LOG_MESSAGE << "Connected to client " << packet->guid.ToString() << "." << std::endl; } break; // ----------------------------------------------------------------------- case ID_DISCONNECTION_NOTIFICATION: Logger::LOG_MESSAGE << packet->guid.ToString() << " disconnected." << std::endl; break; // ################ NAT PUNCH THROUGH PACKETS ############################ // ----------------------------------------------------------------------- case ID_NAT_PUNCHTHROUGH_SUCCEEDED: if (phase_ == CONNECTING_TO_HOST) { Logger::LOG_MESSAGE << "Found route to host. Connecting..." << std::endl; peer_.connect(packet->systemAddress.ToString(false), packet->systemAddress.GetPort()); } break; // ----------------------------------------------------------------------- case ID_NAT_PUNCHTHROUGH_FAILED: Logger::LOG_MESSAGE << "Found no route to host." << std::endl; break; // ----------------------------------------------------------------------- case ID_NAT_RESPOND_BOUND_ADDRESSES: // ignore packet break; // ################## FULLY CONNECTED MESH ############################### // ----------------------------------------------------------------------- case ID_FCM2_NEW_HOST: if (packet->guid.g == peer_.get_guid()) { if (phase_ != HOSTING_INSTANCE) { enter_phase(HOSTING_INSTANCE); } } else { Logger::LOG_MESSAGE << packet->guid.ToString() << " is host now." << std::endl; RakNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(1); RakNet::RakNetGUID old_host; bs.Read(old_host); if (old_host != RakNet::UNASSIGNED_RAKNET_GUID) { Logger::LOG_MESSAGE << "Old host was " << old_host.ToString() << std::endl; } else { Logger::LOG_MESSAGE << "There was no host before." << std::endl; } } break; // ----------------------------------------------------------------------- case (ID_USER_PACKET_ENUM + REQUEST_JOIN): Logger::LOG_MESSAGE << "Got join request from " << packet->guid.ToString() << "." << std::endl; peer_.start_join(packet->guid.g); break; // ----------------------------------------------------------------------- case ID_FCM2_VERIFIED_JOIN_CAPABLE: Logger::LOG_MESSAGE << "ID_FCM2_VERIFIED_JOIN_CAPABLE." << std::endl; peer_.mesh_->RespondOnVerifiedJoinCapable(packet, true, 0); break; // ----------------------------------------------------------------------- case ID_FCM2_VERIFIED_JOIN_ACCEPTED: { DataStructures::List<RakNet::RakNetGUID> peers; bool this_was_accepted; peer_.mesh_->GetVerifiedJoinAcceptedAdditionalData(packet, &this_was_accepted, peers, 0); if (this_was_accepted) { Logger::LOG_MESSAGE << "Join accepted." << std::endl; } else { Logger::LOG_MESSAGE << "Peer " << peers[0].ToString() << " joined the game." << std::endl; } if (this_was_accepted) { enter_phase(PARTICIPATING); } } break; // ----------------------------------------------------------------------- case ID_FCM2_VERIFIED_JOIN_REJECTED: Logger::LOG_MESSAGE << "Join rejected." << std::endl; peer_.peer_->CloseConnection(packet->guid, true); break; // ----------------------------------------------------------------------- case ID_FCM2_VERIFIED_JOIN_FAILED: Logger::LOG_MESSAGE << "Join failed." << std::endl; break; // ----------------------------------------------------------------------- case ID_FCM2_VERIFIED_JOIN_START: enter_phase(CONNECTING_TO_PEERS); peer_.join(packet->guid.g, nat_server_address_); break; // ##################### OTHER PACKETS ################################### // ----------------------------------------------------------------------- default: Logger::LOG_DEBUG << "Got " << RakNet::PacketLogger::BaseIDTOString(packet->data[0]) << " from " << packet->guid.ToString() << std::endl; break; } } } //////////////////////////////////////////////////////////////////////////////// void Network::enter_phase(Phase phase) { phase_ = phase; switch (phase) { // ------------------------------------------------------------------------- case CONNECTING_TO_SERVER: Logger::LOG_MESSAGE << "Connecting to NAT server..." << std::endl; peer_.connect("natpunch.jenkinssoftware.com", 61111); break; // ------------------------------------------------------------------------- case OPENING_UPNP: Logger::LOG_MESSAGE << "Opening UPNP..." << std::endl; upnp_.open(peer_); break; // ------------------------------------------------------------------------- case SEARCHING_FOR_OTHER_INSTANCES: Logger::LOG_MESSAGE << "Downloading running instances from " << "master server..." << std::endl; http_.get("masterserver2.raknet.com/testServer?__gameId=" + game_ID_, "masterserver2.raknet.com", 80); break; // ------------------------------------------------------------------------- case CONNECTING_TO_HOST: Logger::LOG_MESSAGE << "Found running instance. Searching route to host " << host_guid_ << "..." << std::endl; peer_.open_nat(host_guid_, nat_server_address_); break; // ------------------------------------------------------------------------- case STARTING_NEW_INSTANCE: Logger::LOG_MESSAGE << "No running instances found. " << "Starting new instance..." << std::endl; peer_.mesh_->ResetHostCalculation(); upload_game(); update_timer_.reset(); break; // ------------------------------------------------------------------------- case HOSTING_INSTANCE: Logger::LOG_MESSAGE << "We are host now." << std::endl; upload_game(); update_timer_.reset(); break; // ------------------------------------------------------------------------- case PARTICIPATING: Logger::LOG_MESSAGE << "Participating game." << std::endl; break; } } //////////////////////////////////////////////////////////////////////////////// void Network::upload_game() { std::stringstream game_descriptor; game_descriptor << "{'__gameId': '" << game_ID_ << "', '__clientReqId': '0', " << "'__rowId': '0', '__timeoutSec': '45', " << "'guid': '" << peer_.peer_->GetMyGUID().ToString() << "' }"; http_.post("masterserver2.raknet.com/testServer", game_descriptor.str(), "masterserver2.raknet.com", 80); } //////////////////////////////////////////////////////////////////////////////// } <|endoftext|>
<commit_before>/* * Copyright (c) 2020 SUSE LLC * * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License 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, contact Novell, Inc. * * To contact Novell about this file by physical or electronic mail, you may * find current contact information at www.novell.com. */ #include "storage/Holders/BtrfsQgroupRelationImpl.h" #include "storage/Filesystems/BtrfsImpl.h" #include "storage/Filesystems/BtrfsQgroupImpl.h" #include "storage/Filesystems/BtrfsSubvolumeImpl.h" #include "storage/Utils/XmlFile.h" #include "storage/Utils/Format.h" #include "storage/Action.h" #include "storage/Utils/StorageDefines.h" #include "storage/Utils/SystemCmd.h" #include "storage/Utils/StorageTmpl.h" namespace storage { const char* HolderTraits<BtrfsQgroupRelation>::classname = "BtrfsQgroupRelation"; BtrfsQgroupRelation::Impl::Impl(const xmlNode* node) : Holder::Impl(node) { } void BtrfsQgroupRelation::Impl::save(xmlNode* node) const { Holder::Impl::save(node); } bool BtrfsQgroupRelation::Impl::is_in_view(View view) const { switch (view) { case View::ALL: return true; case View::CLASSIC: return false; case View::REMOVE: { const Device* device = get_source(); return is_btrfs(device); } } ST_THROW(LogicException("invalid value for view")); } const Btrfs* BtrfsQgroupRelation::Impl::get_btrfs() const { return to_btrfs_qgroup(get_target())->get_btrfs(); } void BtrfsQgroupRelation::Impl::add_create_actions(Actiongraph::Impl& actiongraph) const { // Only btrfs qgroup relations between btrfs qgroups must be created in the // system. Relations from a btrfs or from a subvolume do not exists in the system. vector<Action::Base*> actions; if (is_btrfs_qgroup(get_source()) && is_btrfs_qgroup(get_target())) actions.push_back(new Action::Create(make_pair(get_source_sid(), get_target_sid()))); actiongraph.add_chain(actions); } void BtrfsQgroupRelation::Impl::add_delete_actions(Actiongraph::Impl& actiongraph) const { if (contains(actiongraph.btrfs_qgroup_delete_is_nop, get_btrfs()->get_sid())) return; // See above. vector<Action::Base*> actions; if (is_btrfs_qgroup(get_source()) && is_btrfs_qgroup(get_target())) actions.push_back(new Action::Delete(make_pair(get_source_sid(), get_target_sid()))); actiongraph.add_chain(actions); } void BtrfsQgroupRelation::Impl::add_dependencies(Actiongraph::Impl::vertex_descriptor vertex1, Actiongraph::Impl& actiongraph) const { // qgroup relations must be created after the qgroups have been created. Inverse // order for delete. This is likely so generic that it could be move to Holder. const Action::Base* action1 = actiongraph[vertex1]; if (is_create(action1)) { for (Actiongraph::Impl::vertex_descriptor vertex2 : actiongraph.actions_with_sid(get_source_sid(), ONLY_LAST)) actiongraph.add_edge(vertex2, vertex1); for (Actiongraph::Impl::vertex_descriptor vertex2 : actiongraph.actions_with_sid(get_target_sid(), ONLY_LAST)) actiongraph.add_edge(vertex2, vertex1); } if (is_delete(action1)) { for (Actiongraph::Impl::vertex_descriptor vertex2 : actiongraph.actions_with_sid(get_source_sid(), ONLY_FIRST)) actiongraph.add_edge(vertex1, vertex2); for (Actiongraph::Impl::vertex_descriptor vertex2 : actiongraph.actions_with_sid(get_target_sid(), ONLY_FIRST)) actiongraph.add_edge(vertex1, vertex2); } } bool BtrfsQgroupRelation::Impl::equal(const Holder::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); return Holder::Impl::equal(rhs); } void BtrfsQgroupRelation::Impl::log_diff(std::ostream& log, const Holder::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); Holder::Impl::log_diff(log, rhs); } void BtrfsQgroupRelation::Impl::print(std::ostream& out) const { Holder::Impl::print(out); } Text BtrfsQgroupRelation::Impl::do_create_text(Tense tense) const { const BtrfsQgroup* qgroup1 = to_btrfs_qgroup(get_source()); const BtrfsQgroup* qgroup2 = to_btrfs_qgroup(get_target()); const Btrfs* btrfs = qgroup1->get_btrfs(); if (qgroup1->get_id().first == 0 && qgroup1->get_id().second != BtrfsSubvolume::Impl::top_level_id && qgroup1->get_impl().has_btrfs_subvolume()) { const BtrfsSubvolume* btrfs_subvolume = qgroup1->get_impl().get_btrfs_subvolume(); Text text = tenser(tense, // TRANSLATORS: displayed before action, // %1$s is replaced by subvolume path (e.g. var/log), // %2$s is replaced by the btrfs qgroup id (e.g. 1/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Assign qgroup of subvolume %1$s to qgroup %2$s on %3$s"), // TRANSLATORS: displayed during action, // %1$s is replaced by subvolume path (e.g. var/log), // %2$s is replaced by the btrfs qgroup id (e.g. 1/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Assigning qgroup of subvolume %1$s to qgroup %2$s on %3$s")); return sformat(text, btrfs_subvolume->get_path(), BtrfsQgroup::Impl::format_id(qgroup2->get_id()), btrfs->get_impl().get_message_name()); } else { Text text = tenser(tense, // TRANSLATORS: displayed before action, // %1$s is replaced by the btrfs qgroup id (e.g. 1/0), // %2$s is replaced by the btrfs qgroup id (e.g. 2/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Assign qgroup %1$s to qgroup %2$s on %3$s"), // TRANSLATORS: displayed during action, // %1$s is replaced by the btrfs qgroup id (e.g. 1/0), // %2$s is replaced by the btrfs qgroup id (e.g. 2/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Assigning qgroup %1$s to qgroup %2$s on %3$s")); return sformat(text, BtrfsQgroup::Impl::format_id(qgroup1->get_id()), BtrfsQgroup::Impl::format_id(qgroup2->get_id()), btrfs->get_impl().get_message_name()); } } void BtrfsQgroupRelation::Impl::do_create() { const BtrfsQgroup* qgroup1 = to_btrfs_qgroup(get_source()); const BtrfsQgroup* qgroup2 = to_btrfs_qgroup(get_target()); const Btrfs* btrfs = qgroup1->get_btrfs(); EnsureMounted ensure_mounted(btrfs->get_top_level_btrfs_subvolume(), false); string cmd_line = BTRFS_BIN " qgroup assign " + BtrfsQgroup::Impl::format_id(qgroup1->get_id()) + " " + BtrfsQgroup::Impl::format_id(qgroup2->get_id()) + " " + quote(ensure_mounted.get_any_mount_point()); SystemCmd cmd(cmd_line, SystemCmd::DoThrow); } Text BtrfsQgroupRelation::Impl::do_delete_text(Tense tense) const { const BtrfsQgroup* qgroup1 = to_btrfs_qgroup(get_source()); const BtrfsQgroup* qgroup2 = to_btrfs_qgroup(get_target()); const Btrfs* btrfs = qgroup1->get_btrfs(); if (qgroup1->get_id().first == 0 && qgroup1->get_id().second != BtrfsSubvolume::Impl::top_level_id && qgroup1->get_impl().has_btrfs_subvolume()) { const BtrfsSubvolume* btrfs_subvolume = qgroup1->get_impl().get_btrfs_subvolume(); Text text = tenser(tense, // TRANSLATORS: displayed before action, // %1$s is replaced by subvolume path (e.g. var/log), // %2$s is replaced by the btrfs qgroup id (e.g. 1/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Unassign qgroup of subvolume %1$s from qgroup %2$s on %3$s"), // TRANSLATORS: displayed during action, // %1$s is replaced by subvolume path (e.g. var/log), // %2$s is replaced by the btrfs qgroup id (e.g. 1/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Unassigning qgroup of subvolume %1$s from qgroup %2$s on %3$s")); return sformat(text, btrfs_subvolume->get_path(), BtrfsQgroup::Impl::format_id(qgroup2->get_id()), btrfs->get_impl().get_message_name()); } else { Text text = tenser(tense, // TRANSLATORS: displayed before action, // %1$s is replaced by the btrfs qgroup id (e.g. 1/0), // %2$s is replaced by the btrfs qgroup id (e.g. 2/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Unassign qgroup %1$s from qgroup %2$s on %3$s"), // TRANSLATORS: displayed during action, // %1$s is replaced by the btrfs qgroup id (e.g. 1/0), // %2$s is replaced by the btrfs qgroup id (e.g. 2/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Unassigning qgroup %1$s from qgroup %2$s on %3$s")); return sformat(text, BtrfsQgroup::Impl::format_id(qgroup1->get_id()), BtrfsQgroup::Impl::format_id(qgroup2->get_id()), btrfs->get_impl().get_message_name()); } } void BtrfsQgroupRelation::Impl::do_delete() const { const BtrfsQgroup* qgroup1 = to_btrfs_qgroup(get_source()); const BtrfsQgroup* qgroup2 = to_btrfs_qgroup(get_target()); const Btrfs* btrfs = qgroup1->get_btrfs(); EnsureMounted ensure_mounted(btrfs->get_top_level_btrfs_subvolume(), false); string cmd_line = BTRFS_BIN " qgroup remove " + BtrfsQgroup::Impl::format_id(qgroup1->get_id()) + " " + BtrfsQgroup::Impl::format_id(qgroup2->get_id()) + " " + quote(ensure_mounted.get_any_mount_point()); SystemCmd cmd(cmd_line, SystemCmd::DoThrow); } } <commit_msg>- add more btrfs qgroups to remove view (bsc#1179590)<commit_after>/* * Copyright (c) 2020 SUSE LLC * * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License 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, contact Novell, Inc. * * To contact Novell about this file by physical or electronic mail, you may * find current contact information at www.novell.com. */ #include "storage/Holders/BtrfsQgroupRelationImpl.h" #include "storage/Filesystems/BtrfsImpl.h" #include "storage/Filesystems/BtrfsQgroupImpl.h" #include "storage/Filesystems/BtrfsSubvolumeImpl.h" #include "storage/Utils/XmlFile.h" #include "storage/Utils/Format.h" #include "storage/Action.h" #include "storage/Utils/StorageDefines.h" #include "storage/Utils/SystemCmd.h" #include "storage/Utils/StorageTmpl.h" namespace storage { const char* HolderTraits<BtrfsQgroupRelation>::classname = "BtrfsQgroupRelation"; BtrfsQgroupRelation::Impl::Impl(const xmlNode* node) : Holder::Impl(node) { } void BtrfsQgroupRelation::Impl::save(xmlNode* node) const { Holder::Impl::save(node); } bool BtrfsQgroupRelation::Impl::is_in_view(View view) const { switch (view) { case View::ALL: return true; case View::CLASSIC: return false; case View::REMOVE: { // Follow the relation if the btrfs is removed. const Device* source = get_source(); if (is_btrfs(source)) return true; // Follow the relation if the qgroup was created along with the btrfs // subvolume - in which case the id is 0/0. See bsc #1179590. const BtrfsQgroup* target = to_btrfs_qgroup(get_target()); if (target->get_id() == BtrfsQgroup::Impl::unknown_id) return true; return false; } } ST_THROW(LogicException("invalid value for view")); } const Btrfs* BtrfsQgroupRelation::Impl::get_btrfs() const { return to_btrfs_qgroup(get_target())->get_btrfs(); } void BtrfsQgroupRelation::Impl::add_create_actions(Actiongraph::Impl& actiongraph) const { // Only btrfs qgroup relations between btrfs qgroups must be created in the // system. Relations from a btrfs or from a subvolume do not exists in the system. vector<Action::Base*> actions; if (is_btrfs_qgroup(get_source()) && is_btrfs_qgroup(get_target())) actions.push_back(new Action::Create(make_pair(get_source_sid(), get_target_sid()))); actiongraph.add_chain(actions); } void BtrfsQgroupRelation::Impl::add_delete_actions(Actiongraph::Impl& actiongraph) const { if (contains(actiongraph.btrfs_qgroup_delete_is_nop, get_btrfs()->get_sid())) return; // See above. vector<Action::Base*> actions; if (is_btrfs_qgroup(get_source()) && is_btrfs_qgroup(get_target())) actions.push_back(new Action::Delete(make_pair(get_source_sid(), get_target_sid()))); actiongraph.add_chain(actions); } void BtrfsQgroupRelation::Impl::add_dependencies(Actiongraph::Impl::vertex_descriptor vertex1, Actiongraph::Impl& actiongraph) const { // qgroup relations must be created after the qgroups have been created. Inverse // order for delete. This is likely so generic that it could be move to Holder. const Action::Base* action1 = actiongraph[vertex1]; if (is_create(action1)) { for (Actiongraph::Impl::vertex_descriptor vertex2 : actiongraph.actions_with_sid(get_source_sid(), ONLY_LAST)) actiongraph.add_edge(vertex2, vertex1); for (Actiongraph::Impl::vertex_descriptor vertex2 : actiongraph.actions_with_sid(get_target_sid(), ONLY_LAST)) actiongraph.add_edge(vertex2, vertex1); } if (is_delete(action1)) { for (Actiongraph::Impl::vertex_descriptor vertex2 : actiongraph.actions_with_sid(get_source_sid(), ONLY_FIRST)) actiongraph.add_edge(vertex1, vertex2); for (Actiongraph::Impl::vertex_descriptor vertex2 : actiongraph.actions_with_sid(get_target_sid(), ONLY_FIRST)) actiongraph.add_edge(vertex1, vertex2); } } bool BtrfsQgroupRelation::Impl::equal(const Holder::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); return Holder::Impl::equal(rhs); } void BtrfsQgroupRelation::Impl::log_diff(std::ostream& log, const Holder::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); Holder::Impl::log_diff(log, rhs); } void BtrfsQgroupRelation::Impl::print(std::ostream& out) const { Holder::Impl::print(out); } Text BtrfsQgroupRelation::Impl::do_create_text(Tense tense) const { const BtrfsQgroup* qgroup1 = to_btrfs_qgroup(get_source()); const BtrfsQgroup* qgroup2 = to_btrfs_qgroup(get_target()); const Btrfs* btrfs = qgroup1->get_btrfs(); if (qgroup1->get_id().first == 0 && qgroup1->get_id().second != BtrfsSubvolume::Impl::top_level_id && qgroup1->get_impl().has_btrfs_subvolume()) { const BtrfsSubvolume* btrfs_subvolume = qgroup1->get_impl().get_btrfs_subvolume(); Text text = tenser(tense, // TRANSLATORS: displayed before action, // %1$s is replaced by subvolume path (e.g. var/log), // %2$s is replaced by the btrfs qgroup id (e.g. 1/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Assign qgroup of subvolume %1$s to qgroup %2$s on %3$s"), // TRANSLATORS: displayed during action, // %1$s is replaced by subvolume path (e.g. var/log), // %2$s is replaced by the btrfs qgroup id (e.g. 1/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Assigning qgroup of subvolume %1$s to qgroup %2$s on %3$s")); return sformat(text, btrfs_subvolume->get_path(), BtrfsQgroup::Impl::format_id(qgroup2->get_id()), btrfs->get_impl().get_message_name()); } else { Text text = tenser(tense, // TRANSLATORS: displayed before action, // %1$s is replaced by the btrfs qgroup id (e.g. 1/0), // %2$s is replaced by the btrfs qgroup id (e.g. 2/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Assign qgroup %1$s to qgroup %2$s on %3$s"), // TRANSLATORS: displayed during action, // %1$s is replaced by the btrfs qgroup id (e.g. 1/0), // %2$s is replaced by the btrfs qgroup id (e.g. 2/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Assigning qgroup %1$s to qgroup %2$s on %3$s")); return sformat(text, BtrfsQgroup::Impl::format_id(qgroup1->get_id()), BtrfsQgroup::Impl::format_id(qgroup2->get_id()), btrfs->get_impl().get_message_name()); } } void BtrfsQgroupRelation::Impl::do_create() { const BtrfsQgroup* qgroup1 = to_btrfs_qgroup(get_source()); const BtrfsQgroup* qgroup2 = to_btrfs_qgroup(get_target()); const Btrfs* btrfs = qgroup1->get_btrfs(); EnsureMounted ensure_mounted(btrfs->get_top_level_btrfs_subvolume(), false); string cmd_line = BTRFS_BIN " qgroup assign " + BtrfsQgroup::Impl::format_id(qgroup1->get_id()) + " " + BtrfsQgroup::Impl::format_id(qgroup2->get_id()) + " " + quote(ensure_mounted.get_any_mount_point()); SystemCmd cmd(cmd_line, SystemCmd::DoThrow); } Text BtrfsQgroupRelation::Impl::do_delete_text(Tense tense) const { const BtrfsQgroup* qgroup1 = to_btrfs_qgroup(get_source()); const BtrfsQgroup* qgroup2 = to_btrfs_qgroup(get_target()); const Btrfs* btrfs = qgroup1->get_btrfs(); if (qgroup1->get_id().first == 0 && qgroup1->get_id().second != BtrfsSubvolume::Impl::top_level_id && qgroup1->get_impl().has_btrfs_subvolume()) { const BtrfsSubvolume* btrfs_subvolume = qgroup1->get_impl().get_btrfs_subvolume(); Text text = tenser(tense, // TRANSLATORS: displayed before action, // %1$s is replaced by subvolume path (e.g. var/log), // %2$s is replaced by the btrfs qgroup id (e.g. 1/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Unassign qgroup of subvolume %1$s from qgroup %2$s on %3$s"), // TRANSLATORS: displayed during action, // %1$s is replaced by subvolume path (e.g. var/log), // %2$s is replaced by the btrfs qgroup id (e.g. 1/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Unassigning qgroup of subvolume %1$s from qgroup %2$s on %3$s")); return sformat(text, btrfs_subvolume->get_path(), BtrfsQgroup::Impl::format_id(qgroup2->get_id()), btrfs->get_impl().get_message_name()); } else { Text text = tenser(tense, // TRANSLATORS: displayed before action, // %1$s is replaced by the btrfs qgroup id (e.g. 1/0), // %2$s is replaced by the btrfs qgroup id (e.g. 2/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Unassign qgroup %1$s from qgroup %2$s on %3$s"), // TRANSLATORS: displayed during action, // %1$s is replaced by the btrfs qgroup id (e.g. 1/0), // %2$s is replaced by the btrfs qgroup id (e.g. 2/0), // %3$s is replaced by one or more devices (e.g /dev/sda1 (2.00 GiB) // and /dev/sdb2 (2.00 GiB)) _("Unassigning qgroup %1$s from qgroup %2$s on %3$s")); return sformat(text, BtrfsQgroup::Impl::format_id(qgroup1->get_id()), BtrfsQgroup::Impl::format_id(qgroup2->get_id()), btrfs->get_impl().get_message_name()); } } void BtrfsQgroupRelation::Impl::do_delete() const { const BtrfsQgroup* qgroup1 = to_btrfs_qgroup(get_source()); const BtrfsQgroup* qgroup2 = to_btrfs_qgroup(get_target()); const Btrfs* btrfs = qgroup1->get_btrfs(); EnsureMounted ensure_mounted(btrfs->get_top_level_btrfs_subvolume(), false); string cmd_line = BTRFS_BIN " qgroup remove " + BtrfsQgroup::Impl::format_id(qgroup1->get_id()) + " " + BtrfsQgroup::Impl::format_id(qgroup2->get_id()) + " " + quote(ensure_mounted.get_any_mount_point()); SystemCmd cmd(cmd_line, SystemCmd::DoThrow); } } <|endoftext|>
<commit_before>/* Copyright (C) 2003 Justin Karneges Copyright (C) 2005 Brad Hards <[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 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 <QtCore> #include <QtCrypto> #include <iostream> static void dumpCertificateInfo( QCA::CertificateInfo subject) { std::cout << " Common Name: " << std::endl; QList<QString> commonNameList = subject.values(QCA::CommonName); QString commonName; foreach( commonName, commonNameList ) { std::cout << " " << qPrintable(commonName) << std::endl; } std::cout << " Organization: " << std::endl; QList<QString> orgInfo = subject.values(QCA::Organization); QString organization; foreach( organization, orgInfo ) { std::cout << " " << qPrintable(organization) << std::endl; } std::cout << " Country: " << std::endl; QList<QString> countryList = subject.values(QCA::Country); QString country; foreach( country, countryList ) { std::cout << " " << qPrintable(country) << std::endl; } } static void dumpSubjectInfo( QCA::CertificateInfo subject) { std::cout << "Subject: " << std::endl; dumpCertificateInfo( subject ); } static void dumpIssuerInfo( QCA::CertificateInfo subject) { std::cout << "Issuer: " << std::endl; dumpCertificateInfo( subject ); } int main(int argc, char** argv) { // the Initializer object sets things up, and // also does cleanup when it goes out of scope QCA::Initializer init; QCoreApplication app(argc, argv); if ( !QCA::isSupported( "cert" ) ) { std::cout << "Sorry, no PKI certificate support" << std::endl; return 1; } QList<QCA::Certificate> certlist; if (argc >= 2) { std::cout << "Reading certificates from : " << argv[1] << std::endl; QCA::CertificateCollection filecerts; QCA::ConvertResult importResult; filecerts = QCA::CertificateCollection::fromFlatTextFile( argv[1], &importResult ); if ( QCA::ConvertGood == importResult) { std::cout << "Import succeeded" << std::endl; certlist = filecerts.certificates(); } } else { if ( !QCA::haveSystemStore() ) { std::cout << "System certificates not available" << std::endl; return 2; } QCA::CertificateCollection systemcerts = QCA::systemStore(); certlist = systemcerts.certificates(); } std::cout << "Cert size: " << certlist.count() << std::endl; QCA::Certificate cert; foreach (cert, certlist) { std::cout << "Serial Number:"; std::cout << qPrintable(cert.serialNumber().toString()) << std::endl; dumpSubjectInfo( cert.subjectInfo() ); dumpIssuerInfo( cert.issuerInfo() ); if ( cert.isCA() ) { std::cout << "Is certificate authority" << std::endl; } else { std::cout << "Is not a certificate authority" << std::endl; } if (cert.isSelfSigned() ) { std::cout << "Self signed" << std::endl; } else { std::cout << "Is not self-signed!!!" << std::endl; } std::cout << "Valid from " << qPrintable(cert.notValidBefore().toString()); std::cout << ", until " << qPrintable(cert.notValidAfter().toString()); //std::cout << std::endl; //std::cout << "PEM:" << std::endl; //std::cout << qPrintable(cert.toPEM()); std::cout << std::endl << std::endl; } return 0; } <commit_msg>Add better explaination of the various elements of this example.<commit_after>/* Copyright (C) 2003 Justin Karneges Copyright (C) 2005 Brad Hards <[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 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 <QtCore> #include <QtCrypto> #include <iostream> // dump out information about some part of the certificate // we use this same approach for information about the subject // of the certificate, and also about the issuer of the certificate static void dumpCertificateInfo( QCA::CertificateInfo info) { std::cout << " Organization: " << std::endl; // Note that a single certificate can apply to more than one // organisation. QCA::Certificate is a multimap, so when you // ask for the values associated with a parameter, it returns // a list. QList<QString> orgInfoList = info.values(QCA::Organization); // foreach() interates over each value in the list, and we dump // out each value. Note that is uncommon for a certificate to // actually contain multiple values for a single parameter. QString organization; foreach( organization, orgInfoList ) { std::cout << " " << qPrintable(organization) << std::endl; } std::cout << " Country: " << std::endl; // As above, however this shows a more compact way to represent // the iteration and output. foreach( QString country, info.values(QCA::Country) ) { std::cout << " " << qPrintable(country) << std::endl; } } // This is just a convenience routine static void dumpSubjectInfo( QCA::CertificateInfo subject) { std::cout << "Subject: " << std::endl; dumpCertificateInfo( subject ); } // This is just a convenience routine static void dumpIssuerInfo( QCA::CertificateInfo issuer) { std::cout << "Issuer: " << std::endl; dumpCertificateInfo( issuer ); } int main(int argc, char** argv) { // the Initializer object sets things up, and // also does cleanup when it goes out of scope QCA::Initializer init; QCoreApplication app(argc, argv); // We need to ensure that we have certificate handling support if ( !QCA::isSupported( "cert" ) ) { std::cout << "Sorry, no PKI certificate support" << std::endl; return 1; } // We are going to work with a number of certificates, and a // QList is a great template class for that QList<QCA::Certificate> certlist; // We do two different cases - if we provide an argument, it is taken // as a filename to read the keys from. If there is no argument, we just // read from the system store certificates. if (argc >= 2) { // we are going to read the certificates in using a single call // which requires a CertificateCollection. QCA::CertificateCollection filecerts; // The conversion can be tested (although you don't have to) to find out if it // worked. QCA::ConvertResult importResult; // This imports all the PEM encoded certificates from the file specified as the argument // Note that you pass in a pointer to the result argument. filecerts = QCA::CertificateCollection::fromFlatTextFile( argv[1], &importResult ); if ( QCA::ConvertGood == importResult) { std::cout << "Import succeeded" << std::endl; // this turns the CertificateCollection into a QList of Certificate objects certlist = filecerts.certificates(); } } else { // we have no arguments, so just use the system certificates if ( !QCA::haveSystemStore() ) { std::cout << "System certificates not available" << std::endl; return 2; } // Similar to above, except we just want the system certificates QCA::CertificateCollection systemcerts = QCA::systemStore(); // this turns the CertificateCollection into a QList of Certificate objects certlist = systemcerts.certificates(); } std::cout << "Number of certificates: " << certlist.count() << std::endl; QCA::Certificate cert; foreach (cert, certlist) { std::cout << "Serial Number:"; // the serial number of the certificate is a QBigInteger, but we can // just convert it to a string, and then output it. std::cout << qPrintable(cert.serialNumber().toString()) << std::endl; // The subject information shows properties of who the certificate // applies to. See the convenience routines above. dumpSubjectInfo( cert.subjectInfo() ); // The issuer information shows properties of who the certificate // was signed by. See the convenience routines above. dumpIssuerInfo( cert.issuerInfo() ); // Test if the certificate can be used as a certificate authority if ( cert.isCA() ) { std::cout << "Is certificate authority" << std::endl; } else { std::cout << "Is not a certificate authority" << std::endl; } // Test if the certificate is self-signed. if (cert.isSelfSigned() ) { std::cout << "Self signed" << std::endl; } else { std::cout << "Is not self-signed!!!" << std::endl; } // Certificate are only valid between specific dates. We can get the dates // (as a QDateTime) using a couple of calls std::cout << "Valid from " << qPrintable(cert.notValidBefore().toString()); std::cout << ", until " << qPrintable(cert.notValidAfter().toString()); std::cout << std::endl; // You can get the certificate in PEM encoding with a simple toPEM() call std::cout << "PEM:" << std::endl; std::cout << qPrintable(cert.toPEM()); std::cout << std::endl << std::endl; } return 0; } <|endoftext|>
<commit_before>#pragma once #include <fc/reflect/variant.hpp> #include <stdexcept> namespace eosio { namespace chain { enum class backing_store_type { NATIVE, // A name for regular users. Uses Chainbase. ROCKSDB }; }} // namespace eosio::chain namespace fc { template <> inline void to_variant(const eosio::chain::backing_store_type& store, fc::variant& v) { switch (store) { case eosio::chain::backing_store_type::NATIVE: v = "NATIVE"; break; case eosio::chain::backing_store_type::ROCKSDB: v = "ROCKSDB"; } } template <> inline void from_variant(const fc::variant& v, eosio::chain::backing_store_type& store) { const std::string& val = v.as_string(); if (val == "NATIVE") { store = eosio::chain::backing_store_type::NATIVE; } else if (val == "ROCKSDB") { store = eosio::chain::backing_store_type::ROCKSDB; } else { throw std::runtime_error("Invalid backing store name: " + val); } } } // namespace fc <commit_msg>Serialize kv_db_config_object.backing_store as int<commit_after>#pragma once #include <fc/reflect/variant.hpp> #include <stdexcept> namespace eosio { namespace chain { enum class backing_store_type { NATIVE, // A name for regular users. Uses Chainbase. ROCKSDB }; }} // namespace eosio::chain namespace fc { template <> inline void to_variant(const eosio::chain::backing_store_type& store, fc::variant& v) { v = (uint64_t)store; } template <> inline void from_variant(const fc::variant& v, eosio::chain::backing_store_type& store) { switch (store = (eosio::chain::backing_store_type)v.as_uint64()) { case eosio::chain::backing_store_type::NATIVE: /* FALL THROUGH */ case eosio::chain::backing_store_type::ROCKSDB: return; } throw std::runtime_error("Invalid backing store name: " + v.as_string()); } } // namespace fc <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/test/chrome_frame_automation_mock.h" #include "chrome_frame/test/chrome_frame_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" const int kLongWaitTimeout = 25 * 1000; // Note that this test fails occasionally. Disabling it altogether (rather than // marking as flaky to see if the failure cascades down to the next test. // http://crbug.com/81479 TEST(ChromeFrame, DISABLED_Launch) { MessageLoopForUI loop; AutomationMockLaunch mock_launch(&loop, kLongWaitTimeout); loop.PostDelayedTask(FROM_HERE, MessageLoop::QuitClosure(), kLongWaitTimeout); mock_launch.Navigate("about:blank"); loop.RunWithDispatcher(NULL); EXPECT_TRUE(mock_launch.launch_result()); } TEST(ChromeFrame, Navigate) { MessageLoopForUI loop; AutomationMockNavigate mock_navigate(&loop, kLongWaitTimeout); loop.PostDelayedTask(FROM_HERE, MessageLoop::QuitClosure(), kLongWaitTimeout); mock_navigate.NavigateRelativeFile(L"postmessage_basic_frame.html"); loop.RunWithDispatcher(NULL); EXPECT_FALSE(mock_navigate.navigation_result()); } TEST(ChromeFrame, PostMessage) { MessageLoopForUI loop; AutomationMockPostMessage mock_postmessage(&loop, kLongWaitTimeout); loop.PostDelayedTask(FROM_HERE, MessageLoop::QuitClosure(), kLongWaitTimeout); mock_postmessage.NavigateRelativeFile(L"postmessage_basic_frame.html"); loop.RunWithDispatcher(NULL); EXPECT_FALSE(mock_postmessage.postmessage_result()); } TEST(ChromeFrame, RequestStart) { MessageLoopForUI loop; AutomationMockHostNetworkRequestStart mock_request_start(&loop, kLongWaitTimeout); loop.PostDelayedTask(FROM_HERE, MessageLoop::QuitClosure(), kLongWaitTimeout); mock_request_start.NavigateRelative(L"postmessage_basic_frame.html"); loop.RunWithDispatcher(NULL); EXPECT_TRUE(mock_request_start.request_start_result()); } <commit_msg>Revert "Disabling ChromeFrame.Launch" (r124964)<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/test/chrome_frame_automation_mock.h" #include "chrome_frame/test/chrome_frame_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" const int kLongWaitTimeout = 25 * 1000; TEST(ChromeFrame, Launch) { MessageLoopForUI loop; AutomationMockLaunch mock_launch(&loop, kLongWaitTimeout); loop.PostDelayedTask(FROM_HERE, MessageLoop::QuitClosure(), kLongWaitTimeout); mock_launch.Navigate("about:blank"); loop.RunWithDispatcher(NULL); EXPECT_TRUE(mock_launch.launch_result()); } TEST(ChromeFrame, Navigate) { MessageLoopForUI loop; AutomationMockNavigate mock_navigate(&loop, kLongWaitTimeout); loop.PostDelayedTask(FROM_HERE, MessageLoop::QuitClosure(), kLongWaitTimeout); mock_navigate.NavigateRelativeFile(L"postmessage_basic_frame.html"); loop.RunWithDispatcher(NULL); EXPECT_FALSE(mock_navigate.navigation_result()); } TEST(ChromeFrame, PostMessage) { MessageLoopForUI loop; AutomationMockPostMessage mock_postmessage(&loop, kLongWaitTimeout); loop.PostDelayedTask(FROM_HERE, MessageLoop::QuitClosure(), kLongWaitTimeout); mock_postmessage.NavigateRelativeFile(L"postmessage_basic_frame.html"); loop.RunWithDispatcher(NULL); EXPECT_FALSE(mock_postmessage.postmessage_result()); } TEST(ChromeFrame, RequestStart) { MessageLoopForUI loop; AutomationMockHostNetworkRequestStart mock_request_start(&loop, kLongWaitTimeout); loop.PostDelayedTask(FROM_HERE, MessageLoop::QuitClosure(), kLongWaitTimeout); mock_request_start.NavigateRelative(L"postmessage_basic_frame.html"); loop.RunWithDispatcher(NULL); EXPECT_TRUE(mock_request_start.request_start_result()); } <|endoftext|>
<commit_before>#include "ofApp.h" ofVec3f getNormal(const ofVec3f& v1, const ofVec3f& v2, const ofVec3f& v3) { ofVec3f a = v1 - v2; ofVec3f b = v3 - v2; ofVec3f normal = b.cross(a); normal.normalize(); return normal; } void buildNormals(ofMesh& mesh) { vector<ofVec3f>& vertices = mesh.getVertices(); mesh.clearNormals(); for(int i = 0; i < mesh.getNumVertices(); i += 3) { ofVec3f normal = getNormal(mesh.getVertices()[i+0], mesh.getVertices()[i+1], mesh.getVertices()[i+2]); for(int j = 0; j < 3; j++) { mesh.addNormal(normal); } } } ofMesh loadObj(string filename) { ofMesh m; vector<ofVec3f> v; vector<ofVec2f> vt; ofFile f(filename); while(!f.eof()) { string c; f >> c; if(c.size()) { if(c == "v") { float x, y, z; f >> x >> y >> z; v.push_back(ofVec3f(x, y, z)); } else if(c == "vt") { float u, v; f >> u >> v; vt.push_back(ofVec2f(u, v)); } else if(c == "f") { string l; getline(f, l); replace(l.begin(), l.end(), '/', ' '); istringstream ls(l); int vi1, vti1, vi2, vti2, vi3, vti3; ls >> vi1 >> vti1 >> vi2 >> vti2 >> vi3 >> vti3; m.addVertex(v[vi1-1]); m.addVertex(v[vi2-1]); m.addVertex(v[vi3-1]); m.addTexCoord(vt[vti1-1]); m.addTexCoord(vt[vti2-1]); m.addTexCoord(vt[vti3-1]); if(ls.peek() == ' ') { int vi4, vti4; ls >> vi4 >> vti4; m.addVertex(v[vi1-1]); m.addVertex(v[vi3-1]); m.addVertex(v[vi4-1]); m.addTexCoord(vt[vti1-1]); m.addTexCoord(vt[vti2-1]); m.addTexCoord(vt[vti3-1]); } } } } return m; } const float eyeRadius = 14; void loadEye(string filename, ofVec3f& leftEye, ofVec3f& rightEye) { ofFile f(filename); f >> leftEye.x >> leftEye.y >> leftEye.z; f >> rightEye.x >> rightEye.y >> rightEye.z; } void ofApp::setup() { ofSetDrawBitmapMode(OF_BITMAPMODE_MODEL_BILLBOARD); ofSetVerticalSync(true); faceShift.setup(); loadEye("export/eye", leftEye, rightEye); gui.setup(); const vector<string>& names = faceShift.getBlendshapeNames(); for(int i = 0; i < names.size(); i++) { gui.add(Slider(names[i], 0, 1, 0)); } ofDirectory dir("export"); dir.allowExt("obj"); dir.listDir(); for(int i = 0; i < dir.size(); i++) { cout << "loading " << dir.getPath(i) << endl; ofMesh mesh = loadObj(dir.getPath(i)); if(dir.getName(i) == "Neutral.obj") { neutral = mesh; } else { blendshapes.push_back(mesh); } } for(int i = 0; i < blendshapes.size(); i++) { valid.push_back(vector<unsigned int>()); for(int j = 0; j < blendshapes[i].getNumVertices(); j++) { blendshapes[i].getVertices()[j] -= neutral.getVertices()[j]; if(blendshapes[i].getVertices()[j] != ofVec3f()) { valid[i].push_back(j); } } } light.enable(); light.setPosition(+500, +500, +500); } void ofApp::update() { faceShift.update(); current = neutral; // do a weighted sum of all offsets from neutral float t = 3. * ofGetElapsedTimef(); for(int i = 0; i < blendshapes.size(); i++) { float separation = PI; gui.set(i, ofClamp(ofSignedNoise(t + separation * i), 0, 1)); float weight = gui.get(i); if(weight > 0) { for(int j = 0; j < valid[i].size(); j++) { int k = valid[i][j]; current.getVertices()[k] += weight * blendshapes[i].getVertices()[k]; } } } buildNormals(current); } void ofApp::draw(){ ofBackground(128); ofSetColor(255); ofNoFill(); int n = faceShift.getBlendshapeCount(); for(int i = 0; i < n; i++) { float weight = faceShift.getBlendshapeWeight(i); string name = faceShift.getBlendshapeName(i); ofRect(0, 0, weight * 100, 10); ofDrawBitmapString(name, weight * 100, 10); ofTranslate(0, 10); } cam.begin(); glEnable(GL_DEPTH_TEST); ofRotateX(180); ofFill(); current.draw(); ofSphere(leftEye, eyeRadius); ofSphere(rightEye, eyeRadius); cam.end(); } <commit_msg>added cornea and initial guess at eye orientation<commit_after>#include "ofApp.h" ofVec3f getNormal(const ofVec3f& v1, const ofVec3f& v2, const ofVec3f& v3) { ofVec3f a = v1 - v2; ofVec3f b = v3 - v2; ofVec3f normal = b.cross(a); normal.normalize(); return normal; } void buildNormals(ofMesh& mesh) { vector<ofVec3f>& vertices = mesh.getVertices(); mesh.clearNormals(); for(int i = 0; i < mesh.getNumVertices(); i += 3) { ofVec3f normal = getNormal(mesh.getVertices()[i+0], mesh.getVertices()[i+1], mesh.getVertices()[i+2]); for(int j = 0; j < 3; j++) { mesh.addNormal(normal); } } } ofMesh loadObj(string filename) { ofMesh m; vector<ofVec3f> v; vector<ofVec2f> vt; ofFile f(filename); while(!f.eof()) { string c; f >> c; if(c.size()) { if(c == "v") { float x, y, z; f >> x >> y >> z; v.push_back(ofVec3f(x, y, z)); } else if(c == "vt") { float u, v; f >> u >> v; vt.push_back(ofVec2f(u, v)); } else if(c == "f") { string l; getline(f, l); replace(l.begin(), l.end(), '/', ' '); istringstream ls(l); int vi1, vti1, vi2, vti2, vi3, vti3; ls >> vi1 >> vti1 >> vi2 >> vti2 >> vi3 >> vti3; m.addVertex(v[vi1-1]); m.addVertex(v[vi2-1]); m.addVertex(v[vi3-1]); m.addTexCoord(vt[vti1-1]); m.addTexCoord(vt[vti2-1]); m.addTexCoord(vt[vti3-1]); if(ls.peek() == ' ') { int vi4, vti4; ls >> vi4 >> vti4; m.addVertex(v[vi1-1]); m.addVertex(v[vi3-1]); m.addVertex(v[vi4-1]); m.addTexCoord(vt[vti1-1]); m.addTexCoord(vt[vti2-1]); m.addTexCoord(vt[vti3-1]); } } } } return m; } void loadEye(string filename, ofVec3f& leftEye, ofVec3f& rightEye) { ofFile f(filename); f >> leftEye.x >> leftEye.y >> leftEye.z; f >> rightEye.x >> rightEye.y >> rightEye.z; } const float eyeRadius = 14, corneaScale = .6; void drawEye(ofVec3f position, ofVec2f orientation = ofVec2f()) { ofPushMatrix(); ofTranslate(position); ofRotateY(orientation.x); ofRotateX(orientation.y); ofSphere(eyeRadius); ofTranslate(0, 0, -eyeRadius * (1.1 - corneaScale)); ofSphere(eyeRadius * corneaScale); ofPopMatrix(); } void ofApp::setup() { ofSetDrawBitmapMode(OF_BITMAPMODE_MODEL_BILLBOARD); ofSetVerticalSync(true); faceShift.setup(); loadEye("export/eye", leftEye, rightEye); gui.setup(); const vector<string>& names = faceShift.getBlendshapeNames(); for(int i = 0; i < names.size(); i++) { gui.add(Slider(names[i], 0, 1, 0)); } ofDirectory dir("export"); dir.allowExt("obj"); dir.listDir(); for(int i = 0; i < dir.size(); i++) { cout << "loading " << dir.getPath(i) << endl; ofMesh mesh = loadObj(dir.getPath(i)); if(dir.getName(i) == "Neutral.obj") { neutral = mesh; } else { blendshapes.push_back(mesh); } } for(int i = 0; i < blendshapes.size(); i++) { valid.push_back(vector<unsigned int>()); for(int j = 0; j < blendshapes[i].getNumVertices(); j++) { blendshapes[i].getVertices()[j] -= neutral.getVertices()[j]; if(blendshapes[i].getVertices()[j] != ofVec3f()) { valid[i].push_back(j); } } } light.enable(); light.setPosition(+500, +500, +500); } void ofApp::update() { faceShift.update(); current = neutral; // do a weighted sum of all offsets from neutral float t = 3. * ofGetElapsedTimef(); for(int i = 0; i < blendshapes.size(); i++) { float separation = PI; gui.set(i, ofClamp(ofSignedNoise(t + separation * i), 0, 1)); float weight = gui.get(i); if(weight > 0) { for(int j = 0; j < valid[i].size(); j++) { int k = valid[i][j]; current.getVertices()[k] += weight * blendshapes[i].getVertices()[k]; } } } buildNormals(current); } void ofApp::draw(){ ofBackground(128); ofSetColor(255); ofNoFill(); int n = faceShift.getBlendshapeCount(); for(int i = 0; i < n; i++) { float weight = faceShift.getBlendshapeWeight(i); string name = faceShift.getBlendshapeName(i); ofRect(0, 0, weight * 100, 10); ofDrawBitmapString(name, weight * 100, 10); ofTranslate(0, 10); } cam.begin(); glEnable(GL_DEPTH_TEST); ofRotateX(180); ofFill(); current.draw(); drawEye(leftEye); drawEye(rightEye); cam.end(); } <|endoftext|>
<commit_before>//===- ICF.cpp ------------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Identical Code Folding is a feature to merge sections not by name (which // is regular comdat handling) but by contents. If two non-writable sections // have the same data, relocations, attributes, etc., then the two // are considered identical and merged by the linker. This optimization // makes outputs smaller. // // ICF is theoretically a problem of reducing graphs by merging as many // identical subgraphs as possible if we consider sections as vertices and // relocations as edges. It may sound simple, but it is a bit more // complicated than you might think. The order of processing sections // matters because merging two sections can make other sections, whose // relocations now point to the same section, mergeable. Graphs may contain // cycles. We need a sophisticated algorithm to do this properly and // efficiently. // // What we do in this file is this. We split sections into groups. Sections // in the same group are considered identical. // // We begin by optimistically putting all sections into a single equivalence // class. Then we apply a series of checks that split this initial // equivalence class into more and more refined equivalence classes based on // the properties by which a section can be distinguished. // // We begin by checking that the section contents and flags are the // same. This only needs to be done once since these properties don't depend // on the current equivalence class assignment. // // Then we split the equivalence classes based on checking that their // relocations are the same, where relocation targets are compared by their // equivalence class, not the concrete section. This may need to be done // multiple times because as the equivalence classes are refined, two // sections that had a relocation target in the same equivalence class may // now target different equivalence classes, and hence these two sections // must be put in different equivalence classes (whereas in the previous // iteration they were not since the relocation target was the same.) // // Our algorithm is smart enough to merge the following mutually-recursive // functions. // // void foo() { bar(); } // void bar() { foo(); } // // This algorithm is so-called "optimistic" algorithm described in // http://research.google.com/pubs/pub36912.html. (Note that what GNU // gold implemented is different from the optimistic algorithm.) // //===----------------------------------------------------------------------===// #include "ICF.h" #include "Config.h" #include "SymbolTable.h" #include "llvm/ADT/Hashing.h" #include "llvm/Object/ELF.h" #include "llvm/Support/ELF.h" #include <algorithm> using namespace lld; using namespace lld::elf; using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; namespace { template <class ELFT> class ICF { public: void run(); private: uint64_t NextId = 1; using Comparator = std::function<bool(const InputSection<ELFT> *, const InputSection<ELFT> *)>; void segregate(MutableArrayRef<InputSection<ELFT> *> Arr, Comparator Eq); void forEachGroup(std::vector<InputSection<ELFT> *> &V, std::function<void(MutableArrayRef<InputSection<ELFT> *>)> Fn); }; } // Returns a hash value for S. Note that the information about // relocation targets is not included in the hash value. template <class ELFT> static uint64_t getHash(InputSection<ELFT> *S) { return hash_combine(S->Flags, S->getSize(), S->NumRelocations); } // Returns true if section S is subject of ICF. template <class ELFT> static bool isEligible(InputSection<ELFT> *S) { // .init and .fini contains instructions that must be executed to // initialize and finalize the process. They cannot and should not // be merged. return S->Live && (S->Flags & SHF_ALLOC) && !(S->Flags & SHF_WRITE) && S->Name != ".init" && S->Name != ".fini"; } template <class ELFT> static std::vector<InputSection<ELFT> *> getSections() { std::vector<InputSection<ELFT> *> V; for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) if (auto *S = dyn_cast<InputSection<ELFT>>(Sec)) if (isEligible(S)) V.push_back(S); return V; } // All sections between Begin and End must have the same group ID before // you call this function. This function compare sections between Begin // and End using Eq and assign new group IDs for new groups. template <class ELFT> void ICF<ELFT>::segregate(MutableArrayRef<InputSection<ELFT> *> Arr, Comparator Eq) { // This loop rearranges [Begin, End) so that all sections that are // equal in terms of Eq are contiguous. The algorithm is quadratic in // the worst case, but that is not an issue in practice because the // number of distinct sections in [Begin, End) is usually very small. InputSection<ELFT> **I = Arr.begin(); for (;;) { InputSection<ELFT> *Head = *I; auto Bound = std::stable_partition( I + 1, Arr.end(), [&](InputSection<ELFT> *S) { return Eq(Head, S); }); if (Bound == Arr.end()) return; uint64_t Id = NextId++; for (; I != Bound; ++I) (*I)->GroupId = Id; } } template <class ELFT> void ICF<ELFT>::forEachGroup( std::vector<InputSection<ELFT> *> &V, std::function<void(MutableArrayRef<InputSection<ELFT> *>)> Fn) { for (InputSection<ELFT> **I = V.data(), **E = I + V.size(); I != E;) { InputSection<ELFT> *Head = *I; auto Bound = std::find_if(I + 1, E, [&](InputSection<ELFT> *S) { return S->GroupId != Head->GroupId; }); Fn({I, Bound}); I = Bound; } } // Compare two lists of relocations. template <class ELFT, class RelTy> static bool relocationEq(ArrayRef<RelTy> RelsA, ArrayRef<RelTy> RelsB) { auto Eq = [](const RelTy &A, const RelTy &B) { return A.r_offset == B.r_offset && A.getType(Config->Mips64EL) == B.getType(Config->Mips64EL) && getAddend<ELFT>(A) == getAddend<ELFT>(B); }; return RelsA.size() == RelsB.size() && std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "non-moving" part of two InputSections, namely everything // except relocation targets. template <class ELFT> static bool equalsConstant(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->NumRelocations != B->NumRelocations || A->Flags != B->Flags || A->getSize() != B->getSize() || A->Data != B->Data) return false; if (A->AreRelocsRela) return relocationEq<ELFT>(A->relas(), B->relas()); return relocationEq<ELFT>(A->rels(), B->rels()); } template <class ELFT, class RelTy> static bool variableEq(const InputSection<ELFT> *A, ArrayRef<RelTy> RelsA, const InputSection<ELFT> *B, ArrayRef<RelTy> RelsB) { auto Eq = [&](const RelTy &RA, const RelTy &RB) { SymbolBody &SA = A->getFile()->getRelocTargetSym(RA); SymbolBody &SB = B->getFile()->getRelocTargetSym(RB); if (&SA == &SB) return true; // Or, the symbols should be pointing to the same section // in terms of the group ID. auto *DA = dyn_cast<DefinedRegular<ELFT>>(&SA); auto *DB = dyn_cast<DefinedRegular<ELFT>>(&SB); if (!DA || !DB) return false; if (DA->Value != DB->Value) return false; auto *X = dyn_cast<InputSection<ELFT>>(DA->Section); auto *Y = dyn_cast<InputSection<ELFT>>(DB->Section); return X && Y && X->GroupId && X->GroupId == Y->GroupId; }; return std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "moving" part of two InputSections, namely relocation targets. template <class ELFT> static bool equalsVariable(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->AreRelocsRela) return variableEq(A, A->relas(), B, B->relas()); return variableEq(A, A->rels(), B, B->rels()); } // The main function of ICF. template <class ELFT> void ICF<ELFT>::run() { // Initially, we use hash values as section group IDs. Therefore, // if two sections have the same ID, they are likely (but not // guaranteed) to have the same static contents in terms of ICF. std::vector<InputSection<ELFT> *> Sections = getSections<ELFT>(); for (InputSection<ELFT> *S : Sections) // Set MSB on to avoid collisions with serial group IDs S->GroupId = getHash(S) | (uint64_t(1) << 63); // From now on, sections in V are ordered so that sections in // the same group are consecutive in the vector. std::stable_sort(Sections.begin(), Sections.end(), [](InputSection<ELFT> *A, InputSection<ELFT> *B) { if (A->GroupId != B->GroupId) return A->GroupId < B->GroupId; // Within a group, put the highest alignment // requirement first, so that's the one we'll keep. return B->Alignment < A->Alignment; }); // Compare static contents and assign unique IDs for each static content. forEachGroup(Sections, [&](MutableArrayRef<InputSection<ELFT> *> V) { segregate(V, equalsConstant<ELFT>); }); // Split groups by comparing relocations until we get a convergence. int Cnt = 1; for (;;) { ++Cnt; uint64_t Id = NextId; forEachGroup(Sections, [&](MutableArrayRef<InputSection<ELFT> *> V) { segregate(V, equalsVariable<ELFT>); }); if (Id == NextId) break; } log("ICF needed " + Twine(Cnt) + " iterations."); // Merge sections in the same group. forEachGroup(Sections, [](MutableArrayRef<InputSection<ELFT> *> V) { log("selected " + V[0]->Name); for (InputSection<ELFT> *S : V.slice(1)) { log(" removed " + S->Name); V[0]->replace(S); } }); } // ICF entry point function. template <class ELFT> void elf::doIcf() { ICF<ELFT>().run(); } template void elf::doIcf<ELF32LE>(); template void elf::doIcf<ELF32BE>(); template void elf::doIcf<ELF64LE>(); template void elf::doIcf<ELF64BE>(); <commit_msg>Update comments.<commit_after>//===- ICF.cpp ------------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Identical Code Folding is a feature to merge sections not by name (which // is regular comdat handling) but by contents. If two non-writable sections // have the same data, relocations, attributes, etc., then the two // are considered identical and merged by the linker. This optimization // makes outputs smaller. // // ICF is theoretically a problem of reducing graphs by merging as many // identical subgraphs as possible if we consider sections as vertices and // relocations as edges. It may sound simple, but it is a bit more // complicated than you might think. The order of processing sections // matters because merging two sections can make other sections, whose // relocations now point to the same section, mergeable. Graphs may contain // cycles. We need a sophisticated algorithm to do this properly and // efficiently. // // What we do in this file is this. We split sections into groups. Sections // in the same group are considered identical. // // We begin by optimistically putting all sections into a single equivalence // class. Then we apply a series of checks that split this initial // equivalence class into more and more refined equivalence classes based on // the properties by which a section can be distinguished. // // We begin by checking that the section contents and flags are the // same. This only needs to be done once since these properties don't depend // on the current equivalence class assignment. // // Then we split the equivalence classes based on checking that their // relocations are the same, where relocation targets are compared by their // equivalence class, not the concrete section. This may need to be done // multiple times because as the equivalence classes are refined, two // sections that had a relocation target in the same equivalence class may // now target different equivalence classes, and hence these two sections // must be put in different equivalence classes (whereas in the previous // iteration they were not since the relocation target was the same.) // // Our algorithm is smart enough to merge the following mutually-recursive // functions. // // void foo() { bar(); } // void bar() { foo(); } // // This algorithm is so-called "optimistic" algorithm described in // http://research.google.com/pubs/pub36912.html. (Note that what GNU // gold implemented is different from the optimistic algorithm.) // //===----------------------------------------------------------------------===// #include "ICF.h" #include "Config.h" #include "SymbolTable.h" #include "llvm/ADT/Hashing.h" #include "llvm/Object/ELF.h" #include "llvm/Support/ELF.h" #include <algorithm> using namespace lld; using namespace lld::elf; using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; namespace { template <class ELFT> class ICF { public: void run(); private: uint64_t NextId = 1; using Comparator = std::function<bool(const InputSection<ELFT> *, const InputSection<ELFT> *)>; void segregate(MutableArrayRef<InputSection<ELFT> *> Arr, Comparator Eq); void forEachGroup(std::vector<InputSection<ELFT> *> &V, std::function<void(MutableArrayRef<InputSection<ELFT> *>)> Fn); }; } // Returns a hash value for S. Note that the information about // relocation targets is not included in the hash value. template <class ELFT> static uint64_t getHash(InputSection<ELFT> *S) { return hash_combine(S->Flags, S->getSize(), S->NumRelocations); } // Returns true if section S is subject of ICF. template <class ELFT> static bool isEligible(InputSection<ELFT> *S) { // .init and .fini contains instructions that must be executed to // initialize and finalize the process. They cannot and should not // be merged. return S->Live && (S->Flags & SHF_ALLOC) && !(S->Flags & SHF_WRITE) && S->Name != ".init" && S->Name != ".fini"; } template <class ELFT> static std::vector<InputSection<ELFT> *> getSections() { std::vector<InputSection<ELFT> *> V; for (InputSectionBase<ELFT> *Sec : Symtab<ELFT>::X->Sections) if (auto *S = dyn_cast<InputSection<ELFT>>(Sec)) if (isEligible(S)) V.push_back(S); return V; } // Before calling this function, all sections in Arr must have the // same group ID. This function compare sections in Arr using Eq and // assign new group IDs for new groups. template <class ELFT> void ICF<ELFT>::segregate(MutableArrayRef<InputSection<ELFT> *> Arr, Comparator Eq) { // This loop rearranges Arr so that all sections that are equal in // terms of Eq are contiguous. The algorithm is quadratic in the // worst case, but that is not an issue in practice because the // number of distinct sections in Arr is usually very small. InputSection<ELFT> **I = Arr.begin(); for (;;) { InputSection<ELFT> *Head = *I; auto Bound = std::stable_partition( I + 1, Arr.end(), [&](InputSection<ELFT> *S) { return Eq(Head, S); }); if (Bound == Arr.end()) return; uint64_t Id = NextId++; for (; I != Bound; ++I) (*I)->GroupId = Id; } } // Call Fn for each section group having the same group ID. template <class ELFT> void ICF<ELFT>::forEachGroup( std::vector<InputSection<ELFT> *> &V, std::function<void(MutableArrayRef<InputSection<ELFT> *>)> Fn) { for (InputSection<ELFT> **I = V.data(), **E = I + V.size(); I != E;) { InputSection<ELFT> *Head = *I; auto Bound = std::find_if(I + 1, E, [&](InputSection<ELFT> *S) { return S->GroupId != Head->GroupId; }); Fn({I, Bound}); I = Bound; } } // Compare two lists of relocations. template <class ELFT, class RelTy> static bool relocationEq(ArrayRef<RelTy> RelsA, ArrayRef<RelTy> RelsB) { auto Eq = [](const RelTy &A, const RelTy &B) { return A.r_offset == B.r_offset && A.getType(Config->Mips64EL) == B.getType(Config->Mips64EL) && getAddend<ELFT>(A) == getAddend<ELFT>(B); }; return RelsA.size() == RelsB.size() && std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "non-moving" part of two InputSections, namely everything // except relocation targets. template <class ELFT> static bool equalsConstant(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->NumRelocations != B->NumRelocations || A->Flags != B->Flags || A->getSize() != B->getSize() || A->Data != B->Data) return false; if (A->AreRelocsRela) return relocationEq<ELFT>(A->relas(), B->relas()); return relocationEq<ELFT>(A->rels(), B->rels()); } // Compare two lists of relocations. Returns true if all pairs of // relocations point to the same section in terms of ICF. template <class ELFT, class RelTy> static bool variableEq(const InputSection<ELFT> *A, ArrayRef<RelTy> RelsA, const InputSection<ELFT> *B, ArrayRef<RelTy> RelsB) { auto Eq = [&](const RelTy &RA, const RelTy &RB) { SymbolBody &SA = A->getFile()->getRelocTargetSym(RA); SymbolBody &SB = B->getFile()->getRelocTargetSym(RB); if (&SA == &SB) return true; // Or, the symbols should be pointing to the same section // in terms of the group ID. auto *DA = dyn_cast<DefinedRegular<ELFT>>(&SA); auto *DB = dyn_cast<DefinedRegular<ELFT>>(&SB); if (!DA || !DB) return false; if (DA->Value != DB->Value) return false; auto *X = dyn_cast<InputSection<ELFT>>(DA->Section); auto *Y = dyn_cast<InputSection<ELFT>>(DB->Section); return X && Y && X->GroupId && X->GroupId == Y->GroupId; }; return std::equal(RelsA.begin(), RelsA.end(), RelsB.begin(), Eq); } // Compare "moving" part of two InputSections, namely relocation targets. template <class ELFT> static bool equalsVariable(const InputSection<ELFT> *A, const InputSection<ELFT> *B) { if (A->AreRelocsRela) return variableEq(A, A->relas(), B, B->relas()); return variableEq(A, A->rels(), B, B->rels()); } // The main function of ICF. template <class ELFT> void ICF<ELFT>::run() { // Initially, we use hash values as section group IDs. Therefore, // if two sections have the same ID, they are likely (but not // guaranteed) to have the same static contents in terms of ICF. std::vector<InputSection<ELFT> *> Sections = getSections<ELFT>(); for (InputSection<ELFT> *S : Sections) // Set MSB on to avoid collisions with serial group IDs S->GroupId = getHash(S) | (uint64_t(1) << 63); // From now on, sections in Sections are ordered so that sections in // the same group are consecutive in the vector. std::stable_sort(Sections.begin(), Sections.end(), [](InputSection<ELFT> *A, InputSection<ELFT> *B) { if (A->GroupId != B->GroupId) return A->GroupId < B->GroupId; // Within a group, put the highest alignment // requirement first, so that's the one we'll keep. return B->Alignment < A->Alignment; }); // Compare static contents and assign unique IDs for each static content. forEachGroup(Sections, [&](MutableArrayRef<InputSection<ELFT> *> V) { segregate(V, equalsConstant<ELFT>); }); // Split groups by comparing relocations until we get a convergence. int Cnt = 1; for (;;) { ++Cnt; uint64_t Id = NextId; forEachGroup(Sections, [&](MutableArrayRef<InputSection<ELFT> *> V) { segregate(V, equalsVariable<ELFT>); }); if (Id == NextId) break; } log("ICF needed " + Twine(Cnt) + " iterations."); // Merge sections in the same group. forEachGroup(Sections, [](MutableArrayRef<InputSection<ELFT> *> V) { log("selected " + V[0]->Name); for (InputSection<ELFT> *S : V.slice(1)) { log(" removed " + S->Name); V[0]->replace(S); } }); } // ICF entry point function. template <class ELFT> void elf::doIcf() { ICF<ELFT>().run(); } template void elf::doIcf<ELF32LE>(); template void elf::doIcf<ELF32BE>(); template void elf::doIcf<ELF64LE>(); template void elf::doIcf<ELF64BE>(); <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of QMime ** ** Based on Qt Creator source code ** ** Qt Creator Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** **************************************************************************/ #include "magicmatcher.h" #include "magicmatcher_p.h" #include "qmimetype_p.h" #include <QtCore/QDebug> #include <qendian.h> // UTF16 byte order marks static const char bigEndianByteOrderMarkC[] = "\xFE\xFF"; static const char littleEndianByteOrderMarkC[] = "\xFF\xFE"; /*! \class IMagicMatcher \brief Interface for a Mime type magic matcher (examinig file contents). \sa MimeType, MimeDatabase, MagicRuleMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ //namespace Core { typedef QSharedPointer<MagicRuleMatcher> MagicRuleMatcherPtr; //namespace Internal { /*! \class FileMatchContext \brief Context passed on to the mime types when looking for a file match. It exists to enable reading the file contents "on demand" (as opposed to each mime type trying to open and read while checking). \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ FileMatchContext::FileMatchContext(const QFileInfo &fi) : m_fileInfo(fi), m_fileName(fi.fileName()), m_state(fi.isFile() && fi.isReadable() && fi.size() > 0 ? DataNotRead : NoDataAvailable) { } QByteArray FileMatchContext::data() { // Do we need to read? if (m_state == DataNotRead) { const QString fullName = m_fileInfo.absoluteFilePath(); QFile file(fullName); if (file.open(QIODevice::ReadOnly)) { m_data = file.read(MaxData); m_state = DataRead; } else { qWarning("%s failed to open %s: %s\n", Q_FUNC_INFO, fullName.toUtf8().constData(), file.errorString().toUtf8().constData()); m_state = NoDataAvailable; } } return m_data; } /*! \class BinaryMatcher \brief The binary fallback matcher for mime type "application/octet-stream". \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ /*! \class HeuristicTextMagicMatcher \brief Heuristic text file matcher for mime types. If the data do not contain any character below tab (9), detect as text. Additionally, check on UTF16 byte order markers. \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher \sa BaseMimeTypeParser, MimeTypeParser */ bool HeuristicTextMagicMatcher::isTextFile(const QByteArray &data) { const int size = data.size(); for (int i = 0; i < size; i++) { const char c = data.at(i); if (c >= 0x01 && c < 0x09) // Sure-fire binary return false; if (c == 0) // Check for UTF16 return data.startsWith(bigEndianByteOrderMarkC) || data.startsWith(littleEndianByteOrderMarkC); } return true; } bool HeuristicTextMagicMatcher::matches(const QByteArray &data) const { const bool rc = isTextFile(data); if (debugMimeDB) qDebug() << Q_FUNC_INFO << " on " << data.size() << " returns " << rc; return rc; } //} // namespace Internal /*! \class MagicRule \brief Base class for standard Magic match rules based on contents and offset specification. Stores the offset and provides conversion helpers. Base class for implementations for "string" and "byte". (Others like little16, big16, etc. can be created whenever there is a need.) \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ const QChar MagicRule::kColon(QLatin1Char(':')); MagicRule::MagicRule(int startPos, int endPos) : m_startPos(startPos), m_endPos(endPos) { } MagicRule::~MagicRule() { } int MagicRule::startPos() const { return m_startPos; } int MagicRule::endPos() const { return m_endPos; } QString MagicRule::toOffset(const QPair<int, int> &startEnd) { return QString(QLatin1String("%1:%2")).arg(startEnd.first).arg(startEnd.second); } QPair<int, int> MagicRule::fromOffset(const QString &offset) { const QStringList &startEnd = offset.split(kColon); Q_ASSERT(startEnd.size() == 2); return qMakePair(startEnd.at(0).toInt(), startEnd.at(1).toInt()); } /*! \class MagicStringRule \brief Match on a string. \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ const QString MagicStringRule::kMatchType("string"); MagicStringRule::MagicStringRule(const QString &s, int startPos, int endPos) : MagicRule(startPos, endPos), m_pattern(s.toUtf8()) { } MagicStringRule::~MagicStringRule() { } QString MagicStringRule::matchType() const { return kMatchType; } QString MagicStringRule::matchValue() const { return m_pattern; } bool MagicStringRule::matches(const QByteArray &data) const { // Quick check if ((startPos() + m_pattern.size()) > data.size()) return false; // Most common: some string at position 0: if (startPos() == 0 && startPos() == endPos()) return data.startsWith(m_pattern); // Range return QByteArray::fromRawData(data.data() + startPos(), endPos() - startPos() + m_pattern.size()).contains(m_pattern); } /*! \class MagicByteRule \brief Match on a sequence of binary data. Format: \code \0x7f\0x45\0x4c\0x46 \endcode \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ const QString MagicByteRule::kMatchType(QLatin1String("byte")); MagicByteRule::MagicByteRule(const QString &s, int startPos, int endPos) : MagicRule(startPos, endPos), m_bytesSize(0) { if (validateByteSequence(s, &m_bytes)) m_bytesSize = m_bytes.size(); else m_bytes.clear(); } MagicByteRule::~MagicByteRule() { } bool MagicByteRule::validateByteSequence(const QString &sequence, QList<int> *bytes) { // Expect an hex format value like this: \0x7f\0x45\0x4c\0x46 const QStringList &byteSequence = sequence.split(QLatin1Char('\\'), QString::SkipEmptyParts); foreach (const QString &byte, byteSequence) { bool ok; const int hex = byte.toInt(&ok, 16); if (ok) { if (bytes) bytes->push_back(hex); } else { return false; } } return true; } QString MagicByteRule::matchType() const { return kMatchType; } QString MagicByteRule::matchValue() const { QString value; foreach (int byte, m_bytes) value.append(QString(QLatin1String("\\0x%1")).arg(byte, 0, 16)); return value; } bool MagicByteRule::matches(const QByteArray &data) const { if (m_bytesSize == 0) return false; const int dataSize = data.size(); for (int start = startPos(); start <= endPos(); ++start) { if ((start + m_bytesSize) > dataSize) return false; int matchAt = 0; while (matchAt < m_bytesSize) { if (data.at(start + matchAt) != m_bytes.at(matchAt)) break; ++matchAt; } if (matchAt == m_bytesSize) return true; } return false; } MagicNumberRule::MagicNumberRule(const QString &s, int startPos, int endPos, Size size, Endianness endianness) : MagicRule(startPos, endPos), m_stringValue(s), m_size(size), m_endiannes(endianness) { bool ok; uint value = s.toUInt(&ok, 8); if (!ok) { value = s.toUInt(&ok, 16); } if (!ok) { value = s.toUInt(&ok, 10); } if (!ok) qWarning() << "MagicNumberRule::MagicNumberRule: Can't convert string to int"; if (size == Size16) { m_value16 = value; if (endianness == LittleEndian) m_value16 = qFromLittleEndian<quint16>(value); else if (endianness == BigEndian) m_value16 = qFromBigEndian<quint16>(value); else m_value16 = qFromBigEndian<quint16>(value); // reverse on little-endians } else if (size == Size32) { m_value32 = value; if (endianness == LittleEndian) m_value32 = qFromLittleEndian<quint32>(value); else if (endianness == BigEndian) m_value32 = qFromBigEndian<quint32>(value); else m_value32 = qFromBigEndian<quint32>(value); // reverse on little-endians } } MagicNumberRule::~MagicNumberRule() { } QString MagicNumberRule::matchType() const { static const QString kMatchType(QLatin1String("big16")); return kMatchType; } QString MagicNumberRule::matchValue() const { return m_stringValue; } bool MagicNumberRule::matches(const QByteArray &data) const { if (m_size == Size16) { for (int i = startPos(); i <= endPos(); i++) { if (data.size() < i + 2) return false; if ( *(reinterpret_cast<const quint16*>(data.data() + i)) == m_value16 ) return true; } } else if (m_size == Size32) { for (int i = startPos(); i <= endPos(); i++) { if (data.size() < i + 4) return false; if ( *(reinterpret_cast<const quint32*>(data.data() + i)) == m_value32 ) return true; } } return false; } /*! \class MagicRuleMatcher \brief A Magic matcher that checks a number of rules based on operator "or". It is used for rules parsed from XML files. \sa MimeType, MimeDatabase, IMagicMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ MagicRuleMatcher::MagicRuleMatcher() : m_priority(65535) { } void MagicRuleMatcher::add(const MagicRuleSharedPointer &rule) { m_list.append(rule); } void MagicRuleMatcher::add(const MagicRuleList &ruleList) { m_list.append(ruleList); } MagicRuleMatcher::MagicRuleList MagicRuleMatcher::magicRules() const { return m_list; } bool MagicRuleMatcher::matches(const QByteArray &data) const { const MagicRuleList::const_iterator cend = m_list.constEnd(); for (MagicRuleList::const_iterator it = m_list.constBegin(); it != cend; ++it) if ( (*it)->matches(data)) return true; return false; } int MagicRuleMatcher::priority() const { return m_priority; } void MagicRuleMatcher::setPriority(int p) { m_priority = p; } IMagicMatcher::IMagicMatcherList MagicRuleMatcher::createMatchers( const QHash<int, MagicRuleList> &rulesByPriority) { IMagicMatcher::IMagicMatcherList matchers; QHash<int, MagicRuleList>::const_iterator ruleIt = rulesByPriority.begin(); for (; ruleIt != rulesByPriority.end(); ++ruleIt) { MagicRuleMatcher *magicRuleMatcher = new MagicRuleMatcher(); magicRuleMatcher->setPriority(ruleIt.key()); magicRuleMatcher->add(ruleIt.value()); matchers.append(IMagicMatcher::IMagicMatcherSharedPointer(magicRuleMatcher)); } return matchers; } <commit_msg>Refactoring<commit_after>/************************************************************************** ** ** This file is part of QMime ** ** Based on Qt Creator source code ** ** Qt Creator Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** **************************************************************************/ #include "magicmatcher.h" #include "magicmatcher_p.h" #include "qmimetype_p.h" #include <QtCore/QDebug> #include <qendian.h> // UTF16 byte order marks static const char bigEndianByteOrderMarkC[] = "\xFE\xFF"; static const char littleEndianByteOrderMarkC[] = "\xFF\xFE"; /*! \class IMagicMatcher \brief Interface for a Mime type magic matcher (examinig file contents). \sa MimeType, MimeDatabase, MagicRuleMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ //namespace Core { typedef QSharedPointer<MagicRuleMatcher> MagicRuleMatcherPtr; //namespace Internal { /*! \class FileMatchContext \brief Context passed on to the mime types when looking for a file match. It exists to enable reading the file contents "on demand" (as opposed to each mime type trying to open and read while checking). \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ FileMatchContext::FileMatchContext(const QFileInfo &fi) : m_fileInfo(fi), m_fileName(fi.fileName()), m_state(fi.isFile() && fi.isReadable() && fi.size() > 0 ? DataNotRead : NoDataAvailable) { } QByteArray FileMatchContext::data() { // Do we need to read? if (m_state == DataNotRead) { const QString fullName = m_fileInfo.absoluteFilePath(); QFile file(fullName); if (file.open(QIODevice::ReadOnly)) { m_data = file.read(MaxData); m_state = DataRead; } else { qWarning("%s failed to open %s: %s\n", Q_FUNC_INFO, fullName.toUtf8().constData(), file.errorString().toUtf8().constData()); m_state = NoDataAvailable; } } return m_data; } /*! \class BinaryMatcher \brief The binary fallback matcher for mime type "application/octet-stream". \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ /*! \class HeuristicTextMagicMatcher \brief Heuristic text file matcher for mime types. If the data do not contain any character below tab (9), detect as text. Additionally, check on UTF16 byte order markers. \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher \sa BaseMimeTypeParser, MimeTypeParser */ bool HeuristicTextMagicMatcher::isTextFile(const QByteArray &data) { const int size = data.size(); for (int i = 0; i < size; i++) { const char c = data.at(i); if (c >= 0x01 && c < 0x09) // Sure-fire binary return false; if (c == 0) // Check for UTF16 return data.startsWith(bigEndianByteOrderMarkC) || data.startsWith(littleEndianByteOrderMarkC); } return true; } bool HeuristicTextMagicMatcher::matches(const QByteArray &data) const { const bool rc = isTextFile(data); if (debugMimeDB) qDebug() << Q_FUNC_INFO << " on " << data.size() << " returns " << rc; return rc; } //} // namespace Internal /*! \class MagicRule \brief Base class for standard Magic match rules based on contents and offset specification. Stores the offset and provides conversion helpers. Base class for implementations for "string" and "byte". (Others like little16, big16, etc. can be created whenever there is a need.) \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ const QChar MagicRule::kColon(QLatin1Char(':')); MagicRule::MagicRule(int startPos, int endPos) : m_startPos(startPos), m_endPos(endPos) { } MagicRule::~MagicRule() { } int MagicRule::startPos() const { return m_startPos; } int MagicRule::endPos() const { return m_endPos; } QString MagicRule::toOffset(const QPair<int, int> &startEnd) { return QString(QLatin1String("%1:%2")).arg(startEnd.first).arg(startEnd.second); } QPair<int, int> MagicRule::fromOffset(const QString &offset) { const QStringList &startEnd = offset.split(kColon); Q_ASSERT(startEnd.size() == 2); return qMakePair(startEnd.at(0).toInt(), startEnd.at(1).toInt()); } /*! \class MagicStringRule \brief Match on a string. \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ const QString MagicStringRule::kMatchType("string"); MagicStringRule::MagicStringRule(const QString &s, int startPos, int endPos) : MagicRule(startPos, endPos), m_pattern(s.toUtf8()) { } MagicStringRule::~MagicStringRule() { } QString MagicStringRule::matchType() const { return kMatchType; } QString MagicStringRule::matchValue() const { return m_pattern; } bool MagicStringRule::matches(const QByteArray &data) const { // Quick check if ((startPos() + m_pattern.size()) > data.size()) return false; // Most common: some string at position 0: if (startPos() == 0 && startPos() == endPos()) return data.startsWith(m_pattern); // Range return QByteArray::fromRawData(data.data() + startPos(), endPos() - startPos() + m_pattern.size()).contains(m_pattern); } /*! \class MagicByteRule \brief Match on a sequence of binary data. Format: \code \0x7f\0x45\0x4c\0x46 \endcode \sa MimeType, MimeDatabase, IMagicMatcher, MagicRuleMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ const QString MagicByteRule::kMatchType(QLatin1String("byte")); MagicByteRule::MagicByteRule(const QString &s, int startPos, int endPos) : MagicRule(startPos, endPos), m_bytesSize(0) { if (validateByteSequence(s, &m_bytes)) m_bytesSize = m_bytes.size(); else m_bytes.clear(); } MagicByteRule::~MagicByteRule() { } bool MagicByteRule::validateByteSequence(const QString &sequence, QList<int> *bytes) { // Expect an hex format value like this: \0x7f\0x45\0x4c\0x46 const QStringList &byteSequence = sequence.split(QLatin1Char('\\'), QString::SkipEmptyParts); foreach (const QString &byte, byteSequence) { bool ok; const int hex = byte.toInt(&ok, 16); if (ok) { if (bytes) bytes->push_back(hex); } else { return false; } } return true; } QString MagicByteRule::matchType() const { return kMatchType; } QString MagicByteRule::matchValue() const { QString value; foreach (int byte, m_bytes) value.append(QString(QLatin1String("\\0x%1")).arg(byte, 0, 16)); return value; } bool MagicByteRule::matches(const QByteArray &data) const { if (m_bytesSize == 0) return false; const int dataSize = data.size(); for (int start = startPos(); start <= endPos(); ++start) { if ((start + m_bytesSize) > dataSize) return false; int matchAt = 0; while (matchAt < m_bytesSize) { if (data.at(start + matchAt) != m_bytes.at(matchAt)) break; ++matchAt; } if (matchAt == m_bytesSize) return true; } return false; } MagicNumberRule::MagicNumberRule(const QString &s, int startPos, int endPos, Size size, Endianness endianness) : MagicRule(startPos, endPos), m_stringValue(s), m_size(size), m_endiannes(endianness) { bool ok = false; uint value = 0; if (!s.isEmpty()) { if (s[0] == '0') { if (s.size() > 1 && s[1] == 'x') value = s.toUInt(&ok, 16); else value = s.toUInt(&ok, 8); } else value = s.toUInt(&ok, 10); } if (!ok) qWarning() << QString("MagicNumberRule::MagicNumberRule: Can't convert %1 string to int").arg(s); if (size == Size16) { if (endianness == LittleEndian) m_value16 = qFromLittleEndian<quint16>(value); else if (endianness == BigEndian) m_value16 = qFromBigEndian<quint16>(value); else m_value16 = qFromBigEndian<quint16>(value); // reverse on little-endians } else if (size == Size32) { if (endianness == LittleEndian) m_value32 = qFromLittleEndian<quint32>(value); else if (endianness == BigEndian) m_value32 = qFromBigEndian<quint32>(value); else m_value32 = qFromBigEndian<quint32>(value); // reverse on little-endians } } MagicNumberRule::~MagicNumberRule() { } QString MagicNumberRule::matchType() const { static const QString kMatchType(QLatin1String("big16")); return kMatchType; } QString MagicNumberRule::matchValue() const { return m_stringValue; } bool MagicNumberRule::matches(const QByteArray &data) const { if (m_size == Size16) { for (int i = startPos(); i <= endPos(); i++) { if (data.size() < i + 2) return false; if ( *(reinterpret_cast<const quint16*>(data.data() + i)) == m_value16 ) return true; } } else if (m_size == Size32) { for (int i = startPos(); i <= endPos(); i++) { if (data.size() < i + 4) return false; if ( *(reinterpret_cast<const quint32*>(data.data() + i)) == m_value32 ) return true; } } return false; } /*! \class MagicRuleMatcher \brief A Magic matcher that checks a number of rules based on operator "or". It is used for rules parsed from XML files. \sa MimeType, MimeDatabase, IMagicMatcher, MagicRule, MagicStringRule, MagicByteRule, GlobPattern \sa FileMatchContext, BinaryMatcher, HeuristicTextMagicMatcher \sa BaseMimeTypeParser, MimeTypeParser */ MagicRuleMatcher::MagicRuleMatcher() : m_priority(65535) { } void MagicRuleMatcher::add(const MagicRuleSharedPointer &rule) { m_list.append(rule); } void MagicRuleMatcher::add(const MagicRuleList &ruleList) { m_list.append(ruleList); } MagicRuleMatcher::MagicRuleList MagicRuleMatcher::magicRules() const { return m_list; } bool MagicRuleMatcher::matches(const QByteArray &data) const { const MagicRuleList::const_iterator cend = m_list.constEnd(); for (MagicRuleList::const_iterator it = m_list.constBegin(); it != cend; ++it) if ( (*it)->matches(data)) return true; return false; } int MagicRuleMatcher::priority() const { return m_priority; } void MagicRuleMatcher::setPriority(int p) { m_priority = p; } IMagicMatcher::IMagicMatcherList MagicRuleMatcher::createMatchers( const QHash<int, MagicRuleList> &rulesByPriority) { IMagicMatcher::IMagicMatcherList matchers; QHash<int, MagicRuleList>::const_iterator ruleIt = rulesByPriority.begin(); for (; ruleIt != rulesByPriority.end(); ++ruleIt) { MagicRuleMatcher *magicRuleMatcher = new MagicRuleMatcher(); magicRuleMatcher->setPriority(ruleIt.key()); magicRuleMatcher->add(ruleIt.value()); matchers.append(IMagicMatcher::IMagicMatcherSharedPointer(magicRuleMatcher)); } return matchers; } <|endoftext|>
<commit_before>/* * lines.cpp * * Created on: Oct 22, 2014 * Author: Carsten Uphoff ([email protected]) */ #include <Canvas.hpp> #include <LinePlot.hpp> #include <Color.hpp> #include <Geometry.hpp> #include <HorizontalLayout.hpp> #include <VerticalLayout.hpp> #include <GridLayout.hpp> #include <cmath> #define NUM_POINTS 200 int main() { double x[NUM_POINTS]; double y[NUM_POINTS]; double z[NUM_POINTS]; for (int i = 0; i < NUM_POINTS; ++i) { x[i] = i / static_cast<double>(NUM_POINTS); y[i] = sin(10.0 * x[i]); z[i] = cos(20.0 * x[i]); } hpl::Canvas canvas("../fonts/inconsolata.font"); canvas.setBackgroundColor(hpl::Color(0.9f, 0.9f, 0.9f)); hpl::HorizontalLayout& layout = canvas.addLayout<hpl::HorizontalLayout>(); hpl::LinePlot& plot1 = canvas.add1D<hpl::LinePlot>(NUM_POINTS, x, y); plot1.setLegendColor(hpl::Color(0.0f, 0.0f, 0.0f)); plot1.setLineColor(0, hpl::Color(0.1f, 0.3f, 0.6f)); hpl::LinePlot& plot2 = canvas.add1D<hpl::LinePlot>(NUM_POINTS, x, z); plot2.setLegendColor(hpl::Color(0.0f, 0.0f, 0.0f)); plot2.setLineColor(0, hpl::Color(0.6f, 0.3f, 0.1f)); canvas.addPlotToLayout(plot1->id(), layout->id()); /*hpl::sleep(1e6); canvas.setLayout(new hpl::HorizontalLayout(hpl::HorizontalLayout::RightToLeft)); for (int i = 0; i < 5; ++i) { hpl::sleep(5e5); plot2->setLineColor(0, hpl::Color( rand() / static_cast<float>(RAND_MAX), rand() / static_cast<float>(RAND_MAX), rand() / static_cast<float>(RAND_MAX) )); } hpl::sleep(1e6); canvas.setLayout(new hpl::GridLayout(2, 2, hpl::GridLayout::BottomRightToTopLeft)); hpl::ScatterPlot* plot3 = canvas.addScatterPlot(NUM_POINTS, x, y); plot3->setLegendColor(hpl::Color(0.0f, 0.0f, 0.0f)); plot3->setPointColor(0, hpl::Color(0.0f, 0.0f, 0.0f)); hpl::sleep(1e6); static_cast<hpl::GridLayout*>(canvas.getLayout())->changeOrientation(hpl::GridLayout::TopLeftToBottomRight); canvas.saveToFile("testoutput");*/ canvas.wait(); return 0; } <commit_msg>fixes example<commit_after>/* * lines.cpp * * Created on: Oct 22, 2014 * Author: Carsten Uphoff ([email protected]) */ #include <Canvas.hpp> #include <LinePlot.hpp> #include <Color.hpp> #include <Geometry.hpp> #include <HorizontalLayout.hpp> #include <VerticalLayout.hpp> #include <GridLayout.hpp> #include <cmath> #define NUM_POINTS 200 int main() { double x[NUM_POINTS]; double y[NUM_POINTS]; double z[NUM_POINTS]; for (int i = 0; i < NUM_POINTS; ++i) { x[i] = i / static_cast<double>(NUM_POINTS); y[i] = sin(10.0 * x[i]); z[i] = cos(20.0 * x[i]); } hpl::Canvas canvas("../fonts/inconsolata.font"); canvas.setBackgroundColor(hpl::Color(0.9f, 0.9f, 0.9f)); hpl::HorizontalLayout& layout = canvas.addLayout<hpl::HorizontalLayout>(); hpl::LinePlot& plot1 = canvas.add1D<hpl::LinePlot>(NUM_POINTS, x, y); plot1.setLegendColor(hpl::Color(0.0f, 0.0f, 0.0f)); plot1.setLineColor(0, hpl::Color(0.1f, 0.3f, 0.6f)); hpl::LinePlot& plot2 = canvas.add1D<hpl::LinePlot>(NUM_POINTS, x, z); plot2.setLegendColor(hpl::Color(0.0f, 0.0f, 0.0f)); plot2.setLineColor(0, hpl::Color(0.6f, 0.3f, 0.1f)); /// canvas.addPlotToLayout(plot1.id(), layout.id()); /*hpl::sleep(1e6); canvas.setLayout(new hpl::HorizontalLayout(hpl::HorizontalLayout::RightToLeft)); for (int i = 0; i < 5; ++i) { hpl::sleep(5e5); plot2->setLineColor(0, hpl::Color( rand() / static_cast<float>(RAND_MAX), rand() / static_cast<float>(RAND_MAX), rand() / static_cast<float>(RAND_MAX) )); } hpl::sleep(1e6); canvas.setLayout(new hpl::GridLayout(2, 2, hpl::GridLayout::BottomRightToTopLeft)); hpl::ScatterPlot* plot3 = canvas.addScatterPlot(NUM_POINTS, x, y); plot3->setLegendColor(hpl::Color(0.0f, 0.0f, 0.0f)); plot3->setPointColor(0, hpl::Color(0.0f, 0.0f, 0.0f)); hpl::sleep(1e6); static_cast<hpl::GridLayout*>(canvas.getLayout())->changeOrientation(hpl::GridLayout::TopLeftToBottomRight); canvas.saveToFile("testoutput");*/ canvas.wait(); return 0; } <|endoftext|>
<commit_before>#include "LDPC_matrix_handler.hpp" using namespace aff3ct; using namespace tools; void LDPC_matrix_handler ::sparse_to_full(const Sparse_matrix& sparse, Full_matrix& full) { full.clear(); full.resize(sparse.get_n_rows(), mipp::vector<int8_t>(sparse.get_n_cols(), 0)); for (unsigned i = 0; i < sparse.get_n_rows(); i++) for (unsigned j = 0; j < sparse.get_cols_from_row(i).size(); j++) full[i][sparse.get_cols_from_row(i)[j]] = 1; } Sparse_matrix LDPC_matrix_handler ::full_to_sparse(const Full_matrix& full) { Sparse_matrix sparse(full.size(), full.front().size()); for (unsigned i = 0; i < full.size(); i++) for (unsigned j = 0; j < full[i].size(); j++) if (full[i][j]) sparse.add_connection(i,j); return sparse; } Sparse_matrix LDPC_matrix_handler ::transform_H_to_G(const Sparse_matrix& H, std::vector<unsigned>& info_bits_pos) { LDPC_matrix_handler::Full_matrix mat; if (H.get_n_rows() > H.get_n_cols()) LDPC_matrix_handler::sparse_to_full(H.transpose(), mat); else LDPC_matrix_handler::sparse_to_full(H, mat); LDPC_matrix_handler::transform_H_to_G(mat, info_bits_pos); return LDPC_matrix_handler::full_to_sparse(mat); } void LDPC_matrix_handler ::transform_H_to_G(Full_matrix& mat, std::vector<unsigned>& info_bits_pos) { unsigned n_row = (unsigned)mat.size(); unsigned n_col = (unsigned)mat.front().size(); if (n_row > n_col) throw std::length_error("aff3ct::tools::LDPC_G::transform_H_to_G: matrix high \"mat.size()\" has to be smaller " " than its width \"mat.front().size()\"."); std::vector<unsigned> swapped_cols; LDPC_matrix_handler::create_diagonal(mat, swapped_cols); LDPC_matrix_handler::create_identity(mat); for (unsigned i = 0; i < n_row; i++) // erase the just created identity in the left part of H mat[i].erase( mat[i].begin(), mat[i].begin() + n_row ); // mat dimension is now n_col*n_row (above it was n_row*n_col) mat.resize(n_col, mipp::vector<int8_t>(n_col-n_row,0)); for (unsigned i = n_row; i < n_col; i++) // Add identity at the end mat[i][i-n_row] = 1; // Re-organization: get G for (unsigned l = (unsigned)(swapped_cols.size() / 2); l > 0; l--) std::swap(mat[swapped_cols[l*2-2]], mat[swapped_cols[l*2-1]]); // return info bits positions info_bits_pos.resize(n_row); mipp::vector<unsigned> bits_pos(n_col); std::iota(bits_pos.begin(), bits_pos.begin() + n_col, 0); for (unsigned l = 1; l <= (swapped_cols.size() / 2); l++) std::swap(bits_pos[swapped_cols[l*2-2]], bits_pos[swapped_cols[l*2-1]]); std::copy(bits_pos.begin() + (n_col-n_row), bits_pos.end(), info_bits_pos.begin()); } void LDPC_matrix_handler ::create_diagonal(Full_matrix& mat, std::vector<unsigned>& swapped_cols) { unsigned n_row = (unsigned)mat.size(); unsigned n_col = (unsigned)mat.front().size(); if (n_row > n_col) throw std::length_error("aff3ct::tools::LDPC_G::create_diagonal: matrix high \"mat.size()\" has to be smaller " " than its width \"mat.front().size()\"."); unsigned i = 0; bool found = false; while (i < n_row) { if (mat[i][i]) { for (unsigned j = i +1; j < n_row; j++) if( mat[j][i] ) std::transform(mat[j].begin(), mat[j].end(), mat[i].begin(), mat[j].begin(), std::not_equal_to<int8_t>()); } else { for (unsigned j = i +1; j < n_row; j++) // find an other row which is good if (mat[j][i]) { std::swap(mat[i], mat[j]); i--; found = true; break; } if (!found) // if does not fund for (unsigned j = i +1; j < n_col; j++) // find an other column which is good if (mat[i][j]) { swapped_cols.push_back(i); swapped_cols.push_back(j); // swap the columns mipp::vector<int8_t> column_save(n_row); for (unsigned l = 0; l < n_row; l++) column_save[l] = (mat[l][i]); for (unsigned l = 0; l < n_row; l++) mat[l][i] = mat[l][j]; for (unsigned l = 0; l < n_row; l++) mat[l][j] = column_save[l]; i--; found = true; break; } if (!found) // if does not fund again this mean that the row is the null vector { mat.erase(mat.begin() +i); i--; n_row--; } found = false; } i++; } } void LDPC_matrix_handler ::create_identity(Full_matrix& mat) { unsigned n_row = (unsigned)mat.size(); unsigned n_col = (unsigned)mat.front().size(); if (n_row > n_col) throw std::length_error("aff3ct::tools::LDPC_G::create_identity: matrix high \"mat.size()\" has to be smaller " " than its width \"mat.front().size()\"."); for (unsigned i = n_row - 1 ; i > 0; i--) for (unsigned j = i; j > 0; j--) if (mat[j-1][i]) std::transform (mat[j-1].begin(), mat[j-1].end(), mat[i].begin(), mat[j-1].begin(), std::not_equal_to<int8_t>()); } float LDPC_matrix_handler ::compute_density(Full_matrix& mat) { unsigned n_rows = mat.size(); unsigned n_cols = mat.front().size(); unsigned nb_ones = 0; for (unsigned i = 0; i < n_rows; i++) for (unsigned j = 0; j < n_cols; j++) if (mat[i][j]) nb_ones++; return ((float)nb_ones/(float)(n_rows*n_cols)); } Sparse_matrix LDPC_matrix_handler ::interleave_matrix(const Sparse_matrix& mat, std::vector<unsigned>& new_cols_pos) { if (mat.get_n_cols() != new_cols_pos.size()) throw std::length_error("aff3ct::tools::LDPC_G::interleave_matrix: matrix width \"mat.get_n_cols()\" has to be" " equal to interleaver length \"new_cols_pos.size()\"."); Sparse_matrix itl_mat(mat.get_n_rows(), mat.get_n_cols()); for (unsigned i = 0; i < mat.get_n_cols(); i++) { for (unsigned j = 0; j < mat.get_rows_from_col(i).size(); j++) itl_mat.add_connection(mat.get_rows_from_col(i)[j], new_cols_pos[i]); } return itl_mat; } std::vector<unsigned> LDPC_matrix_handler ::interleave_info_bits_pos(const std::vector<unsigned>& info_bits_pos, std::vector<unsigned>& new_cols_pos) { if (info_bits_pos.size() > new_cols_pos.size()) throw std::length_error("aff3ct::tools::LDPC_G::interleave_info_bits_pos: vector length \"vec.size()\" has to" " be smaller than or equal to interleaver length \"new_cols_pos.size()\"."); std::vector<unsigned> itl_vec(info_bits_pos.size()); for (unsigned i = 0; i < info_bits_pos.size(); i++) { itl_vec[i] = new_cols_pos[info_bits_pos[i]]; } return itl_vec; } <commit_msg>Fix compilation error on MSVC.<commit_after>#include <functional> #include "LDPC_matrix_handler.hpp" using namespace aff3ct; using namespace tools; void LDPC_matrix_handler ::sparse_to_full(const Sparse_matrix& sparse, Full_matrix& full) { full.clear(); full.resize(sparse.get_n_rows(), mipp::vector<int8_t>(sparse.get_n_cols(), 0)); for (unsigned i = 0; i < sparse.get_n_rows(); i++) for (unsigned j = 0; j < sparse.get_cols_from_row(i).size(); j++) full[i][sparse.get_cols_from_row(i)[j]] = 1; } Sparse_matrix LDPC_matrix_handler ::full_to_sparse(const Full_matrix& full) { Sparse_matrix sparse(full.size(), full.front().size()); for (unsigned i = 0; i < full.size(); i++) for (unsigned j = 0; j < full[i].size(); j++) if (full[i][j]) sparse.add_connection(i,j); return sparse; } Sparse_matrix LDPC_matrix_handler ::transform_H_to_G(const Sparse_matrix& H, std::vector<unsigned>& info_bits_pos) { LDPC_matrix_handler::Full_matrix mat; if (H.get_n_rows() > H.get_n_cols()) LDPC_matrix_handler::sparse_to_full(H.transpose(), mat); else LDPC_matrix_handler::sparse_to_full(H, mat); LDPC_matrix_handler::transform_H_to_G(mat, info_bits_pos); return LDPC_matrix_handler::full_to_sparse(mat); } void LDPC_matrix_handler ::transform_H_to_G(Full_matrix& mat, std::vector<unsigned>& info_bits_pos) { unsigned n_row = (unsigned)mat.size(); unsigned n_col = (unsigned)mat.front().size(); if (n_row > n_col) throw std::length_error("aff3ct::tools::LDPC_G::transform_H_to_G: matrix high \"mat.size()\" has to be smaller " " than its width \"mat.front().size()\"."); std::vector<unsigned> swapped_cols; LDPC_matrix_handler::create_diagonal(mat, swapped_cols); LDPC_matrix_handler::create_identity(mat); for (unsigned i = 0; i < n_row; i++) // erase the just created identity in the left part of H mat[i].erase( mat[i].begin(), mat[i].begin() + n_row ); // mat dimension is now n_col*n_row (above it was n_row*n_col) mat.resize(n_col, mipp::vector<int8_t>(n_col-n_row,0)); for (unsigned i = n_row; i < n_col; i++) // Add identity at the end mat[i][i-n_row] = 1; // Re-organization: get G for (unsigned l = (unsigned)(swapped_cols.size() / 2); l > 0; l--) std::swap(mat[swapped_cols[l*2-2]], mat[swapped_cols[l*2-1]]); // return info bits positions info_bits_pos.resize(n_row); mipp::vector<unsigned> bits_pos(n_col); std::iota(bits_pos.begin(), bits_pos.begin() + n_col, 0); for (unsigned l = 1; l <= (swapped_cols.size() / 2); l++) std::swap(bits_pos[swapped_cols[l*2-2]], bits_pos[swapped_cols[l*2-1]]); std::copy(bits_pos.begin() + (n_col-n_row), bits_pos.end(), info_bits_pos.begin()); } void LDPC_matrix_handler ::create_diagonal(Full_matrix& mat, std::vector<unsigned>& swapped_cols) { unsigned n_row = (unsigned)mat.size(); unsigned n_col = (unsigned)mat.front().size(); if (n_row > n_col) throw std::length_error("aff3ct::tools::LDPC_G::create_diagonal: matrix high \"mat.size()\" has to be smaller " " than its width \"mat.front().size()\"."); unsigned i = 0; bool found = false; while (i < n_row) { if (mat[i][i]) { for (unsigned j = i +1; j < n_row; j++) if( mat[j][i] ) std::transform(mat[j].begin(), mat[j].end(), mat[i].begin(), mat[j].begin(), std::not_equal_to<int8_t>()); } else { for (unsigned j = i +1; j < n_row; j++) // find an other row which is good if (mat[j][i]) { std::swap(mat[i], mat[j]); i--; found = true; break; } if (!found) // if does not fund for (unsigned j = i +1; j < n_col; j++) // find an other column which is good if (mat[i][j]) { swapped_cols.push_back(i); swapped_cols.push_back(j); // swap the columns mipp::vector<int8_t> column_save(n_row); for (unsigned l = 0; l < n_row; l++) column_save[l] = (mat[l][i]); for (unsigned l = 0; l < n_row; l++) mat[l][i] = mat[l][j]; for (unsigned l = 0; l < n_row; l++) mat[l][j] = column_save[l]; i--; found = true; break; } if (!found) // if does not fund again this mean that the row is the null vector { mat.erase(mat.begin() +i); i--; n_row--; } found = false; } i++; } } void LDPC_matrix_handler ::create_identity(Full_matrix& mat) { unsigned n_row = (unsigned)mat.size(); unsigned n_col = (unsigned)mat.front().size(); if (n_row > n_col) throw std::length_error("aff3ct::tools::LDPC_G::create_identity: matrix high \"mat.size()\" has to be smaller " " than its width \"mat.front().size()\"."); for (unsigned i = n_row - 1 ; i > 0; i--) for (unsigned j = i; j > 0; j--) if (mat[j-1][i]) std::transform (mat[j-1].begin(), mat[j-1].end(), mat[i].begin(), mat[j-1].begin(), std::not_equal_to<int8_t>()); } float LDPC_matrix_handler ::compute_density(Full_matrix& mat) { unsigned n_rows = mat.size(); unsigned n_cols = mat.front().size(); unsigned nb_ones = 0; for (unsigned i = 0; i < n_rows; i++) for (unsigned j = 0; j < n_cols; j++) if (mat[i][j]) nb_ones++; return ((float)nb_ones/(float)(n_rows*n_cols)); } Sparse_matrix LDPC_matrix_handler ::interleave_matrix(const Sparse_matrix& mat, std::vector<unsigned>& new_cols_pos) { if (mat.get_n_cols() != new_cols_pos.size()) throw std::length_error("aff3ct::tools::LDPC_G::interleave_matrix: matrix width \"mat.get_n_cols()\" has to be" " equal to interleaver length \"new_cols_pos.size()\"."); Sparse_matrix itl_mat(mat.get_n_rows(), mat.get_n_cols()); for (unsigned i = 0; i < mat.get_n_cols(); i++) { for (unsigned j = 0; j < mat.get_rows_from_col(i).size(); j++) itl_mat.add_connection(mat.get_rows_from_col(i)[j], new_cols_pos[i]); } return itl_mat; } std::vector<unsigned> LDPC_matrix_handler ::interleave_info_bits_pos(const std::vector<unsigned>& info_bits_pos, std::vector<unsigned>& new_cols_pos) { if (info_bits_pos.size() > new_cols_pos.size()) throw std::length_error("aff3ct::tools::LDPC_G::interleave_info_bits_pos: vector length \"vec.size()\" has to" " be smaller than or equal to interleaver length \"new_cols_pos.size()\"."); std::vector<unsigned> itl_vec(info_bits_pos.size()); for (unsigned i = 0; i < info_bits_pos.size(); i++) { itl_vec[i] = new_cols_pos[info_bits_pos[i]]; } return itl_vec; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/cpp/resource.h" #include <algorithm> #include "ppapi/cpp/logging.h" #include "ppapi/cpp/module.h" namespace pp { Resource::Resource() : pp_resource_(0) { } Resource::Resource(const Resource& other) : pp_resource_(other.pp_resource_) { if (!is_null()) Module::Get()->core()->AddRefResource(pp_resource_); } Resource::~Resource() { if (!is_null()) Module::Get()->core()->ReleaseResource(pp_resource_); } Resource& Resource::operator=(const Resource& other) { if (!is_null()) Module::Get()->core()->ReleaseResource(pp_resource_); pp_resource_ = other.pp_resource_; if (!is_null()) Module::Get()->core()->AddRefResource(pp_resource_); return *this; } PP_Resource Resource::detach() { PP_Resource ret = pp_resource_; pp_resource_ = 0; return ret; } Resource::Resource(PP_Resource resource) : pp_resource_(resource) { if (!is_null()) Module::Get()->core()->AddRefResource(pp_resource_); } void Resource::PassRefFromConstructor(PP_Resource resource) { PP_DCHECK(!pp_resource_); pp_resource_ = resource; } } // namespace pp <commit_msg>Fix self-assignment in pp::Resource<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/cpp/resource.h" #include <algorithm> #include "ppapi/cpp/logging.h" #include "ppapi/cpp/module.h" namespace pp { Resource::Resource() : pp_resource_(0) { } Resource::Resource(const Resource& other) : pp_resource_(other.pp_resource_) { if (!is_null()) Module::Get()->core()->AddRefResource(pp_resource_); } Resource::~Resource() { if (!is_null()) Module::Get()->core()->ReleaseResource(pp_resource_); } Resource& Resource::operator=(const Resource& other) { if (!other.is_null()) Module::Get()->core()->AddRefResource(other.pp_resource_); if (!is_null()) Module::Get()->core()->ReleaseResource(pp_resource_); pp_resource_ = other.pp_resource_; return *this; } PP_Resource Resource::detach() { PP_Resource ret = pp_resource_; pp_resource_ = 0; return ret; } Resource::Resource(PP_Resource resource) : pp_resource_(resource) { if (!is_null()) Module::Get()->core()->AddRefResource(pp_resource_); } void Resource::PassRefFromConstructor(PP_Resource resource) { PP_DCHECK(!pp_resource_); pp_resource_ = resource; } } // namespace pp <|endoftext|>
<commit_before>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include <armnn/Tensor.hpp> #include <boost/assert.hpp> namespace armnn { // Utility class providing access to raw tensor memory based on indices along each dimension. template <typename DataType> class TensorBufferArrayView { public: TensorBufferArrayView(const TensorShape& shape, DataType* data, DataLayoutIndexed dataLayout = DataLayout::NCHW) : m_Shape(shape) , m_Data(data) , m_DataLayout(dataLayout) { } DataType& Get(unsigned int b, unsigned int c, unsigned int h, unsigned int w) const { BOOST_ASSERT( b < m_Shape[0] || ( m_Shape[0] == 0 && b == 0 ) ); BOOST_ASSERT( c < m_Shape[m_DataLayout.GetChannelsIndex()] || ( m_Shape[m_DataLayout.GetChannelsIndex()] == 0 && c == 0) ); BOOST_ASSERT( h < m_Shape[m_DataLayout.GetHeightIndex()] || ( m_Shape[m_DataLayout.GetHeightIndex()] == 0 && h == 0) ); BOOST_ASSERT( w < m_Shape[m_DataLayout.GetWidthIndex()] || ( m_Shape[m_DataLayout.GetWidthIndex()] == 0 && w == 0) ); return m_Data[b * m_Shape[1] * m_Shape[2] * m_Shape[3] + c * m_Shape[m_DataLayout.GetHeightIndex()] * m_Shape[m_DataLayout.GetWidthIndex()] + h * m_Shape[m_DataLayout.GetWidthIndex()] + w]; } private: const TensorShape m_Shape; DataType* m_Data; DataLayoutIndexed m_DataLayout; }; } //namespace armnn <commit_msg>IVGCVSW-2018 Support NHWC in the current ref implementation<commit_after>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include <armnn/Tensor.hpp> #include <boost/assert.hpp> namespace armnn { // Utility class providing access to raw tensor memory based on indices along each dimension. template <typename DataType> class TensorBufferArrayView { public: TensorBufferArrayView(const TensorShape& shape, DataType* data, DataLayoutIndexed dataLayout = DataLayout::NCHW) : m_Shape(shape) , m_Data(data) , m_DataLayout(dataLayout) { BOOST_ASSERT(m_Shape.GetNumDimensions() == 4); } DataType& Get(unsigned int b, unsigned int c, unsigned int h, unsigned int w) const { BOOST_ASSERT( b < m_Shape[0] || ( m_Shape[0] == 0 && b == 0 ) ); BOOST_ASSERT( c < m_Shape[m_DataLayout.GetChannelsIndex()] || ( m_Shape[m_DataLayout.GetChannelsIndex()] == 0 && c == 0) ); BOOST_ASSERT( h < m_Shape[m_DataLayout.GetHeightIndex()] || ( m_Shape[m_DataLayout.GetHeightIndex()] == 0 && h == 0) ); BOOST_ASSERT( w < m_Shape[m_DataLayout.GetWidthIndex()] || ( m_Shape[m_DataLayout.GetWidthIndex()] == 0 && w == 0) ); // Offset the given indices appropriately depending on the data layout. switch (m_DataLayout.GetDataLayout()) { case DataLayout::NHWC: b *= m_Shape[1] * m_Shape[2] * m_Shape[3]; // b *= height_index * width_index * channel_index; h *= m_Shape[m_DataLayout.GetWidthIndex()] * m_Shape[m_DataLayout.GetChannelsIndex()]; w *= m_Shape[m_DataLayout.GetChannelsIndex()]; // c stays unchanged break; case DataLayout::NCHW: default: b *= m_Shape[1] * m_Shape[2] * m_Shape[3]; // b *= height_index * width_index * channel_index; c *= m_Shape[m_DataLayout.GetHeightIndex()] * m_Shape[m_DataLayout.GetWidthIndex()]; h *= m_Shape[m_DataLayout.GetWidthIndex()]; // w stays unchanged break; } // Get the value using the correct offset. return m_Data[b + c + h + w]; } private: const TensorShape m_Shape; DataType* m_Data; DataLayoutIndexed m_DataLayout; }; } //namespace armnn <|endoftext|>
<commit_before>/* behaviorconfig.cpp - Kopete Look Feel Config Kopete (c) 2002-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "behaviorconfig.h" #include "behaviorconfig_general.h" #include "behaviorconfig_events.h" #include "behaviorconfig_chat.h" #include <qcheckbox.h> #include <qradiobutton.h> #include <qlayout.h> #include <qlabel.h> #include <qhbuttongroup.h> #include <qspinbox.h> #include <qcombobox.h> #include <kdebug.h> #include <kplugininfo.h> #include <klocale.h> #include <kpushbutton.h> #include <kgenericfactory.h> #include <ktrader.h> #include <kconfig.h> #include "kopeteprefs.h" #include "kopeteaway.h" #include "kopeteawayconfigbase.h" #include "kopetepluginmanager.h" #include <qtabwidget.h> typedef KGenericFactory<BehaviorConfig, QWidget> KopeteBehaviorConfigFactory; K_EXPORT_COMPONENT_FACTORY( kcm_kopete_behaviorconfig, KopeteBehaviorConfigFactory( "kcm_kopete_behaviorconfig" ) ) BehaviorConfig::BehaviorConfig(QWidget *parent, const char * /* name */, const QStringList &args) : KCModule( KopeteBehaviorConfigFactory::instance(), parent, args ) { (new QVBoxLayout(this))->setAutoAdd(true); mBehaviorTabCtl = new QTabWidget(this, "mBehaviorTabCtl"); // "General" TAB ============================================================ mPrfsGeneral = new BehaviorConfig_General(mBehaviorTabCtl); mBehaviorTabCtl->addTab(mPrfsGeneral, i18n("&General")); // "Events" TAB ============================================================ mPrfsEvents = new BehaviorConfig_Events(mBehaviorTabCtl); mBehaviorTabCtl->addTab(mPrfsEvents, i18n("&Events")); // "Away" TAB =============================================================== mAwayConfigUI = new KopeteAwayConfigBaseUI(mBehaviorTabCtl); mBehaviorTabCtl->addTab(mAwayConfigUI, i18n("A&way Settings")); // "Chat" TAB =============================================================== mPrfsChat = new BehaviorConfig_Chat(mBehaviorTabCtl); mBehaviorTabCtl->addTab(mPrfsChat, i18n("Cha&t")); Kopete::PluginManager *pluginManager = Kopete::PluginManager::self(); viewPlugins = pluginManager->availablePlugins("Views"); load(); // "General" TAB ============================================================ connect(mPrfsGeneral->mShowTrayChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mStartDockedChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mUseQueueChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mUseStackChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mQueueUnreadMessagesChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mAutoConnect, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mMouseNavigation, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); // "Events" TAB ============================================================ connect(mPrfsEvents->mQueueOnlyHighlightedMessagesInGroupChatsChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mQueueOnlyMessagesOnAnotherDesktopChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mBalloonNotifyChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mBalloonNotifyIgnoreClosesChatViewChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mCloseBalloonChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mBalloonCloseDelay, SIGNAL(valueChanged(int)), this, SLOT(slotValueChanged(int))); connect(mPrfsEvents->mTrayflashNotifyChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mTrayflashNotifyLeftClickOpensMessageChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mTrayflashNotifySetCurrentDesktopToChatViewChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mSoundIfAwayChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mEventIfActive, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mRaiseMsgWindowChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); // "Chat" TAB =============================================================== connect( mPrfsChat->cb_ShowEventsChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect( mPrfsChat->highlightEnabled, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect( mPrfsChat->cb_SpellCheckChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect( mPrfsChat->cmbChatGroupingPolicy, SIGNAL(activated(int)), this, SLOT(slotValueChanged(int))); connect( mPrfsChat->mChatViewBufferSize, SIGNAL(valueChanged(int)), this, SLOT(slotValueChanged(int))); connect( mPrfsChat->truncateContactNameEnabled, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect( mPrfsChat->mMaxContactNameLength, SIGNAL(valueChanged(int)), this, SLOT(slotValueChanged(int))); connect( mPrfsChat->viewPlugin, SIGNAL(activated(int)), this, SLOT(slotValueChanged(int))); connect( mPrfsChat->viewPlugin, SIGNAL(activated(int)), this, SLOT(slotUpdatePluginLabel(int))); // "Away" TAB =============================================================== connect( mAwayConfigUI->mAutoAwayTimeout, SIGNAL(valueChanged(int)), this, SLOT(slotValueChanged(int))); connect( mAwayConfigUI->mGoAvailable, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect( mAwayConfigUI->mUseAutoAway, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); } void BehaviorConfig::save() { // kdDebug(14000) << k_funcinfo << "called." << endl; KopetePrefs *p = KopetePrefs::prefs(); KConfig *config = KGlobal::config(); // "General" TAB ============================================================ p->setShowTray(mPrfsGeneral->mShowTrayChk->isChecked()); p->setStartDocked(mPrfsGeneral->mStartDockedChk->isChecked()); p->setUseQueue(mPrfsGeneral->mUseQueueChk->isChecked()); p->setUseStack(mPrfsGeneral->mUseStackChk->isChecked()); p->setQueueUnreadMessages(mPrfsGeneral->mQueueUnreadMessagesChk->isChecked()); p->setAutoConnect(mPrfsGeneral->mAutoConnect->isChecked()); p->setContactListMouseNavigation(mPrfsGeneral->mMouseNavigation->isChecked()); // "Events" TAB ============================================================ p->setQueueOnlyHighlightedMessagesInGroupChats(mPrfsEvents->mQueueOnlyHighlightedMessagesInGroupChatsChk->isChecked()); p->setQueueOnlyMessagesOnAnotherDesktop(mPrfsEvents->mQueueOnlyMessagesOnAnotherDesktopChk->isChecked()); p->setBalloonNotify(mPrfsEvents->mBalloonNotifyChk->isChecked()); p->setBalloonNotifyIgnoreClosesChatView(mPrfsEvents->mBalloonNotifyIgnoreClosesChatViewChk->isChecked()); p->setBalloonClose(mPrfsEvents->mCloseBalloonChk->isChecked()); p->setBalloonDelay(mPrfsEvents->mBalloonCloseDelay->value()); p->setTrayflashNotify(mPrfsEvents->mTrayflashNotifyChk->isChecked()); p->setTrayflashNotifyLeftClickOpensMessage(mPrfsEvents->mTrayflashNotifyLeftClickOpensMessageChk->isChecked()); p->setTrayflashNotifySetCurrentDesktopToChatView(mPrfsEvents->mTrayflashNotifySetCurrentDesktopToChatViewChk->isChecked()); p->setSoundIfAway(mPrfsEvents->mSoundIfAwayChk->isChecked()); p->setRaiseMsgWindow(mPrfsEvents->mRaiseMsgWindowChk->isChecked()); config->setGroup("General"); config->writeEntry("EventIfActive", mPrfsEvents->mEventIfActive->isChecked()); // "Away" TAB =============================================================== p->setRememberedMessages( mAwayConfigUI->rememberedMessages->value() ); config->setGroup("AutoAway"); config->writeEntry("Timeout", mAwayConfigUI->mAutoAwayTimeout->value() * 60); config->writeEntry("GoAvailable", mAwayConfigUI->mGoAvailable->isChecked()); config->writeEntry("UseAutoAway", mAwayConfigUI->mUseAutoAway->isChecked() ); config->sync(); // "Chat" TAB =============================================================== p->setShowEvents(mPrfsChat->cb_ShowEventsChk->isChecked()); p->setHighlightEnabled(mPrfsChat->highlightEnabled->isChecked()); p->setSpellCheck(mPrfsChat->cb_SpellCheckChk->isChecked()); p->setInterfacePreference( viewPlugins[mPrfsChat->viewPlugin->currentItem()]->pluginName() ); p->setChatWindowPolicy(mPrfsChat->cmbChatGroupingPolicy->currentItem()); p->setChatViewBufferSize(mPrfsChat->mChatViewBufferSize->value()); p->setTruncateContactNames(mPrfsChat->truncateContactNameEnabled->isChecked()); p->setMaxContactNameLength(mPrfsChat->mMaxContactNameLength->value()); p->save(); emit changed(false); } void BehaviorConfig::load() { // kdDebug(14000) << k_funcinfo << "called" << endl; KopetePrefs *p = KopetePrefs::prefs(); KConfig *config = KGlobal::config(); // "General" TAB ============================================================ mPrfsGeneral->mShowTrayChk->setChecked( p->showTray() ); mPrfsGeneral->mStartDockedChk->setChecked( p->startDocked() ); mPrfsGeneral->mUseQueueChk->setChecked( p->useQueue() ); mPrfsGeneral->mUseStackChk->setChecked( p->useStack() ); mPrfsGeneral->mQueueUnreadMessagesChk->setChecked ( p->queueUnreadMessages() ); mPrfsGeneral->mAutoConnect->setChecked( p->autoConnect() ); mPrfsGeneral->mMouseNavigation->setChecked( p->contactListMouseNavigation() ); // "Events" TAB ============================================================ mPrfsEvents->mQueueOnlyHighlightedMessagesInGroupChatsChk->setChecked ( p->queueOnlyHighlightedMessagesInGroupChats() ); mPrfsEvents->mQueueOnlyMessagesOnAnotherDesktopChk->setChecked ( p->queueOnlyMessagesOnAnotherDesktop() ); mPrfsEvents->mBalloonNotifyChk->setChecked ( p->balloonNotify() ); mPrfsEvents->mBalloonNotifyIgnoreClosesChatViewChk->setChecked ( p->balloonNotifyIgnoreClosesChatView() ); mPrfsEvents->mCloseBalloonChk->setChecked( p->balloonClose() ); mPrfsEvents->mBalloonCloseDelay->setValue( p->balloonCloseDelay() ); mPrfsEvents->mTrayflashNotifyChk->setChecked ( p->trayflashNotify() ); mPrfsEvents->mTrayflashNotifyLeftClickOpensMessageChk->setChecked ( p->trayflashNotifyLeftClickOpensMessage() ); mPrfsEvents->mTrayflashNotifySetCurrentDesktopToChatViewChk->setChecked ( p->trayflashNotifySetCurrentDesktopToChatView() ); mPrfsEvents->mSoundIfAwayChk->setChecked( p->soundIfAway() ); mPrfsEvents->mRaiseMsgWindowChk->setChecked(p->raiseMsgWindow()); config->setGroup("General"); mPrfsEvents->mEventIfActive->setChecked(config->readBoolEntry("EventIfActive", true)); // "Away" TAB =============================================================== config->setGroup("AutoAway"); mAwayConfigUI->mAutoAwayTimeout->setValue(config->readNumEntry("Timeout", 600)/60); mAwayConfigUI->mGoAvailable->setChecked(config->readBoolEntry("GoAvailable", true)); mAwayConfigUI->mUseAutoAway->setChecked(config->readBoolEntry("UseAutoAway", true)); mAwayConfigUI->rememberedMessages->setValue( p->rememberedMessages() ); // "Chat" TAB =============================================================== mPrfsChat->cb_ShowEventsChk->setChecked(p->showEvents()); mPrfsChat->highlightEnabled->setChecked(p->highlightEnabled()); mPrfsChat->cb_SpellCheckChk->setChecked(p->spellCheck()); mPrfsChat->cmbChatGroupingPolicy->setCurrentItem(p->chatWindowPolicy()); mPrfsChat->mChatViewBufferSize->setValue(p->chatViewBufferSize()); mPrfsChat->truncateContactNameEnabled->setChecked(p->truncateContactNames()); mPrfsChat->mMaxContactNameLength->setValue(p->maxConactNameLength()); mPrfsChat->viewPlugin->clear(); int selectedIdx = 0, i = 0; for( QValueList<KPluginInfo*>::iterator it = viewPlugins.begin(); it != viewPlugins.end(); ++it ) { if( (*it)->pluginName() == p->interfacePreference() ) selectedIdx = i; mPrfsChat->viewPlugin->insertItem( (*it)->name(), i++ ); } mPrfsChat->viewPlugin->setCurrentItem(selectedIdx); slotUpdatePluginLabel(selectedIdx); } void BehaviorConfig::slotUpdatePluginLabel(int) { mPrfsChat->viewPluginLabel->setText( viewPlugins[ mPrfsChat->viewPlugin->currentItem() ]->comment() ); } void BehaviorConfig::slotSettingsChanged(bool) { emit changed(true); } void BehaviorConfig::slotValueChanged(int) { emit changed( true ); } #include "behaviorconfig.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>Fix Bug 123259: "Remember Away Messages" spinbox not connected to Apply button Patch from the reporter of the bug. Thanks<commit_after>/* behaviorconfig.cpp - Kopete Look Feel Config Kopete (c) 2002-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "behaviorconfig.h" #include "behaviorconfig_general.h" #include "behaviorconfig_events.h" #include "behaviorconfig_chat.h" #include <qcheckbox.h> #include <qradiobutton.h> #include <qlayout.h> #include <qlabel.h> #include <qhbuttongroup.h> #include <qspinbox.h> #include <qcombobox.h> #include <kdebug.h> #include <kplugininfo.h> #include <klocale.h> #include <kpushbutton.h> #include <kgenericfactory.h> #include <ktrader.h> #include <kconfig.h> #include "kopeteprefs.h" #include "kopeteaway.h" #include "kopeteawayconfigbase.h" #include "kopetepluginmanager.h" #include <qtabwidget.h> typedef KGenericFactory<BehaviorConfig, QWidget> KopeteBehaviorConfigFactory; K_EXPORT_COMPONENT_FACTORY( kcm_kopete_behaviorconfig, KopeteBehaviorConfigFactory( "kcm_kopete_behaviorconfig" ) ) BehaviorConfig::BehaviorConfig(QWidget *parent, const char * /* name */, const QStringList &args) : KCModule( KopeteBehaviorConfigFactory::instance(), parent, args ) { (new QVBoxLayout(this))->setAutoAdd(true); mBehaviorTabCtl = new QTabWidget(this, "mBehaviorTabCtl"); // "General" TAB ============================================================ mPrfsGeneral = new BehaviorConfig_General(mBehaviorTabCtl); mBehaviorTabCtl->addTab(mPrfsGeneral, i18n("&General")); // "Events" TAB ============================================================ mPrfsEvents = new BehaviorConfig_Events(mBehaviorTabCtl); mBehaviorTabCtl->addTab(mPrfsEvents, i18n("&Events")); // "Away" TAB =============================================================== mAwayConfigUI = new KopeteAwayConfigBaseUI(mBehaviorTabCtl); mBehaviorTabCtl->addTab(mAwayConfigUI, i18n("A&way Settings")); // "Chat" TAB =============================================================== mPrfsChat = new BehaviorConfig_Chat(mBehaviorTabCtl); mBehaviorTabCtl->addTab(mPrfsChat, i18n("Cha&t")); Kopete::PluginManager *pluginManager = Kopete::PluginManager::self(); viewPlugins = pluginManager->availablePlugins("Views"); load(); // "General" TAB ============================================================ connect(mPrfsGeneral->mShowTrayChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mStartDockedChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mUseQueueChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mUseStackChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mQueueUnreadMessagesChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mAutoConnect, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsGeneral->mMouseNavigation, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); // "Events" TAB ============================================================ connect(mPrfsEvents->mQueueOnlyHighlightedMessagesInGroupChatsChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mQueueOnlyMessagesOnAnotherDesktopChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mBalloonNotifyChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mBalloonNotifyIgnoreClosesChatViewChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mCloseBalloonChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mBalloonCloseDelay, SIGNAL(valueChanged(int)), this, SLOT(slotValueChanged(int))); connect(mPrfsEvents->mTrayflashNotifyChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mTrayflashNotifyLeftClickOpensMessageChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mTrayflashNotifySetCurrentDesktopToChatViewChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mSoundIfAwayChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mEventIfActive, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect(mPrfsEvents->mRaiseMsgWindowChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); // "Chat" TAB =============================================================== connect( mPrfsChat->cb_ShowEventsChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect( mPrfsChat->highlightEnabled, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect( mPrfsChat->cb_SpellCheckChk, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect( mPrfsChat->cmbChatGroupingPolicy, SIGNAL(activated(int)), this, SLOT(slotValueChanged(int))); connect( mPrfsChat->mChatViewBufferSize, SIGNAL(valueChanged(int)), this, SLOT(slotValueChanged(int))); connect( mPrfsChat->truncateContactNameEnabled, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect( mPrfsChat->mMaxContactNameLength, SIGNAL(valueChanged(int)), this, SLOT(slotValueChanged(int))); connect( mPrfsChat->viewPlugin, SIGNAL(activated(int)), this, SLOT(slotValueChanged(int))); connect( mPrfsChat->viewPlugin, SIGNAL(activated(int)), this, SLOT(slotUpdatePluginLabel(int))); // "Away" TAB =============================================================== connect( mAwayConfigUI->rememberedMessages, SIGNAL(valueChanged(int)), this, SLOT(slotValueChanged(int))); connect( mAwayConfigUI->mAutoAwayTimeout, SIGNAL(valueChanged(int)), this, SLOT(slotValueChanged(int))); connect( mAwayConfigUI->mGoAvailable, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); connect( mAwayConfigUI->mUseAutoAway, SIGNAL(toggled(bool)), this, SLOT(slotSettingsChanged(bool))); } void BehaviorConfig::save() { // kdDebug(14000) << k_funcinfo << "called." << endl; KopetePrefs *p = KopetePrefs::prefs(); KConfig *config = KGlobal::config(); // "General" TAB ============================================================ p->setShowTray(mPrfsGeneral->mShowTrayChk->isChecked()); p->setStartDocked(mPrfsGeneral->mStartDockedChk->isChecked()); p->setUseQueue(mPrfsGeneral->mUseQueueChk->isChecked()); p->setUseStack(mPrfsGeneral->mUseStackChk->isChecked()); p->setQueueUnreadMessages(mPrfsGeneral->mQueueUnreadMessagesChk->isChecked()); p->setAutoConnect(mPrfsGeneral->mAutoConnect->isChecked()); p->setContactListMouseNavigation(mPrfsGeneral->mMouseNavigation->isChecked()); // "Events" TAB ============================================================ p->setQueueOnlyHighlightedMessagesInGroupChats(mPrfsEvents->mQueueOnlyHighlightedMessagesInGroupChatsChk->isChecked()); p->setQueueOnlyMessagesOnAnotherDesktop(mPrfsEvents->mQueueOnlyMessagesOnAnotherDesktopChk->isChecked()); p->setBalloonNotify(mPrfsEvents->mBalloonNotifyChk->isChecked()); p->setBalloonNotifyIgnoreClosesChatView(mPrfsEvents->mBalloonNotifyIgnoreClosesChatViewChk->isChecked()); p->setBalloonClose(mPrfsEvents->mCloseBalloonChk->isChecked()); p->setBalloonDelay(mPrfsEvents->mBalloonCloseDelay->value()); p->setTrayflashNotify(mPrfsEvents->mTrayflashNotifyChk->isChecked()); p->setTrayflashNotifyLeftClickOpensMessage(mPrfsEvents->mTrayflashNotifyLeftClickOpensMessageChk->isChecked()); p->setTrayflashNotifySetCurrentDesktopToChatView(mPrfsEvents->mTrayflashNotifySetCurrentDesktopToChatViewChk->isChecked()); p->setSoundIfAway(mPrfsEvents->mSoundIfAwayChk->isChecked()); p->setRaiseMsgWindow(mPrfsEvents->mRaiseMsgWindowChk->isChecked()); config->setGroup("General"); config->writeEntry("EventIfActive", mPrfsEvents->mEventIfActive->isChecked()); // "Away" TAB =============================================================== p->setRememberedMessages( mAwayConfigUI->rememberedMessages->value() ); config->setGroup("AutoAway"); config->writeEntry("Timeout", mAwayConfigUI->mAutoAwayTimeout->value() * 60); config->writeEntry("GoAvailable", mAwayConfigUI->mGoAvailable->isChecked()); config->writeEntry("UseAutoAway", mAwayConfigUI->mUseAutoAway->isChecked() ); config->sync(); // "Chat" TAB =============================================================== p->setShowEvents(mPrfsChat->cb_ShowEventsChk->isChecked()); p->setHighlightEnabled(mPrfsChat->highlightEnabled->isChecked()); p->setSpellCheck(mPrfsChat->cb_SpellCheckChk->isChecked()); p->setInterfacePreference( viewPlugins[mPrfsChat->viewPlugin->currentItem()]->pluginName() ); p->setChatWindowPolicy(mPrfsChat->cmbChatGroupingPolicy->currentItem()); p->setChatViewBufferSize(mPrfsChat->mChatViewBufferSize->value()); p->setTruncateContactNames(mPrfsChat->truncateContactNameEnabled->isChecked()); p->setMaxContactNameLength(mPrfsChat->mMaxContactNameLength->value()); p->save(); emit changed(false); } void BehaviorConfig::load() { // kdDebug(14000) << k_funcinfo << "called" << endl; KopetePrefs *p = KopetePrefs::prefs(); KConfig *config = KGlobal::config(); // "General" TAB ============================================================ mPrfsGeneral->mShowTrayChk->setChecked( p->showTray() ); mPrfsGeneral->mStartDockedChk->setChecked( p->startDocked() ); mPrfsGeneral->mUseQueueChk->setChecked( p->useQueue() ); mPrfsGeneral->mUseStackChk->setChecked( p->useStack() ); mPrfsGeneral->mQueueUnreadMessagesChk->setChecked ( p->queueUnreadMessages() ); mPrfsGeneral->mAutoConnect->setChecked( p->autoConnect() ); mPrfsGeneral->mMouseNavigation->setChecked( p->contactListMouseNavigation() ); // "Events" TAB ============================================================ mPrfsEvents->mQueueOnlyHighlightedMessagesInGroupChatsChk->setChecked ( p->queueOnlyHighlightedMessagesInGroupChats() ); mPrfsEvents->mQueueOnlyMessagesOnAnotherDesktopChk->setChecked ( p->queueOnlyMessagesOnAnotherDesktop() ); mPrfsEvents->mBalloonNotifyChk->setChecked ( p->balloonNotify() ); mPrfsEvents->mBalloonNotifyIgnoreClosesChatViewChk->setChecked ( p->balloonNotifyIgnoreClosesChatView() ); mPrfsEvents->mCloseBalloonChk->setChecked( p->balloonClose() ); mPrfsEvents->mBalloonCloseDelay->setValue( p->balloonCloseDelay() ); mPrfsEvents->mTrayflashNotifyChk->setChecked ( p->trayflashNotify() ); mPrfsEvents->mTrayflashNotifyLeftClickOpensMessageChk->setChecked ( p->trayflashNotifyLeftClickOpensMessage() ); mPrfsEvents->mTrayflashNotifySetCurrentDesktopToChatViewChk->setChecked ( p->trayflashNotifySetCurrentDesktopToChatView() ); mPrfsEvents->mSoundIfAwayChk->setChecked( p->soundIfAway() ); mPrfsEvents->mRaiseMsgWindowChk->setChecked(p->raiseMsgWindow()); config->setGroup("General"); mPrfsEvents->mEventIfActive->setChecked(config->readBoolEntry("EventIfActive", true)); // "Away" TAB =============================================================== config->setGroup("AutoAway"); mAwayConfigUI->mAutoAwayTimeout->setValue(config->readNumEntry("Timeout", 600)/60); mAwayConfigUI->mGoAvailable->setChecked(config->readBoolEntry("GoAvailable", true)); mAwayConfigUI->mUseAutoAway->setChecked(config->readBoolEntry("UseAutoAway", true)); mAwayConfigUI->rememberedMessages->setValue( p->rememberedMessages() ); // "Chat" TAB =============================================================== mPrfsChat->cb_ShowEventsChk->setChecked(p->showEvents()); mPrfsChat->highlightEnabled->setChecked(p->highlightEnabled()); mPrfsChat->cb_SpellCheckChk->setChecked(p->spellCheck()); mPrfsChat->cmbChatGroupingPolicy->setCurrentItem(p->chatWindowPolicy()); mPrfsChat->mChatViewBufferSize->setValue(p->chatViewBufferSize()); mPrfsChat->truncateContactNameEnabled->setChecked(p->truncateContactNames()); mPrfsChat->mMaxContactNameLength->setValue(p->maxConactNameLength()); mPrfsChat->viewPlugin->clear(); int selectedIdx = 0, i = 0; for( QValueList<KPluginInfo*>::iterator it = viewPlugins.begin(); it != viewPlugins.end(); ++it ) { if( (*it)->pluginName() == p->interfacePreference() ) selectedIdx = i; mPrfsChat->viewPlugin->insertItem( (*it)->name(), i++ ); } mPrfsChat->viewPlugin->setCurrentItem(selectedIdx); slotUpdatePluginLabel(selectedIdx); } void BehaviorConfig::slotUpdatePluginLabel(int) { mPrfsChat->viewPluginLabel->setText( viewPlugins[ mPrfsChat->viewPlugin->currentItem() ]->comment() ); } void BehaviorConfig::slotSettingsChanged(bool) { emit changed(true); } void BehaviorConfig::slotValueChanged(int) { emit changed( true ); } #include "behaviorconfig.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/* #include <allegro.h> #ifdef WINDOWS #include <winalleg.h> #endif */ #include <pthread.h> #include <math.h> #include <iostream> #include "init.h" #include "loading.h" #include "util/bitmap.h" #include "fonts.h" #include "util/font.h" #include "util/funcs.h" #include <vector> using namespace std; typedef struct pair{ int x, y; } ppair; void * loadingScreen( void * arg ){ int load_x = 80; int load_y = 120; string name = "data/fonts/arial.ttf"; const Font & myFont = Font::getFont( name, 24, 24 ); const char * the_string = "Loading Paintown"; int load_width = myFont.textLength( the_string ); int load_height = myFont.getHeight( the_string ); Bitmap work( load_width, load_height ); Bitmap letters( load_width, load_height ); letters.fill( Bitmap::MaskColor ); myFont.printf( 0, 0, Bitmap::makeColor( 255, 255, 255 ), letters, the_string ); vector< ppair > pairs; /* store every pixel we need to draw */ for ( int x = 0; x < letters.getWidth(); x++ ){ for ( int y = 0; y < letters.getHeight(); y++ ){ int pixel = letters.getPixel( x, y ); if ( pixel != Bitmap::MaskColor ){ ppair p; p.x = x; p.y = y; pairs.push_back( p ); } } } const int MAX_COLOR = 200; int colors[ MAX_COLOR ]; int c1 = Bitmap::makeColor( 16, 16, 16 ); int c2 = Bitmap::makeColor( 192, 8, 8 ); /* blend from dark grey to light red */ Util::blend_palette( colors, MAX_COLOR / 2, c1, c2 ); Util::blend_palette( colors + MAX_COLOR / 2, MAX_COLOR / 2, c2, c1 ); Global::speed_counter = 0; Bitmap::Screen->Blit( string( "data/paintown-title.png" ) ); Bitmap::Screen->Blit( load_x, load_y, load_width, load_height, 0, 0, work ); Font::getDefaultFont().printf( 400, 480 - Font::getDefaultFont().getHeight() * 5 / 2, Bitmap::makeColor( 192, 192, 192 ), *Bitmap::Screen, "Made by Jon Rafkind" ); bool quit = false; /* keeps the colors moving */ static unsigned mover = 0; while ( ! quit ){ bool draw = false; if ( Global::speed_counter > 0 ){ double think = Global::speed_counter; Global::speed_counter = 0; draw = true; while ( think > 0 ){ mover = (mover + 1) % MAX_COLOR; think -= 1; } } else { Util::rest( 1 ); } if ( draw ){ for ( vector< ppair >::iterator it = pairs.begin(); it != pairs.end(); it++ ){ int color = colors[ (it->x - mover + MAX_COLOR) % MAX_COLOR ]; work.putPixel( it->x, it->y, color ); } /* work already contains the correct background */ work.Blit( load_x, load_y, *Bitmap::Screen ); } pthread_mutex_lock( &Global::loading_screen_mutex ); quit = Global::done_loading; pthread_mutex_unlock( &Global::loading_screen_mutex ); } return NULL; } <commit_msg>dont need fonts<commit_after>/* #include <allegro.h> #ifdef WINDOWS #include <winalleg.h> #endif */ #include <pthread.h> #include <math.h> #include <iostream> #include "init.h" #include "loading.h" #include "util/bitmap.h" #include "util/font.h" #include "util/funcs.h" #include <vector> using namespace std; typedef struct pair{ int x, y; } ppair; void * loadingScreen( void * arg ){ int load_x = 80; int load_y = 120; string name = "data/fonts/arial.ttf"; const Font & myFont = Font::getFont( name, 24, 24 ); const char * the_string = "Loading Paintown"; int load_width = myFont.textLength( the_string ); int load_height = myFont.getHeight( the_string ); Bitmap work( load_width, load_height ); Bitmap letters( load_width, load_height ); letters.fill( Bitmap::MaskColor ); myFont.printf( 0, 0, Bitmap::makeColor( 255, 255, 255 ), letters, the_string ); vector< ppair > pairs; /* store every pixel we need to draw */ for ( int x = 0; x < letters.getWidth(); x++ ){ for ( int y = 0; y < letters.getHeight(); y++ ){ int pixel = letters.getPixel( x, y ); if ( pixel != Bitmap::MaskColor ){ ppair p; p.x = x; p.y = y; pairs.push_back( p ); } } } const int MAX_COLOR = 200; int colors[ MAX_COLOR ]; int c1 = Bitmap::makeColor( 16, 16, 16 ); int c2 = Bitmap::makeColor( 192, 8, 8 ); /* blend from dark grey to light red */ Util::blend_palette( colors, MAX_COLOR / 2, c1, c2 ); Util::blend_palette( colors + MAX_COLOR / 2, MAX_COLOR / 2, c2, c1 ); Global::speed_counter = 0; Bitmap::Screen->Blit( string( "data/paintown-title.png" ) ); Bitmap::Screen->Blit( load_x, load_y, load_width, load_height, 0, 0, work ); Font::getDefaultFont().printf( 400, 480 - Font::getDefaultFont().getHeight() * 5 / 2, Bitmap::makeColor( 192, 192, 192 ), *Bitmap::Screen, "Made by Jon Rafkind" ); bool quit = false; /* keeps the colors moving */ static unsigned mover = 0; while ( ! quit ){ bool draw = false; if ( Global::speed_counter > 0 ){ double think = Global::speed_counter; Global::speed_counter = 0; draw = true; while ( think > 0 ){ mover = (mover + 1) % MAX_COLOR; think -= 1; } } else { Util::rest( 1 ); } if ( draw ){ for ( vector< ppair >::iterator it = pairs.begin(); it != pairs.end(); it++ ){ int color = colors[ (it->x - mover + MAX_COLOR) % MAX_COLOR ]; work.putPixel( it->x, it->y, color ); } /* work already contains the correct background */ work.Blit( load_x, load_y, *Bitmap::Screen ); } pthread_mutex_lock( &Global::loading_screen_mutex ); quit = Global::done_loading; pthread_mutex_unlock( &Global::loading_screen_mutex ); } return NULL; } <|endoftext|>
<commit_before>/*************************************************************************** * lpconfig.c * * Thu Mar 10 11:13:44 2005 * Copyright 2005 Simon Morlat * Email [email protected] ****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #define MAX_LEN 1024 #include <sys/stat.h> #define lp_new0(type, n) (type *) calloc(sizeof(type), n) #include "lpconfig.h" #include <list> #include <algorithm> #include <ortp/ortp.h> using namespace std; typedef struct _LpItem { char *key; char *value; int is_read; int lineno; } LpItem; typedef struct _LpSection { char *name; list<_LpItem *> items; } LpSection; struct _LpConfig { FILE *file; char *filename; list<_LpSection *> sections; int modified; int readonly; }; LpItem *lp_item_new(const char *key, const char *value) { LpItem *item = new LpItem(); item->key = strdup(key); item->value = strdup(value); return item; } LpSection *lp_section_new(const char *name) { LpSection *sec = new LpSection(); sec->name = ortp_strdup(name); return sec; } void lp_item_destroy(LpItem *item) { free(item->key); free(item->value); delete (item); } void lp_section_destroy(LpSection *sec) { free(sec->name); for (auto it = sec->items.cbegin(); it != sec->items.cend(); ++it) { lp_item_destroy(*it); } sec->items.clear(); delete (sec); } void lp_section_add_item(LpSection *sec, LpItem *item) { sec->items.push_back(item); } void lp_config_add_section(LpConfig *lpconfig, LpSection *section) { lpconfig->sections.push_back(section); } void lp_config_remove_section(LpConfig *lpconfig, LpSection *section) { lpconfig->sections.remove(section); lp_section_destroy(section); } static bool_t is_first_char(const char *start, const char *pos) { const char *p; for (p = start; p < pos; p++) { if (*p != ' ') return false; } return true; } struct LpSectionComp { explicit LpSectionComp(const char *name) : name(name) { } inline bool operator()(const _LpSection *sec) const { return strcasecmp(sec->name, name) == 0; } private: const char *name; }; LpSection *lp_config_find_section(LpConfig *lpconfig, const char *name) { auto it = find_if(lpconfig->sections.cbegin(), lpconfig->sections.cend(), LpSectionComp(name)); return it != lpconfig->sections.cend() ? *it : NULL; } struct LpItemComp { explicit LpItemComp(const char *key) : key(key) { } inline bool operator()(const _LpItem *item) const { return strcasecmp(item->key, key) == 0; } private: const char *key; }; LpItem *lp_section_find_item(LpSection *sec, const char *name) { auto it = find_if(sec->items.cbegin(), sec->items.cend(), LpItemComp(name)); if (it == sec->items.cend()) return NULL; (*it)->is_read = true; return *it; } static int is_a_comment(const char *str) { while (*str == ' ') { str++; } if (*str == '#') return 1; return 0; } void lp_config_parse(LpConfig *lpconfig, FILE *file) { char tmp[MAX_LEN]; LpSection *cur = NULL; int line = 0; if (file == NULL) return; while (fgets(tmp, MAX_LEN, file) != NULL) { char *pos1, *pos2; line++; if (is_a_comment(tmp)) continue; pos1 = strchr(tmp, '['); if (pos1 != NULL && is_first_char(tmp, pos1)) { pos2 = strchr(pos1, ']'); if (pos2 != NULL) { int nbs; char secname[MAX_LEN]; secname[0] = '\0'; /* found section */ *pos2 = '\0'; nbs = sscanf(pos1 + 1, "%s", secname); if (nbs == 1) { if (strlen(secname) > 0) { cur = lp_config_find_section(lpconfig, secname); if (cur == NULL) { cur = lp_section_new(secname); lp_config_add_section(lpconfig, cur); } } } else { ortp_warning("parse error!"); } } } else { pos1 = strchr(tmp, '='); if (pos1 != NULL) { char key[MAX_LEN]; key[0] = '\0'; *pos1 = '\0'; if (sscanf(tmp, "%s", key) > 0) { pos1++; pos2 = strchr(pos1, '\n'); if (pos2 == NULL) pos2 = pos1 + strlen(pos1); else { *pos2 = '\0'; /*replace the '\n' */ pos2--; } /* remove ending white spaces */ for (; pos2 > pos1 && *pos2 == ' '; pos2--) *pos2 = '\0'; if (pos2 - pos1 >= 0) { /* found a pair key,value */ if (cur != NULL) { LpItem *item = lp_section_find_item(cur, key); if (item == NULL) { item = lp_item_new(key, pos1); lp_section_add_item(cur, item); } else { free(item->value); item->value = strdup(pos1); } item->lineno = line; /*printf("Found %s %s=%s\n",cur->name,key,pos1);*/ } else { ortp_warning("found key,item but no sections"); } } } } } } } LpConfig *lp_config_new(const char *filename) { LpConfig *lpconfig = new LpConfig(); if (filename != NULL) { ortp_message("Loading configuration file from [%s]", filename); lpconfig->filename = ortp_strdup(filename); lpconfig->file = fopen(filename, "rw"); if (lpconfig->file != NULL) { lp_config_parse(lpconfig, lpconfig->file); fclose(lpconfig->file); #if 0 /* make existing configuration files non-group/world-accessible */ if (chmod(filename, S_IRUSR | S_IWUSR) == -1) ortp_warning("unable to correct permissions on " "configuration file: %s", strerror(errno)); #endif /*_WIN32_WCE*/ lpconfig->file = NULL; lpconfig->modified = 0; } } return lpconfig; } int lp_config_read_file(LpConfig *lpconfig, const char *filename) { FILE *f = fopen(filename, "r"); if (f != NULL) { lp_config_parse(lpconfig, f); fclose(f); return 0; } ortp_warning("Fail to open file %s", filename); return -1; } void lp_item_set_value(LpItem *item, const char *value) { free(item->value); item->value = ortp_strdup(value); } void lp_config_for_each_unread(LpConfig *lpconfig, LpConfigUnreadCallback cb, void *data) { for (auto elem = lpconfig->sections.cbegin(); elem != lpconfig->sections.cend(); ++elem) { LpSection *sec = *elem; for (auto it = sec->items.cbegin(); it != sec->items.cend(); ++it) { LpItem *item = *it; if (item->is_read == false) { cb(data, sec->name, item->key, item->lineno); } } } } void lp_config_destroy(LpConfig *lpconfig) { if (lpconfig->filename != NULL) free(lpconfig->filename); for (auto elem = lpconfig->sections.cbegin(); elem != lpconfig->sections.cend(); ++elem) { lp_section_destroy(*elem); } lpconfig->sections.clear(); delete (lpconfig); } void lp_section_remove_item(LpSection *sec, LpItem *item) { sec->items.remove(item); lp_item_destroy(item); } const char *lp_config_get_string(LpConfig *lpconfig, const char *section, const char *key, const char *default_string) { LpSection *sec; LpItem *item; sec = lp_config_find_section(lpconfig, section); if (sec != NULL) { item = lp_section_find_item(sec, key); if (item != NULL) return item->value; } return default_string; } int lp_config_get_int(LpConfig *lpconfig, const char *section, const char *key, int default_value) { const char *str = lp_config_get_string(lpconfig, section, key, NULL); if (str != NULL) return atoi(str); else return default_value; } float lp_config_get_float(LpConfig *lpconfig, const char *section, const char *key, float default_value) { const char *str = lp_config_get_string(lpconfig, section, key, NULL); float ret = default_value; if (str == NULL) return default_value; sscanf(str, "%f", &ret); return ret; } void lp_config_set_string(LpConfig *lpconfig, const char *section, const char *key, const char *value) { LpItem *item; LpSection *sec = lp_config_find_section(lpconfig, section); if (sec != NULL) { item = lp_section_find_item(sec, key); if (item != NULL) { if (value != NULL) lp_item_set_value(item, value); else lp_section_remove_item(sec, item); } else { if (value != NULL) lp_section_add_item(sec, lp_item_new(key, value)); } } else if (value != NULL) { sec = lp_section_new(section); lp_config_add_section(lpconfig, sec); lp_section_add_item(sec, lp_item_new(key, value)); } lpconfig->modified++; } void lp_config_set_int(LpConfig *lpconfig, const char *section, const char *key, int value) { char tmp[30]; snprintf(tmp, 30, "%i", value); lp_config_set_string(lpconfig, section, key, tmp); lpconfig->modified++; } void lp_item_write(LpItem *item, FILE *file) { fprintf(file, "%s=%s\n", item->key, item->value); } void lp_section_write(LpSection *sec, FILE *file) { fprintf(file, "[%s]\n", sec->name); for (auto it = sec->items.cbegin(); it != sec->items.cend(); ++it) { lp_item_write(*it, file); } fprintf(file, "\n"); } int lp_config_sync(LpConfig *lpconfig) { FILE *file; if (lpconfig->filename == NULL) return -1; if (lpconfig->readonly) return 0; #ifndef WIN32 /* don't create group/world-accessible files */ (void)umask(S_IRWXG | S_IRWXO); #endif file = fopen(lpconfig->filename, "w"); if (file == NULL) { ortp_warning("Could not write %s ! Maybe it is read-only. Configuration will not be saved.", lpconfig->filename); lpconfig->readonly = 1; return -1; } for (auto elem = lpconfig->sections.cbegin(); elem != lpconfig->sections.cend(); ++elem) { lp_section_write(*elem, file); } fclose(file); lpconfig->modified = 0; return 0; } int lp_config_has_section(LpConfig *lpconfig, const char *section) { if (lp_config_find_section(lpconfig, section) != NULL) return 1; return 0; } void lp_config_clean_section(LpConfig *lpconfig, const char *section) { LpSection *sec = lp_config_find_section(lpconfig, section); if (sec != NULL) { lp_config_remove_section(lpconfig, sec); } lpconfig->modified++; } int lp_config_needs_commit(const LpConfig *lpconfig) { return lpconfig->modified > 0; } <commit_msg>allow users to put space in boolean config values !<commit_after>/*************************************************************************** * lpconfig.c * * Thu Mar 10 11:13:44 2005 * Copyright 2005 Simon Morlat * Email [email protected] ****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #define MAX_LEN 1024 #include <sys/stat.h> #define lp_new0(type, n) (type *) calloc(sizeof(type), n) #include "lpconfig.h" #include <list> #include <algorithm> #include <ortp/ortp.h> using namespace std; typedef struct _LpItem { char *key; char *value; int is_read; int lineno; } LpItem; typedef struct _LpSection { char *name; list<_LpItem *> items; } LpSection; struct _LpConfig { FILE *file; char *filename; list<_LpSection *> sections; int modified; int readonly; }; LpItem *lp_item_new(const char *key, const char *value) { LpItem *item = new LpItem(); item->key = strdup(key); item->value = strdup(value); return item; } LpSection *lp_section_new(const char *name) { LpSection *sec = new LpSection(); sec->name = ortp_strdup(name); return sec; } void lp_item_destroy(LpItem *item) { free(item->key); free(item->value); delete (item); } void lp_section_destroy(LpSection *sec) { free(sec->name); for (auto it = sec->items.cbegin(); it != sec->items.cend(); ++it) { lp_item_destroy(*it); } sec->items.clear(); delete (sec); } void lp_section_add_item(LpSection *sec, LpItem *item) { sec->items.push_back(item); } void lp_config_add_section(LpConfig *lpconfig, LpSection *section) { lpconfig->sections.push_back(section); } void lp_config_remove_section(LpConfig *lpconfig, LpSection *section) { lpconfig->sections.remove(section); lp_section_destroy(section); } static bool_t is_first_char(const char *start, const char *pos) { const char *p; for (p = start; p < pos; p++) { if (*p != ' ') return false; } return true; } struct LpSectionComp { explicit LpSectionComp(const char *name) : name(name) { } inline bool operator()(const _LpSection *sec) const { return strcasecmp(sec->name, name) == 0; } private: const char *name; }; LpSection *lp_config_find_section(LpConfig *lpconfig, const char *name) { auto it = find_if(lpconfig->sections.cbegin(), lpconfig->sections.cend(), LpSectionComp(name)); return it != lpconfig->sections.cend() ? *it : NULL; } struct LpItemComp { explicit LpItemComp(const char *key) : key(key) { } inline bool operator()(const _LpItem *item) const { return strcasecmp(item->key, key) == 0; } private: const char *key; }; LpItem *lp_section_find_item(LpSection *sec, const char *name) { auto it = find_if(sec->items.cbegin(), sec->items.cend(), LpItemComp(name)); if (it == sec->items.cend()) return NULL; (*it)->is_read = true; return *it; } static int is_a_comment(const char *str) { while (*str == ' ') { str++; } if (*str == '#') return 1; return 0; } void lp_config_parse(LpConfig *lpconfig, FILE *file) { char tmp[MAX_LEN]; LpSection *cur = NULL; int line = 0; if (file == NULL) return; while (fgets(tmp, MAX_LEN, file) != NULL) { char *pos1, *pos2; line++; if (is_a_comment(tmp)) continue; pos1 = strchr(tmp, '['); if (pos1 != NULL && is_first_char(tmp, pos1)) { pos2 = strchr(pos1, ']'); if (pos2 != NULL) { int nbs; char secname[MAX_LEN]; secname[0] = '\0'; /* found section */ *pos2 = '\0'; nbs = sscanf(pos1 + 1, "%s", secname); if (nbs == 1) { if (strlen(secname) > 0) { cur = lp_config_find_section(lpconfig, secname); if (cur == NULL) { cur = lp_section_new(secname); lp_config_add_section(lpconfig, cur); } } } else { ortp_warning("parse error!"); } } } else { pos1 = strchr(tmp, '='); if (pos1 != NULL) { char key[MAX_LEN]; key[0] = '\0'; *pos1 = '\0'; if (sscanf(tmp, "%s", key) > 0) { pos1++; pos2 = strchr(pos1, '\n'); if (pos2 == NULL) pos2 = pos1 + strlen(pos1); else { *pos2 = '\0'; /*replace the '\n' */ pos2--; } /* remove ending white spaces */ for (; pos2 > pos1 && *pos2 == ' '; pos2--) *pos2 = '\0'; if (pos2 - pos1 >= 0) { /* found a pair key,value */ if (cur != NULL) { LpItem *item = lp_section_find_item(cur, key); if (item == NULL) { item = lp_item_new(key, pos1); lp_section_add_item(cur, item); } else { free(item->value); item->value = strdup(pos1); } item->lineno = line; /*printf("Found %s %s=%s\n",cur->name,key,pos1);*/ } else { ortp_warning("found key,item but no sections"); } } } } } } } LpConfig *lp_config_new(const char *filename) { LpConfig *lpconfig = new LpConfig(); if (filename != NULL) { ortp_message("Loading configuration file from [%s]", filename); lpconfig->filename = ortp_strdup(filename); lpconfig->file = fopen(filename, "rw"); if (lpconfig->file != NULL) { lp_config_parse(lpconfig, lpconfig->file); fclose(lpconfig->file); #if 0 /* make existing configuration files non-group/world-accessible */ if (chmod(filename, S_IRUSR | S_IWUSR) == -1) ortp_warning("unable to correct permissions on " "configuration file: %s", strerror(errno)); #endif /*_WIN32_WCE*/ lpconfig->file = NULL; lpconfig->modified = 0; } } return lpconfig; } int lp_config_read_file(LpConfig *lpconfig, const char *filename) { FILE *f = fopen(filename, "r"); if (f != NULL) { lp_config_parse(lpconfig, f); fclose(f); return 0; } ortp_warning("Fail to open file %s", filename); return -1; } void lp_item_set_value(LpItem *item, const char *value) { free(item->value); item->value = ortp_strdup(value); } void lp_config_for_each_unread(LpConfig *lpconfig, LpConfigUnreadCallback cb, void *data) { for (auto elem = lpconfig->sections.cbegin(); elem != lpconfig->sections.cend(); ++elem) { LpSection *sec = *elem; for (auto it = sec->items.cbegin(); it != sec->items.cend(); ++it) { LpItem *item = *it; if (item->is_read == false) { cb(data, sec->name, item->key, item->lineno); } } } } void lp_config_destroy(LpConfig *lpconfig) { if (lpconfig->filename != NULL) free(lpconfig->filename); for (auto elem = lpconfig->sections.cbegin(); elem != lpconfig->sections.cend(); ++elem) { lp_section_destroy(*elem); } lpconfig->sections.clear(); delete (lpconfig); } void lp_section_remove_item(LpSection *sec, LpItem *item) { sec->items.remove(item); lp_item_destroy(item); } const char *skip_initial_blanks(const char *str){ while(*str == ' ') ++str; return str; } const char *lp_config_get_string(LpConfig *lpconfig, const char *section, const char *key, const char *default_string) { LpSection *sec; LpItem *item; sec = lp_config_find_section(lpconfig, section); if (sec != NULL) { item = lp_section_find_item(sec, key); if (item != NULL) return skip_initial_blanks(item->value); } return default_string; } int lp_config_get_int(LpConfig *lpconfig, const char *section, const char *key, int default_value) { const char *str = lp_config_get_string(lpconfig, section, key, NULL); if (str != NULL) return atoi(str); else return default_value; } float lp_config_get_float(LpConfig *lpconfig, const char *section, const char *key, float default_value) { const char *str = lp_config_get_string(lpconfig, section, key, NULL); float ret = default_value; if (str == NULL) return default_value; sscanf(str, "%f", &ret); return ret; } void lp_config_set_string(LpConfig *lpconfig, const char *section, const char *key, const char *value) { LpItem *item; LpSection *sec = lp_config_find_section(lpconfig, section); if (sec != NULL) { item = lp_section_find_item(sec, key); if (item != NULL) { if (value != NULL) lp_item_set_value(item, value); else lp_section_remove_item(sec, item); } else { if (value != NULL) lp_section_add_item(sec, lp_item_new(key, value)); } } else if (value != NULL) { sec = lp_section_new(section); lp_config_add_section(lpconfig, sec); lp_section_add_item(sec, lp_item_new(key, value)); } lpconfig->modified++; } void lp_config_set_int(LpConfig *lpconfig, const char *section, const char *key, int value) { char tmp[30]; snprintf(tmp, 30, "%i", value); lp_config_set_string(lpconfig, section, key, tmp); lpconfig->modified++; } void lp_item_write(LpItem *item, FILE *file) { fprintf(file, "%s=%s\n", item->key, item->value); } void lp_section_write(LpSection *sec, FILE *file) { fprintf(file, "[%s]\n", sec->name); for (auto it = sec->items.cbegin(); it != sec->items.cend(); ++it) { lp_item_write(*it, file); } fprintf(file, "\n"); } int lp_config_sync(LpConfig *lpconfig) { FILE *file; if (lpconfig->filename == NULL) return -1; if (lpconfig->readonly) return 0; #ifndef WIN32 /* don't create group/world-accessible files */ (void)umask(S_IRWXG | S_IRWXO); #endif file = fopen(lpconfig->filename, "w"); if (file == NULL) { ortp_warning("Could not write %s ! Maybe it is read-only. Configuration will not be saved.", lpconfig->filename); lpconfig->readonly = 1; return -1; } for (auto elem = lpconfig->sections.cbegin(); elem != lpconfig->sections.cend(); ++elem) { lp_section_write(*elem, file); } fclose(file); lpconfig->modified = 0; return 0; } int lp_config_has_section(LpConfig *lpconfig, const char *section) { if (lp_config_find_section(lpconfig, section) != NULL) return 1; return 0; } void lp_config_clean_section(LpConfig *lpconfig, const char *section) { LpSection *sec = lp_config_find_section(lpconfig, section); if (sec != NULL) { lp_config_remove_section(lpconfig, sec); } lpconfig->modified++; } int lp_config_needs_commit(const LpConfig *lpconfig) { return lpconfig->modified > 0; } <|endoftext|>
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "clustering/administration/tables/debug_table_status.hpp" #include "clustering/administration/datum_adapter.hpp" #include "clustering/administration/servers/config_client.hpp" #include "clustering/administration/tables/table_config.hpp" #include "clustering/table_manager/table_meta_client.hpp" namespace ql { // src/rdb_protocol/terms/sindex.cc ql::datum_t sindex_status_to_datum( const std::string &, const sindex_config_t &, const sindex_status_t &); } // namespace ql debug_table_status_artificial_table_backend_t:: debug_table_status_artificial_table_backend_t( boost::shared_ptr<semilattice_readwrite_view_t< cluster_semilattice_metadata_t> > _semilattice_view, table_meta_client_t *_table_meta_client) : common_table_artificial_table_backend_t( _semilattice_view, _table_meta_client, admin_identifier_format_t::uuid) { } debug_table_status_artificial_table_backend_t:: ~debug_table_status_artificial_table_backend_t() { begin_changefeed_destruction(); } bool debug_table_status_artificial_table_backend_t::write_row( UNUSED ql::datum_t primary_key, UNUSED bool pkey_was_autogenerated, UNUSED ql::datum_t *new_value_inout, UNUSED signal_t *interruptor_on_caller, admin_err_t *error_out) { *error_out = admin_err_t{ "It's illegal to write to the `rethinkdb.table_status` table.", query_state_t::FAILED}; return false; } ql::datum_t convert_debug_multi_table_manager_bcard_timestamp_epoch_to_datum( const multi_table_manager_timestamp_t::epoch_t &epoch) { ql::datum_object_builder_t builder; builder.overwrite( "timestamp", ql::datum_t(static_cast<double>(epoch.timestamp))); builder.overwrite("id", convert_uuid_to_datum(epoch.id)); return std::move(builder).to_datum(); } ql::datum_t convert_debug_multi_table_manager_bcard_timestamp_to_datum( const multi_table_manager_timestamp_t &timestamp) { ql::datum_object_builder_t builder; builder.overwrite( "epoch", convert_debug_multi_table_manager_bcard_timestamp_epoch_to_datum( timestamp.epoch)); builder.overwrite( "log_index", ql::datum_t(static_cast<double>(timestamp.log_index))); return std::move(builder).to_datum(); } ql::datum_t convert_debug_store_key_to_datum(const store_key_t &store_key) { return ql::datum_t::binary(datum_string_t( store_key.size(), reinterpret_cast<const char *>(store_key.contents()))); } ql::datum_t convert_debug_region_to_datum(const region_t &region) { ql::datum_object_builder_t builder; builder.overwrite("hash_min", ql::datum_t(datum_string_t( strprintf("%016" PRIx64, region.beg)))); builder.overwrite("hash_max", ql::datum_t(datum_string_t( strprintf("%016" PRIx64, region.end)))); builder.overwrite("key_min", convert_debug_store_key_to_datum(region.inner.left)); builder.overwrite("key_max", region.inner.right.unbounded ? ql::datum_t::null() : convert_debug_store_key_to_datum(region.inner.right.key())); return std::move(builder).to_datum(); } ql::datum_t convert_debug_contract_primary_to_datum( const contract_t::primary_t &primary) { ql::datum_object_builder_t builder; builder.overwrite("server", convert_uuid_to_datum(primary.server)); builder.overwrite( "hand_over", static_cast<bool>(primary.hand_over) ? convert_uuid_to_datum(primary.hand_over.get()) : ql::datum_t::null()); return std::move(builder).to_datum(); } ql::datum_t convert_debug_contracts_to_datum( const std::map<contract_id_t, std::pair<region_t, contract_t> > &contracts) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); for (const auto &contract : contracts) { ql::datum_object_builder_t contract_builder; contract_builder.overwrite( "contract", convert_uuid_to_datum(contract.first)); contract_builder.overwrite( "region", convert_debug_region_to_datum(contract.second.first)); contract_builder.overwrite( "replicas", convert_set_to_datum<server_id_t>( &convert_uuid_to_datum, contract.second.second.replicas)); contract_builder.overwrite( "voters", convert_set_to_datum<server_id_t>( &convert_uuid_to_datum, contract.second.second.voters)); contract_builder.overwrite( "temp_voters", static_cast<bool>(contract.second.second.temp_voters) ? convert_set_to_datum<server_id_t>( &convert_uuid_to_datum, contract.second.second.temp_voters.get()) : ql::datum_t::null()); contract_builder.overwrite( "primary", static_cast<bool>(contract.second.second.primary) ? convert_debug_contract_primary_to_datum( contract.second.second.primary.get()) : ql::datum_t::null()); builder.add(std::move(contract_builder).to_datum()); } return std::move(builder).to_datum(); } ql::datum_t convert_debug_table_shard_scheme_to_datum( const table_shard_scheme_t &shard_scheme) { ql::datum_object_builder_t builder; builder.overwrite("split_points", convert_vector_to_datum<store_key_t>( &convert_debug_store_key_to_datum, shard_scheme.split_points)); return std::move(builder).to_datum(); } ql::datum_t convert_debug_contract_ack_state_to_datum( const contract_ack_t::state_t &state) { switch (state) { case contract_ack_t::state_t::primary_need_branch: return convert_string_to_datum("primary_need_branch"); case contract_ack_t::state_t::primary_in_progress: return convert_string_to_datum("primary_in_progress"); case contract_ack_t::state_t::primary_ready: return convert_string_to_datum("primary_ready"); case contract_ack_t::state_t::secondary_need_primary: return convert_string_to_datum("secondary_need_primary"); case contract_ack_t::state_t::secondary_backfilling: return convert_string_to_datum("secondary_backfilling"); case contract_ack_t::state_t::secondary_streaming: return convert_string_to_datum("secondary_streaming"); default: unreachable(); } } ql::datum_t convert_debug_version_to_datum(const version_t &version) { ql::datum_object_builder_t builder; builder.overwrite("branch", convert_uuid_to_datum(version.branch)); builder.overwrite("timestamp", ql::datum_t(static_cast<double>( version.timestamp.to_repli_timestamp().longtime))); return std::move(builder).to_datum(); } ql::datum_t convert_debug_version_map_to_datum( const region_map_t<version_t> &map) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); map.visit( map.get_domain(), [&](const region_t &region, const version_t &version) { ql::datum_object_builder_t pair_builder; pair_builder.overwrite("region", convert_debug_region_to_datum(region)); pair_builder.overwrite("version", convert_debug_version_to_datum(version)); builder.add(std::move(pair_builder).to_datum()); }); return std::move(builder).to_datum(); } ql::datum_t convert_debug_current_branches_to_datum( const region_map_t<branch_id_t> &map) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); map.visit( map.get_domain(), [&](const region_t &region, const branch_id_t &branch) { ql::datum_object_builder_t pair_builder; pair_builder.overwrite("region", convert_debug_region_to_datum(region)); pair_builder.overwrite("branch", convert_uuid_to_datum(branch)); builder.add(std::move(pair_builder).to_datum()); }); return std::move(builder).to_datum(); } ql::datum_t convert_debug_branch_birth_certificate_to_datum( const branch_birth_certificate_t &birth_certificate) { ql::datum_object_builder_t builder; builder.overwrite("initial_timestamp", ql::datum_t(static_cast<double>( birth_certificate.initial_timestamp.to_repli_timestamp().longtime))); builder.overwrite( "origin", convert_debug_version_map_to_datum(birth_certificate.origin)); return std::move(builder).to_datum(); } ql::datum_t convert_debug_branch_history_to_datum( const branch_history_t &branch_history) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); for (const auto &branch : branch_history.branches) { ql::datum_object_builder_t branch_builder; branch_builder.overwrite("branch", convert_uuid_to_datum(branch.first)); branch_builder.overwrite( "branch_birth_certificate", convert_debug_branch_birth_certificate_to_datum(branch.second)); builder.add(std::move(branch_builder).to_datum()); } return std::move(builder).to_datum(); } ql::datum_t convert_debug_contract_acks_to_datum( const std::map<contract_id_t, contract_ack_t> &contract_acks) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); for (const auto &contract_ack : contract_acks) { ql::datum_object_builder_t contract_builder; contract_builder.overwrite( "contract", convert_uuid_to_datum(contract_ack.first)); contract_builder.overwrite( "state", convert_debug_contract_ack_state_to_datum(contract_ack.second.state)); contract_builder.overwrite( "version", static_cast<bool>(contract_ack.second.version) ? convert_debug_version_map_to_datum( contract_ack.second.version.get()) : ql::datum_t::null()); /* RSI(raft) The branch history is append-only thus it grows without bound, printing it can be reinstated once it's garbage collected per #3879. For the time being we print the size instead. contract_builder.overwrite( "branch_history", convert_debug_branch_history_to_datum(contract_ack.second.branch_history)); */ contract_builder.overwrite( "branch_history", ql::datum_t(static_cast<double>( contract_ack.second.branch_history.branches.size()))); builder.add(std::move(contract_builder).to_datum()); } return std::move(builder).to_datum(); } ql::datum_t convert_debug_statuses_to_datum( const std::map<server_id_t, table_status_response_t> &statuses) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); for (const auto &peer : statuses) { ql::datum_object_builder_t peer_builder; peer_builder.overwrite("server", convert_uuid_to_datum(peer.first)); peer_builder.overwrite("timestamp", convert_debug_multi_table_manager_bcard_timestamp_to_datum( *peer.second.raft_state_timestamp)); peer_builder.overwrite("contracts", convert_debug_contracts_to_datum(peer.second.raft_state->contracts)); peer_builder.overwrite("contract_acks", convert_debug_contract_acks_to_datum(peer.second.contract_acks)); peer_builder.overwrite("current_branches", convert_debug_current_branches_to_datum( peer.second.raft_state->current_branches)); builder.add(std::move(peer_builder).to_datum()); } return std::move(builder).to_datum(); } void debug_table_status_artificial_table_backend_t::format_row( const namespace_id_t &table_id, const table_config_and_shards_t &config_and_shards, const ql::datum_t &db_name_or_uuid, signal_t *interruptor_on_home, ql::datum_t *row_out) THROWS_ONLY(interrupted_exc_t, no_such_table_exc_t, failed_table_op_exc_t) { assert_thread(); std::map<server_id_t, table_status_response_t> statuses; table_meta_client->get_debug_status(table_id, interruptor_on_home, &statuses); ql::datum_object_builder_t builder; builder.overwrite("id", convert_uuid_to_datum(table_id)); builder.overwrite("name", convert_name_to_datum(config_and_shards.config.basic.name)); builder.overwrite("db", db_name_or_uuid); builder.overwrite( "config", convert_table_config_to_datum( table_id, db_name_or_uuid, config_and_shards.config, admin_identifier_format_t::uuid, config_and_shards.server_names)); builder.overwrite( "shard_scheme", convert_debug_table_shard_scheme_to_datum(config_and_shards.shard_scheme)); builder.overwrite( "table_server_status", convert_debug_statuses_to_datum(statuses)); *row_out = std::move(builder).to_datum(); } <commit_msg>Fix a minor RSI(raft) comment.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "clustering/administration/tables/debug_table_status.hpp" #include "clustering/administration/datum_adapter.hpp" #include "clustering/administration/servers/config_client.hpp" #include "clustering/administration/tables/table_config.hpp" #include "clustering/table_manager/table_meta_client.hpp" namespace ql { // src/rdb_protocol/terms/sindex.cc ql::datum_t sindex_status_to_datum( const std::string &, const sindex_config_t &, const sindex_status_t &); } // namespace ql debug_table_status_artificial_table_backend_t:: debug_table_status_artificial_table_backend_t( boost::shared_ptr<semilattice_readwrite_view_t< cluster_semilattice_metadata_t> > _semilattice_view, table_meta_client_t *_table_meta_client) : common_table_artificial_table_backend_t( _semilattice_view, _table_meta_client, admin_identifier_format_t::uuid) { } debug_table_status_artificial_table_backend_t:: ~debug_table_status_artificial_table_backend_t() { begin_changefeed_destruction(); } bool debug_table_status_artificial_table_backend_t::write_row( UNUSED ql::datum_t primary_key, UNUSED bool pkey_was_autogenerated, UNUSED ql::datum_t *new_value_inout, UNUSED signal_t *interruptor_on_caller, admin_err_t *error_out) { *error_out = admin_err_t{ "It's illegal to write to the `rethinkdb.table_status` table.", query_state_t::FAILED}; return false; } ql::datum_t convert_debug_multi_table_manager_bcard_timestamp_epoch_to_datum( const multi_table_manager_timestamp_t::epoch_t &epoch) { ql::datum_object_builder_t builder; builder.overwrite( "timestamp", ql::datum_t(static_cast<double>(epoch.timestamp))); builder.overwrite("id", convert_uuid_to_datum(epoch.id)); return std::move(builder).to_datum(); } ql::datum_t convert_debug_multi_table_manager_bcard_timestamp_to_datum( const multi_table_manager_timestamp_t &timestamp) { ql::datum_object_builder_t builder; builder.overwrite( "epoch", convert_debug_multi_table_manager_bcard_timestamp_epoch_to_datum( timestamp.epoch)); builder.overwrite( "log_index", ql::datum_t(static_cast<double>(timestamp.log_index))); return std::move(builder).to_datum(); } ql::datum_t convert_debug_store_key_to_datum(const store_key_t &store_key) { return ql::datum_t::binary(datum_string_t( store_key.size(), reinterpret_cast<const char *>(store_key.contents()))); } ql::datum_t convert_debug_region_to_datum(const region_t &region) { ql::datum_object_builder_t builder; builder.overwrite("hash_min", ql::datum_t(datum_string_t( strprintf("%016" PRIx64, region.beg)))); builder.overwrite("hash_max", ql::datum_t(datum_string_t( strprintf("%016" PRIx64, region.end)))); builder.overwrite("key_min", convert_debug_store_key_to_datum(region.inner.left)); builder.overwrite("key_max", region.inner.right.unbounded ? ql::datum_t::null() : convert_debug_store_key_to_datum(region.inner.right.key())); return std::move(builder).to_datum(); } ql::datum_t convert_debug_contract_primary_to_datum( const contract_t::primary_t &primary) { ql::datum_object_builder_t builder; builder.overwrite("server", convert_uuid_to_datum(primary.server)); builder.overwrite( "hand_over", static_cast<bool>(primary.hand_over) ? convert_uuid_to_datum(primary.hand_over.get()) : ql::datum_t::null()); return std::move(builder).to_datum(); } ql::datum_t convert_debug_contracts_to_datum( const std::map<contract_id_t, std::pair<region_t, contract_t> > &contracts) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); for (const auto &contract : contracts) { ql::datum_object_builder_t contract_builder; contract_builder.overwrite( "contract", convert_uuid_to_datum(contract.first)); contract_builder.overwrite( "region", convert_debug_region_to_datum(contract.second.first)); contract_builder.overwrite( "replicas", convert_set_to_datum<server_id_t>( &convert_uuid_to_datum, contract.second.second.replicas)); contract_builder.overwrite( "voters", convert_set_to_datum<server_id_t>( &convert_uuid_to_datum, contract.second.second.voters)); contract_builder.overwrite( "temp_voters", static_cast<bool>(contract.second.second.temp_voters) ? convert_set_to_datum<server_id_t>( &convert_uuid_to_datum, contract.second.second.temp_voters.get()) : ql::datum_t::null()); contract_builder.overwrite( "primary", static_cast<bool>(contract.second.second.primary) ? convert_debug_contract_primary_to_datum( contract.second.second.primary.get()) : ql::datum_t::null()); builder.add(std::move(contract_builder).to_datum()); } return std::move(builder).to_datum(); } ql::datum_t convert_debug_table_shard_scheme_to_datum( const table_shard_scheme_t &shard_scheme) { ql::datum_object_builder_t builder; builder.overwrite("split_points", convert_vector_to_datum<store_key_t>( &convert_debug_store_key_to_datum, shard_scheme.split_points)); return std::move(builder).to_datum(); } ql::datum_t convert_debug_contract_ack_state_to_datum( const contract_ack_t::state_t &state) { switch (state) { case contract_ack_t::state_t::primary_need_branch: return convert_string_to_datum("primary_need_branch"); case contract_ack_t::state_t::primary_in_progress: return convert_string_to_datum("primary_in_progress"); case contract_ack_t::state_t::primary_ready: return convert_string_to_datum("primary_ready"); case contract_ack_t::state_t::secondary_need_primary: return convert_string_to_datum("secondary_need_primary"); case contract_ack_t::state_t::secondary_backfilling: return convert_string_to_datum("secondary_backfilling"); case contract_ack_t::state_t::secondary_streaming: return convert_string_to_datum("secondary_streaming"); default: unreachable(); } } ql::datum_t convert_debug_version_to_datum(const version_t &version) { ql::datum_object_builder_t builder; builder.overwrite("branch", convert_uuid_to_datum(version.branch)); builder.overwrite("timestamp", ql::datum_t(static_cast<double>( version.timestamp.to_repli_timestamp().longtime))); return std::move(builder).to_datum(); } ql::datum_t convert_debug_version_map_to_datum( const region_map_t<version_t> &map) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); map.visit( map.get_domain(), [&](const region_t &region, const version_t &version) { ql::datum_object_builder_t pair_builder; pair_builder.overwrite("region", convert_debug_region_to_datum(region)); pair_builder.overwrite("version", convert_debug_version_to_datum(version)); builder.add(std::move(pair_builder).to_datum()); }); return std::move(builder).to_datum(); } ql::datum_t convert_debug_current_branches_to_datum( const region_map_t<branch_id_t> &map) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); map.visit( map.get_domain(), [&](const region_t &region, const branch_id_t &branch) { ql::datum_object_builder_t pair_builder; pair_builder.overwrite("region", convert_debug_region_to_datum(region)); pair_builder.overwrite("branch", convert_uuid_to_datum(branch)); builder.add(std::move(pair_builder).to_datum()); }); return std::move(builder).to_datum(); } ql::datum_t convert_debug_branch_birth_certificate_to_datum( const branch_birth_certificate_t &birth_certificate) { ql::datum_object_builder_t builder; builder.overwrite("initial_timestamp", ql::datum_t(static_cast<double>( birth_certificate.initial_timestamp.to_repli_timestamp().longtime))); builder.overwrite( "origin", convert_debug_version_map_to_datum(birth_certificate.origin)); return std::move(builder).to_datum(); } ql::datum_t convert_debug_branch_history_to_datum( const branch_history_t &branch_history) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); for (const auto &branch : branch_history.branches) { ql::datum_object_builder_t branch_builder; branch_builder.overwrite("branch", convert_uuid_to_datum(branch.first)); branch_builder.overwrite( "branch_birth_certificate", convert_debug_branch_birth_certificate_to_datum(branch.second)); builder.add(std::move(branch_builder).to_datum()); } return std::move(builder).to_datum(); } ql::datum_t convert_debug_contract_acks_to_datum( const std::map<contract_id_t, contract_ack_t> &contract_acks) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); for (const auto &contract_ack : contract_acks) { ql::datum_object_builder_t contract_builder; contract_builder.overwrite( "contract", convert_uuid_to_datum(contract_ack.first)); contract_builder.overwrite( "state", convert_debug_contract_ack_state_to_datum(contract_ack.second.state)); contract_builder.overwrite( "version", static_cast<bool>(contract_ack.second.version) ? convert_debug_version_map_to_datum( contract_ack.second.version.get()) : ql::datum_t::null()); contract_builder.overwrite( "branch_history", convert_debug_branch_history_to_datum(contract_ack.second.branch_history)); builder.add(std::move(contract_builder).to_datum()); } return std::move(builder).to_datum(); } ql::datum_t convert_debug_statuses_to_datum( const std::map<server_id_t, table_status_response_t> &statuses) { ql::datum_array_builder_t builder(ql::configured_limits_t::unlimited); for (const auto &peer : statuses) { ql::datum_object_builder_t peer_builder; peer_builder.overwrite("server", convert_uuid_to_datum(peer.first)); peer_builder.overwrite("timestamp", convert_debug_multi_table_manager_bcard_timestamp_to_datum( *peer.second.raft_state_timestamp)); peer_builder.overwrite("contracts", convert_debug_contracts_to_datum(peer.second.raft_state->contracts)); peer_builder.overwrite("contract_acks", convert_debug_contract_acks_to_datum(peer.second.contract_acks)); peer_builder.overwrite("current_branches", convert_debug_current_branches_to_datum( peer.second.raft_state->current_branches)); builder.add(std::move(peer_builder).to_datum()); } return std::move(builder).to_datum(); } void debug_table_status_artificial_table_backend_t::format_row( const namespace_id_t &table_id, const table_config_and_shards_t &config_and_shards, const ql::datum_t &db_name_or_uuid, signal_t *interruptor_on_home, ql::datum_t *row_out) THROWS_ONLY(interrupted_exc_t, no_such_table_exc_t, failed_table_op_exc_t) { assert_thread(); std::map<server_id_t, table_status_response_t> statuses; table_meta_client->get_debug_status(table_id, interruptor_on_home, &statuses); ql::datum_object_builder_t builder; builder.overwrite("id", convert_uuid_to_datum(table_id)); builder.overwrite("name", convert_name_to_datum(config_and_shards.config.basic.name)); builder.overwrite("db", db_name_or_uuid); builder.overwrite( "config", convert_table_config_to_datum( table_id, db_name_or_uuid, config_and_shards.config, admin_identifier_format_t::uuid, config_and_shards.server_names)); builder.overwrite( "shard_scheme", convert_debug_table_shard_scheme_to_datum(config_and_shards.shard_scheme)); builder.overwrite( "table_server_status", convert_debug_statuses_to_datum(statuses)); *row_out = std::move(builder).to_datum(); } <|endoftext|>
<commit_before>/* Copyright (c) 2014 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file mc_att_control_base.cpp * * MC Attitude Controller : Control and math code * * @author Tobias Naegeli <[email protected]> * @author Lorenz Meier <[email protected]> * @author Anton Babushkin <[email protected]> * @author Thomas Gubler <[email protected]> * @author Julian Oes <[email protected]> * @author Roman Bapst <[email protected]> * */ #include "mc_att_control_base.h" #include <geo/geo.h> #include <math.h> #include <lib/mathlib/mathlib.h> #ifdef CONFIG_ARCH_ARM #else #include <cmath> using namespace std; #endif MulticopterAttitudeControlBase::MulticopterAttitudeControlBase() : _v_rates_sp_mod(), _actuators(), _publish_att_sp(false) { _params.att_p.zero(); _params.rate_p.zero(); _params.rate_i.zero(); _params.rate_d.zero(); _params.yaw_ff = 0.0f; _params.yaw_rate_max = 0.0f; _params.acro_rate_max.zero(); _rates_prev.zero(); _rates_sp.zero(); _rates_int.zero(); _thrust_sp = 0.0f; _att_control.zero(); _I.identity(); } MulticopterAttitudeControlBase::~MulticopterAttitudeControlBase() { } void MulticopterAttitudeControlBase::control_attitude(float dt) { _thrust_sp = _v_att_sp->data().thrust; /* construct attitude setpoint rotation matrix */ math::Matrix<3, 3> R_sp; matrix::Quaternion<float> q_sp(&_v_att_sp->data().q_d[0]); R_sp.set(&q_sp._data[0][0]); /* rotation matrix for current state */ math::Matrix<3, 3> R; matrix::Quaternion<float> q(&_v_att->data().q[0]); R.set(&q._data[0][0]); /* all input data is ready, run controller itself */ /* try to move thrust vector shortest way, because yaw response is slower than roll/pitch */ math::Vector <3> R_z(R(0, 2), R(1, 2), R(2, 2)); math::Vector <3> R_sp_z(R_sp(0, 2), R_sp(1, 2), R_sp(2, 2)); /* axis and sin(angle) of desired rotation */ math::Vector <3> e_R = R.transposed() * (R_z % R_sp_z); /* calculate angle error */ float e_R_z_sin = e_R.length(); float e_R_z_cos = R_z * R_sp_z; /* calculate weight for yaw control */ float yaw_w = R_sp(2, 2) * R_sp(2, 2); /* calculate rotation matrix after roll/pitch only rotation */ math::Matrix<3, 3> R_rp; if (e_R_z_sin > 0.0f) { /* get axis-angle representation */ float e_R_z_angle = atan2f(e_R_z_sin, e_R_z_cos); math::Vector <3> e_R_z_axis = e_R / e_R_z_sin; e_R = e_R_z_axis * e_R_z_angle; /* cross product matrix for e_R_axis */ math::Matrix<3, 3> e_R_cp; e_R_cp.zero(); e_R_cp(0, 1) = -e_R_z_axis(2); e_R_cp(0, 2) = e_R_z_axis(1); e_R_cp(1, 0) = e_R_z_axis(2); e_R_cp(1, 2) = -e_R_z_axis(0); e_R_cp(2, 0) = -e_R_z_axis(1); e_R_cp(2, 1) = e_R_z_axis(0); /* rotation matrix for roll/pitch only rotation */ R_rp = R * (_I + e_R_cp * e_R_z_sin + e_R_cp * e_R_cp * (1.0f - e_R_z_cos)); } else { /* zero roll/pitch rotation */ R_rp = R; } /* R_rp and R_sp has the same Z axis, calculate yaw error */ math::Vector <3> R_sp_x(R_sp(0, 0), R_sp(1, 0), R_sp(2, 0)); math::Vector <3> R_rp_x(R_rp(0, 0), R_rp(1, 0), R_rp(2, 0)); e_R(2) = atan2f((R_rp_x % R_sp_x) * R_sp_z, R_rp_x * R_sp_x) * yaw_w; if (e_R_z_cos < 0.0f) { /* for large thrust vector rotations use another rotation method: * calculate angle and axis for R -> R_sp rotation directly */ math::Quaternion ql; ql.from_dcm(R.transposed() * R_sp); math::Vector <3> e_R_d = ql.imag(); e_R_d.normalize(); e_R_d *= 2.0f * atan2f(e_R_d.length(), ql(0)); /* use fusion of Z axis based rotation and direct rotation */ float direct_w = e_R_z_cos * e_R_z_cos * yaw_w; e_R = e_R * (1.0f - direct_w) + e_R_d * direct_w; } /* calculate angular rates setpoint */ _rates_sp = _params.att_p.emult(e_R); /* limit yaw rate */ _rates_sp(2) = math::constrain(_rates_sp(2), -_params.yaw_rate_max, _params.yaw_rate_max); /* feed forward yaw setpoint rate */ _rates_sp(2) += _v_att_sp->data().yaw_sp_move_rate * yaw_w * _params.yaw_ff; } void MulticopterAttitudeControlBase::control_attitude_rates(float dt) { /* reset integral if disarmed */ if (!_armed->data().armed || !_v_status->data().is_rotary_wing) { _rates_int.zero(); } /* current body angular rates */ math::Vector < 3 > rates; rates(0) = _v_att->data().rollspeed; rates(1) = _v_att->data().pitchspeed; rates(2) = _v_att->data().yawspeed; /* angular rates error */ math::Vector < 3 > rates_err = _rates_sp - rates; _att_control = _params.rate_p.emult(rates_err) + _params.rate_d.emult(_rates_prev - rates) / dt + _rates_int; _rates_prev = rates; /* update integral only if not saturated on low limit */ if (_thrust_sp > MIN_TAKEOFF_THRUST) { for (int i = 0; i < 3; i++) { if (fabsf(_att_control(i)) < _thrust_sp) { float rate_i = _rates_int(i) + _params.rate_i(i) * rates_err(i) * dt; if (isfinite( rate_i) && rate_i > -RATES_I_LIMIT && rate_i < RATES_I_LIMIT && _att_control(i) > -RATES_I_LIMIT && _att_control(i) < RATES_I_LIMIT) { _rates_int(i) = rate_i; } } } } } void MulticopterAttitudeControlBase::set_actuator_controls() { _actuators.data().control[0] = (isfinite(_att_control(0))) ? _att_control(0) : 0.0f; _actuators.data().control[1] = (isfinite(_att_control(1))) ? _att_control(1) : 0.0f; _actuators.data().control[2] = (isfinite(_att_control(2))) ? _att_control(2) : 0.0f; _actuators.data().control[3] = (isfinite(_thrust_sp)) ? _thrust_sp : 0.0f; } <commit_msg>Fix mc att control multiplatform<commit_after>/* Copyright (c) 2014 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file mc_att_control_base.cpp * * MC Attitude Controller : Control and math code * * @author Tobias Naegeli <[email protected]> * @author Lorenz Meier <[email protected]> * @author Anton Babushkin <[email protected]> * @author Thomas Gubler <[email protected]> * @author Julian Oes <[email protected]> * @author Roman Bapst <[email protected]> * */ #include "mc_att_control_base.h" #include <geo/geo.h> #include <math.h> #include <lib/mathlib/mathlib.h> #ifdef CONFIG_ARCH_ARM #else #include <cmath> using namespace std; #endif MulticopterAttitudeControlBase::MulticopterAttitudeControlBase() : _v_rates_sp_mod(), _actuators(), _publish_att_sp(false) { _params.att_p.zero(); _params.rate_p.zero(); _params.rate_i.zero(); _params.rate_d.zero(); _params.yaw_ff = 0.0f; _params.yaw_rate_max = 0.0f; _params.acro_rate_max.zero(); _rates_prev.zero(); _rates_sp.zero(); _rates_int.zero(); _thrust_sp = 0.0f; _att_control.zero(); _I.identity(); } MulticopterAttitudeControlBase::~MulticopterAttitudeControlBase() { } void MulticopterAttitudeControlBase::control_attitude(float dt) { _thrust_sp = _v_att_sp->data().thrust; /* construct attitude setpoint rotation matrix */ math::Quaternion q_sp(&_v_att_sp->data().q_d[0]); math::Matrix<3, 3> R_sp = q_sp.to_dcm(); /* rotation matrix for current state */ math::Quaternion q(&_v_att->data().q[0]); math::Matrix<3, 3> R = q.to_dcm(); /* all input data is ready, run controller itself */ /* try to move thrust vector shortest way, because yaw response is slower than roll/pitch */ math::Vector <3> R_z(R(0, 2), R(1, 2), R(2, 2)); math::Vector <3> R_sp_z(R_sp(0, 2), R_sp(1, 2), R_sp(2, 2)); /* axis and sin(angle) of desired rotation */ math::Vector <3> e_R = R.transposed() * (R_z % R_sp_z); /* calculate angle error */ float e_R_z_sin = e_R.length(); float e_R_z_cos = R_z * R_sp_z; /* calculate weight for yaw control */ float yaw_w = R_sp(2, 2) * R_sp(2, 2); /* calculate rotation matrix after roll/pitch only rotation */ math::Matrix<3, 3> R_rp; if (e_R_z_sin > 0.0f) { /* get axis-angle representation */ float e_R_z_angle = atan2f(e_R_z_sin, e_R_z_cos); math::Vector <3> e_R_z_axis = e_R / e_R_z_sin; e_R = e_R_z_axis * e_R_z_angle; /* cross product matrix for e_R_axis */ math::Matrix<3, 3> e_R_cp; e_R_cp.zero(); e_R_cp(0, 1) = -e_R_z_axis(2); e_R_cp(0, 2) = e_R_z_axis(1); e_R_cp(1, 0) = e_R_z_axis(2); e_R_cp(1, 2) = -e_R_z_axis(0); e_R_cp(2, 0) = -e_R_z_axis(1); e_R_cp(2, 1) = e_R_z_axis(0); /* rotation matrix for roll/pitch only rotation */ R_rp = R * (_I + e_R_cp * e_R_z_sin + e_R_cp * e_R_cp * (1.0f - e_R_z_cos)); } else { /* zero roll/pitch rotation */ R_rp = R; } /* R_rp and R_sp has the same Z axis, calculate yaw error */ math::Vector <3> R_sp_x(R_sp(0, 0), R_sp(1, 0), R_sp(2, 0)); math::Vector <3> R_rp_x(R_rp(0, 0), R_rp(1, 0), R_rp(2, 0)); e_R(2) = atan2f((R_rp_x % R_sp_x) * R_sp_z, R_rp_x * R_sp_x) * yaw_w; if (e_R_z_cos < 0.0f) { /* for large thrust vector rotations use another rotation method: * calculate angle and axis for R -> R_sp rotation directly */ math::Quaternion ql; ql.from_dcm(R.transposed() * R_sp); math::Vector <3> e_R_d = ql.imag(); e_R_d.normalize(); e_R_d *= 2.0f * atan2f(e_R_d.length(), ql(0)); /* use fusion of Z axis based rotation and direct rotation */ float direct_w = e_R_z_cos * e_R_z_cos * yaw_w; e_R = e_R * (1.0f - direct_w) + e_R_d * direct_w; } /* calculate angular rates setpoint */ _rates_sp = _params.att_p.emult(e_R); /* limit yaw rate */ _rates_sp(2) = math::constrain(_rates_sp(2), -_params.yaw_rate_max, _params.yaw_rate_max); /* feed forward yaw setpoint rate */ _rates_sp(2) += _v_att_sp->data().yaw_sp_move_rate * yaw_w * _params.yaw_ff; } void MulticopterAttitudeControlBase::control_attitude_rates(float dt) { /* reset integral if disarmed */ if (!_armed->data().armed || !_v_status->data().is_rotary_wing) { _rates_int.zero(); } /* current body angular rates */ math::Vector < 3 > rates; rates(0) = _v_att->data().rollspeed; rates(1) = _v_att->data().pitchspeed; rates(2) = _v_att->data().yawspeed; /* angular rates error */ math::Vector < 3 > rates_err = _rates_sp - rates; _att_control = _params.rate_p.emult(rates_err) + _params.rate_d.emult(_rates_prev - rates) / dt + _rates_int; _rates_prev = rates; /* update integral only if not saturated on low limit */ if (_thrust_sp > MIN_TAKEOFF_THRUST) { for (int i = 0; i < 3; i++) { if (fabsf(_att_control(i)) < _thrust_sp) { float rate_i = _rates_int(i) + _params.rate_i(i) * rates_err(i) * dt; if (isfinite( rate_i) && rate_i > -RATES_I_LIMIT && rate_i < RATES_I_LIMIT && _att_control(i) > -RATES_I_LIMIT && _att_control(i) < RATES_I_LIMIT) { _rates_int(i) = rate_i; } } } } } void MulticopterAttitudeControlBase::set_actuator_controls() { _actuators.data().control[0] = (isfinite(_att_control(0))) ? _att_control(0) : 0.0f; _actuators.data().control[1] = (isfinite(_att_control(1))) ? _att_control(1) : 0.0f; _actuators.data().control[2] = (isfinite(_att_control(2))) ? _att_control(2) : 0.0f; _actuators.data().control[3] = (isfinite(_thrust_sp)) ? _thrust_sp : 0.0f; } <|endoftext|>
<commit_before>#ifndef CPPNOTESMAIN_SPLIT_ARRAY_INTO_CONSECUTIVE_SUBSEQUENCES_HPP #define CPPNOTESMAIN_SPLIT_ARRAY_INTO_CONSECUTIVE_SUBSEQUENCES_HPP /* https://leetcode.com/problems/split-array-into-consecutive-subsequences/ Given an array nums sorted in ascending order, return true if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3. Example 1: Input: [1,2,3,3,4,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3 3, 4, 5 Example 2: Input: [1,2,3,3,4,4,5,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3, 4, 5 3, 4, 5 Example 3: Input: [1,2,3,4,4,5] Output: False Constraints: - 1 <= nums.length <= 10000 */ #include <vector> namespace Algo::Greedy { class SplitArray { public: static bool canSplitIntoConsecutiveSubsequences(const std::vector<int>& nums) { std::vector<std::vector<size_t>> sequences; for (size_t i = 0; i < nums.size(); ) { size_t j = i, count = 0; while (j < nums.size() && nums[j] == nums[i]) { ++count; ++j; } // check if current number is not consecutive number. In this case all current // subsequences should be "finished". if (i > 0 && nums[i] - nums[i-1] > 1) { for (const auto& seq : sequences) { if (seq.size() < 3) { return false; } } sequences.clear(); } while (count < sequences.size()) { if (sequences.front().size() < 3) { return false; } sequences.erase(sequences.begin()); } sequences.resize(count); for (auto& seq : sequences) { seq.push_back(nums[i]); } i += count; } for (const auto& seq : sequences) { if (seq.size() < 3) { return false; } } return true; } }; } #endif //CPPNOTESMAIN_SPLIT_ARRAY_INTO_CONSECUTIVE_SUBSEQUENCES_HPP <commit_msg>Add algo - split array into consecutive subsequences of size k<commit_after>#ifndef CPPNOTESMAIN_SPLIT_ARRAY_INTO_CONSECUTIVE_SUBSEQUENCES_HPP #define CPPNOTESMAIN_SPLIT_ARRAY_INTO_CONSECUTIVE_SUBSEQUENCES_HPP #include <vector> namespace Algo::Greedy { class SplitArray { public: /* https://leetcode.com/problems/split-array-into-consecutive-subsequences/ Given an array nums sorted in ascending order, return true if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3. Example 1: Input: [1,2,3,3,4,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3 3, 4, 5 Example 2: Input: [1,2,3,3,4,4,5,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3, 4, 5 3, 4, 5 Example 3: Input: [1,2,3,4,4,5] Output: False Constraints: - 1 <= nums.length <= 10000 */ static bool canSplitIntoConsecutiveSubsequences(const std::vector<int>& nums) { std::vector<std::vector<size_t>> sequences; for (size_t i = 0; i < nums.size(); ) { size_t j = i, count = 0; while (j < nums.size() && nums[j] == nums[i]) { ++count; ++j; } // check if current number is not consecutive number. In this case all current // subsequences should be "finished". if (i > 0 && nums[i] - nums[i-1] > 1) { for (const auto& seq : sequences) { if (seq.size() < 3) { return false; } } sequences.clear(); } while (count < sequences.size()) { if (sequences.front().size() < 3) { return false; } sequences.erase(sequences.begin()); } sequences.resize(count); for (auto& seq : sequences) { seq.push_back(nums[i]); } i += count; } for (const auto& seq : sequences) { if (seq.size() < 3) { return false; } } return true; } /* https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/ https://leetcode.com/problems/hand-of-straights/ - duplicate Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into sets of k consecutive numbers. Return True if its possible otherwise return False. Example 1: Input: nums = [1,2,3,3,4,4,5,6], k = 4 Output: true Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6]. Example 2: Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3 Output: true Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11]. Example 3: Input: nums = [3,3,2,2,1,1], k = 3 Output: true Example 4: Input: nums = [1,2,3,4], k = 3 Output: false Explanation: Each array should be divided in subarrays of size 3. Constraints: 1 <= nums.length <= 10^5 1 <= nums[i] <= 10^9 1 <= k <= nums.length */ static bool canSplitIntoFixedConsecutiveSubsequences( std::vector<int>& nums, const size_t k) { std::sort(nums.begin(), nums.end()); std::vector<std::vector<size_t>> sequences; for (size_t i = 0; i < nums.size(); ) { size_t j = i, count = 0; while (j < nums.size() && nums[j] == nums[i]) { ++count; ++j; } // check if current number is not consecutive number. In this case all current // subsequences should be "finished". if (i > 0 && nums[i] - nums[i-1] > 1) { for (const auto& seq : sequences) { if (seq.size() != k) { return false; } } sequences.clear(); } auto remove_from_iter = std::remove( sequences.begin(), sequences.end(), [&k](const auto& seq){ return seq.size() == k; }); sequences.erase(remove_from_iter, sequences.end()); while (count < sequences.size()) { if (sequences.front().size() != k) { return false; } sequences.erase(sequences.begin()); } sequences.resize(count); for (auto& seq : sequences) { seq.push_back(nums[i]); } i += count; } for (const auto& seq : sequences) { if (seq.size() != k) { return false; } } return true; } }; } #endif //CPPNOTESMAIN_SPLIT_ARRAY_INTO_CONSECUTIVE_SUBSEQUENCES_HPP <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fldll.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 14:52:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #ifdef WIN #ifndef _SVWIN_H #include <svwin.h> #endif // Statische DLL-Verwaltungs-Variablen static HINSTANCE hDLLInst = 0; // HANDLE der DLL /*************************************************************************** |* |* LibMain() |* |* Beschreibung Initialisierungsfunktion der DLL |* Ersterstellung TH 05.05.93 |* Letzte Aenderung TH 05.05.93 |* ***************************************************************************/ extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR ) { #ifndef WNT if ( nHeap ) UnlockData( 0 ); #endif hDLLInst = hDLL; return TRUE; } /*************************************************************************** |* |* WEP() |* |* Beschreibung DLL-Deinitialisierung |* Ersterstellung TH 05.05.93 |* Letzte Aenderung TH 05.05.93 |* ***************************************************************************/ extern "C" int CALLBACK WEP( int ) { return 1; } #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.450); FILE MERGED 2008/04/01 15:45:05 thb 1.5.450.2: #i85898# Stripping all external header guards 2008/03/31 13:01:55 rt 1.5.450.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fldll.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #ifdef WIN #include <svwin.h> // Statische DLL-Verwaltungs-Variablen static HINSTANCE hDLLInst = 0; // HANDLE der DLL /*************************************************************************** |* |* LibMain() |* |* Beschreibung Initialisierungsfunktion der DLL |* Ersterstellung TH 05.05.93 |* Letzte Aenderung TH 05.05.93 |* ***************************************************************************/ extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR ) { #ifndef WNT if ( nHeap ) UnlockData( 0 ); #endif hDLLInst = hDLL; return TRUE; } /*************************************************************************** |* |* WEP() |* |* Beschreibung DLL-Deinitialisierung |* Ersterstellung TH 05.05.93 |* Letzte Aenderung TH 05.05.93 |* ***************************************************************************/ extern "C" int CALLBACK WEP( int ) { return 1; } #endif <|endoftext|>