text
stringlengths
54
60.6k
<commit_before>#include <Style.h> using namespace canvas; Style::Style(const std::string & s) : color(s) { } Style::Style(const Color & _color) : color(_color) { } Style & Style::operator=(const std::string & s) { color = s; type = SOLID; return *this; } Style & Style::operator=(const Color & _color) { color = _color; type = SOLID; return *this; } <commit_msg>add include from GraphicsState.h, add function call operators<commit_after>#include <Style.h> #include <GraphicsState.h> using namespace canvas; #if 0 Style::Style(const std::string & s) : color(s) { } Style::Style(const Color & _color) : color(_color) { } #endif Style & Style::operator=(const std::string & s) { color = s; type = SOLID; return *this; } Style & Style::operator=(const Color & _color) { color = _color; type = SOLID; return *this; } GraphicsState & Style::operator()(const std::string & s) { color = s; type = SOLID; return *context; } GraphicsState & Style::operator()(const Color & _color) { color = _color; type = SOLID; return *context; } <|endoftext|>
<commit_before>// Copyright © 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. // // Author: Christian Kellner <kellner@bio.lmu.de> #include <nix/Value.hpp> #include <cassert> namespace nix { void Value::maybe_deallocte_string() { #ifndef _WIN32 if (dtype == DataType::String) { v_string.~basic_string(); } #endif } /**************/ /* setters */ void Value::set(none_t) { maybe_deallocte_string(); dtype = DataType::Nothing; v_bool = false; } void Value::set(bool value) { maybe_deallocte_string(); dtype = DataType::Bool; v_bool = value; } void Value::set(int32_t value) { maybe_deallocte_string(); dtype = DataType::Int32; v_int32 = value; } void Value::set(uint32_t value) { maybe_deallocte_string(); dtype = DataType::UInt32; v_uint32 = value; } void Value::set(int64_t value) { maybe_deallocte_string(); dtype = DataType::Int64; v_int64 = value; } void Value::set(uint64_t value) { maybe_deallocte_string(); dtype = DataType::UInt64; v_uint64 = value; } void Value::set(double value) { maybe_deallocte_string(); dtype = DataType::Double; v_double = value; } void Value::set(const std::string &value) { #ifndef _WIN32 //If the active member is not a string //we have to inialize the string object if (dtype != DataType::String) { new (&v_string) std::string(); } #endif dtype = DataType::String; v_string = value; } /**************/ /* getters */ void Value::get(none_t &tag) const { check_argument_type(DataType::Nothing); } void Value::get(bool &value) const { check_argument_type(DataType::Bool); value = v_bool; } void Value::get(int32_t &value) const { check_argument_type(DataType::Int32); value = v_int32; } void Value::get(uint32_t &value) const { check_argument_type(DataType::UInt32); value = v_uint32; } void Value::get(int64_t &value) const { check_argument_type(DataType::Int64); value = v_int64; } void Value::get(uint64_t &value) const { check_argument_type(DataType::UInt64); value = v_uint64; } void Value::get(double &value) const { check_argument_type(DataType::Double); value = v_double; } void Value::get(std::string &value) const { check_argument_type(DataType::String); value = v_string; } /* swap and swap helpers */ #if 0 //set to one to check that all supported DataTypes are handled #define CHECK_SUPOORTED_VALUES #endif #define DATATYPE_SUPPORT_NOT_IMPLEMENTED false void Value::swap(Value &other) { using std::swap; swap(uncertainty, other.uncertainty); swap(reference, other.reference); swap(encoder, other.encoder); swap(checksum, other.checksum); //now for the variant members if (dtype == other.dtype) { switch(dtype) { case DataType::Nothing: /* nothing to do, literally */ break; case DataType::Bool: swap(v_bool, other.v_bool); break; case DataType::Int32: swap(v_int32, other.v_int32); break; case DataType::UInt32: swap(v_uint32, other.v_uint32); break; case DataType::Int64: swap(v_int64, other.v_int64); break; case DataType::UInt64: swap(v_uint64, other.v_uint64); break; case DataType::Double: swap(v_double, other.v_double); break; case DataType::String: swap(v_string, other.v_string); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } swap(dtype, other.dtype); } else { switch(dtype) { case DataType::Nothing: swap_helper<none_t>(other); break; case DataType::Bool: swap_helper<bool>(other); break; case DataType::Int32: swap_helper<int32_t>(other); break; case DataType::UInt32: swap_helper<uint32_t>(other); break; case DataType::Int64: swap_helper<int64_t>(other); break; case DataType::UInt64: swap_helper<uint64_t>(other); break; case DataType::Double: swap_helper<double>(other); break; case DataType::String: swap_helper<std::string>(other); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } } void Value::assign_variant_from(const Value &other) { switch (other.dtype) { case DataType::Bool: set(other.v_bool); break; case DataType::Int32: set(other.v_int32); break; case DataType::UInt32: set(other.v_uint32); break; case DataType::Int64: set(other.v_int64); break; case DataType::UInt64: set(other.v_uint64); break; case DataType::Double: set(other.v_double); break; case DataType::String: set(other.v_string); break; case DataType::Nothing: set(none); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } bool Value::supports_type(DataType dtype) { switch (dtype) { case DataType::Bool: // we fall through here ... case DataType::Int32: // .oO ( what's happening ... case DataType::UInt32: // ... who am I ... case DataType::Int64: // ... why am I here ... case DataType::UInt64: // ... wind, is that a good name .. case DataType::Double: // ... lets call it tail ... case DataType::String: // ... round, ... ground, ... case DataType::Nothing: // ... hello ground ... return true; default: return false; } } /* operators and functions */ std::ostream& operator<<(std::ostream &out, const Value &value) { out << "Value{[" << value.type() << "] "; switch(value.type()) { case DataType::Bool: out << value.get<bool>(); break; case DataType::String: out << value.get<std::string>(); break; case DataType::Int32: out << value.get<int32_t>(); break; case DataType::UInt32: out << value.get<uint32_t>(); break; case DataType::Int64: out << value.get<int64_t>(); break; case DataType::UInt64: out << value.get<uint64_t>(); break; case DataType::Double: out << value.get<double>(); break; case DataType::Nothing: break; default: out << "IMPLEMENT ME"; break; } out << "}"; return out; } bool operator==(const Value &a, const Value &b) { if (a.type() != b.type()) { return false; } switch(a.type()) { case DataType::Nothing: return true; case DataType::Bool: return a.get<bool>() == b.get<bool>(); case DataType::Int32: return a.get<int32_t>() == b.get<int32_t>(); case DataType::UInt32: return a.get<uint32_t>() == b.get<uint32_t>(); case DataType::Int64: return a.get<int64_t>() == b.get<int64_t>(); case DataType::UInt64: return a.get<uint64_t>() == b.get<uint64_t>(); case DataType::Double: return a.get<double>() == b.get<double>(); case DataType::String: return a.get<std::string>() == b.get<std::string>(); #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); return false; #endif } } void swap(Value &a, Value &b) { a.swap(b); } } <commit_msg>[Value] add filename field to copy constructor<commit_after>// Copyright © 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. // // Author: Christian Kellner <kellner@bio.lmu.de> #include <nix/Value.hpp> #include <cassert> namespace nix { void Value::maybe_deallocte_string() { #ifndef _WIN32 if (dtype == DataType::String) { v_string.~basic_string(); } #endif } /**************/ /* setters */ void Value::set(none_t) { maybe_deallocte_string(); dtype = DataType::Nothing; v_bool = false; } void Value::set(bool value) { maybe_deallocte_string(); dtype = DataType::Bool; v_bool = value; } void Value::set(int32_t value) { maybe_deallocte_string(); dtype = DataType::Int32; v_int32 = value; } void Value::set(uint32_t value) { maybe_deallocte_string(); dtype = DataType::UInt32; v_uint32 = value; } void Value::set(int64_t value) { maybe_deallocte_string(); dtype = DataType::Int64; v_int64 = value; } void Value::set(uint64_t value) { maybe_deallocte_string(); dtype = DataType::UInt64; v_uint64 = value; } void Value::set(double value) { maybe_deallocte_string(); dtype = DataType::Double; v_double = value; } void Value::set(const std::string &value) { #ifndef _WIN32 //If the active member is not a string //we have to inialize the string object if (dtype != DataType::String) { new (&v_string) std::string(); } #endif dtype = DataType::String; v_string = value; } /**************/ /* getters */ void Value::get(none_t &tag) const { check_argument_type(DataType::Nothing); } void Value::get(bool &value) const { check_argument_type(DataType::Bool); value = v_bool; } void Value::get(int32_t &value) const { check_argument_type(DataType::Int32); value = v_int32; } void Value::get(uint32_t &value) const { check_argument_type(DataType::UInt32); value = v_uint32; } void Value::get(int64_t &value) const { check_argument_type(DataType::Int64); value = v_int64; } void Value::get(uint64_t &value) const { check_argument_type(DataType::UInt64); value = v_uint64; } void Value::get(double &value) const { check_argument_type(DataType::Double); value = v_double; } void Value::get(std::string &value) const { check_argument_type(DataType::String); value = v_string; } /* swap and swap helpers */ #if 0 //set to one to check that all supported DataTypes are handled #define CHECK_SUPOORTED_VALUES #endif #define DATATYPE_SUPPORT_NOT_IMPLEMENTED false void Value::swap(Value &other) { using std::swap; swap(uncertainty, other.uncertainty); swap(reference, other.reference); swap(filename, other.filename); swap(encoder, other.encoder); swap(checksum, other.checksum); //now for the variant members if (dtype == other.dtype) { switch(dtype) { case DataType::Nothing: /* nothing to do, literally */ break; case DataType::Bool: swap(v_bool, other.v_bool); break; case DataType::Int32: swap(v_int32, other.v_int32); break; case DataType::UInt32: swap(v_uint32, other.v_uint32); break; case DataType::Int64: swap(v_int64, other.v_int64); break; case DataType::UInt64: swap(v_uint64, other.v_uint64); break; case DataType::Double: swap(v_double, other.v_double); break; case DataType::String: swap(v_string, other.v_string); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } swap(dtype, other.dtype); } else { switch(dtype) { case DataType::Nothing: swap_helper<none_t>(other); break; case DataType::Bool: swap_helper<bool>(other); break; case DataType::Int32: swap_helper<int32_t>(other); break; case DataType::UInt32: swap_helper<uint32_t>(other); break; case DataType::Int64: swap_helper<int64_t>(other); break; case DataType::UInt64: swap_helper<uint64_t>(other); break; case DataType::Double: swap_helper<double>(other); break; case DataType::String: swap_helper<std::string>(other); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } } void Value::assign_variant_from(const Value &other) { switch (other.dtype) { case DataType::Bool: set(other.v_bool); break; case DataType::Int32: set(other.v_int32); break; case DataType::UInt32: set(other.v_uint32); break; case DataType::Int64: set(other.v_int64); break; case DataType::UInt64: set(other.v_uint64); break; case DataType::Double: set(other.v_double); break; case DataType::String: set(other.v_string); break; case DataType::Nothing: set(none); break; #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); #endif } } bool Value::supports_type(DataType dtype) { switch (dtype) { case DataType::Bool: // we fall through here ... case DataType::Int32: // .oO ( what's happening ... case DataType::UInt32: // ... who am I ... case DataType::Int64: // ... why am I here ... case DataType::UInt64: // ... wind, is that a good name .. case DataType::Double: // ... lets call it tail ... case DataType::String: // ... round, ... ground, ... case DataType::Nothing: // ... hello ground ... return true; default: return false; } } /* operators and functions */ std::ostream& operator<<(std::ostream &out, const Value &value) { out << "Value{[" << value.type() << "] "; switch(value.type()) { case DataType::Bool: out << value.get<bool>(); break; case DataType::String: out << value.get<std::string>(); break; case DataType::Int32: out << value.get<int32_t>(); break; case DataType::UInt32: out << value.get<uint32_t>(); break; case DataType::Int64: out << value.get<int64_t>(); break; case DataType::UInt64: out << value.get<uint64_t>(); break; case DataType::Double: out << value.get<double>(); break; case DataType::Nothing: break; default: out << "IMPLEMENT ME"; break; } out << "}"; return out; } bool operator==(const Value &a, const Value &b) { if (a.type() != b.type()) { return false; } switch(a.type()) { case DataType::Nothing: return true; case DataType::Bool: return a.get<bool>() == b.get<bool>(); case DataType::Int32: return a.get<int32_t>() == b.get<int32_t>(); case DataType::UInt32: return a.get<uint32_t>() == b.get<uint32_t>(); case DataType::Int64: return a.get<int64_t>() == b.get<int64_t>(); case DataType::UInt64: return a.get<uint64_t>() == b.get<uint64_t>(); case DataType::Double: return a.get<double>() == b.get<double>(); case DataType::String: return a.get<std::string>() == b.get<std::string>(); #ifndef CHECK_SUPPORTED_VALUES default: assert(DATATYPE_SUPPORT_NOT_IMPLEMENTED); return false; #endif } } void swap(Value &a, Value &b) { a.swap(b); } } <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <clutter/clutter.h> #include "clutter.hpp" #include "actor.hpp" namespace clutter { using namespace node; using namespace v8; Actor::Actor() : ObjectWrap() {} void Actor::Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); Local<String> name = String::NewSymbol("Actor"); PrototypeMethodsInit(tpl); target->Set(name, tpl->GetFunction()); } void Actor::PrototypeMethodsInit(Handle<FunctionTemplate> constructor_template) { HandleScope scope; NODE_SET_PROTOTYPE_METHOD(constructor_template, "show", Actor::Show); NODE_SET_PROTOTYPE_METHOD(constructor_template, "showAll", Actor::ShowAll); NODE_SET_PROTOTYPE_METHOD(constructor_template, "hide", Actor::Hide); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setOpacity", Actor::SetOpacity); NODE_SET_PROTOTYPE_METHOD(constructor_template, "resize", Actor::Resize); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setWidth", Actor::SetWidth); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getWidth", Actor::GetWidth); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setHeight", Actor::SetHeight); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getHeight", Actor::GetHeight); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setPosition", Actor::SetPosition); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setDepth", Actor::SetDepth); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getDepth", Actor::GetDepth); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setX", Actor::SetX); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getX", Actor::GetX); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setY", Actor::SetY); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getY", Actor::GetY); NODE_SET_PROTOTYPE_METHOD(constructor_template, "scale", Actor::Scale); } Handle<Value> Actor::New(const Arguments& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use the new operator to create instances of this object.")) ); } // Creates a new instance object of this type and wraps it. Actor* obj = new Actor(); obj->Wrap(args.This()); return args.This(); } Handle<Value> Actor::Show(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_show(instance); return args.This(); } Handle<Value> Actor::ShowAll(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_show_all(instance); return args.This(); } Handle<Value> Actor::Hide(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_hide(instance); return args.This(); } Handle<Value> Actor::SetOpacity(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_opacity(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::Resize(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber() && args[1]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_size(CLUTTER_ACTOR(instance), args[0]->NumberValue(), args[1]->NumberValue()); } return args.This(); } Handle<Value> Actor::SetWidth(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_width(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::GetWidth(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; return scope.Close( Number::New(clutter_actor_get_width(CLUTTER_ACTOR(instance))) ); } Handle<Value> Actor::SetHeight(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_height(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::GetHeight(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; return scope.Close( Number::New(clutter_actor_get_height(CLUTTER_ACTOR(instance))) ); } Handle<Value> Actor::SetPosition(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber() && args[1]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_position(CLUTTER_ACTOR(instance), args[0]->NumberValue(), args[1]->NumberValue()); } return args.This(); } Handle<Value> Actor::SetX(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_x(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::GetX(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; return scope.Close( Number::New(clutter_actor_get_x(CLUTTER_ACTOR(instance))) ); } Handle<Value> Actor::SetY(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_y(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::GetY(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; return scope.Close( Number::New(clutter_actor_get_y(CLUTTER_ACTOR(instance))) ); } Handle<Value> Actor::SetDepth(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_depth(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::GetDepth(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; return scope.Close( Number::New(clutter_actor_get_depth(CLUTTER_ACTOR(instance))) ); } Handle<Value> Actor::Scale(const Arguments &args) { HandleScope scope; static gdouble scale_x, scale_y; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; if (args[0]->IsUndefined() || args[0]->IsNull()) { Local<Object> o; clutter_actor_get_scale(CLUTTER_ACTOR(instance), &scale_x, &scale_y); /* create a JavaScript Object */ o = Object::New(); o->Set(String::New("scale_x"), Number::New(scale_x)); o->Set(String::New("scale_y"), Number::New(scale_y)); return scope.Close(o); } if (args[0]->IsNumber() && args[1]->IsNumber()) { if (args.Length() == 2) { clutter_actor_set_scale(CLUTTER_ACTOR(instance), args[0]->NumberValue(), args[1]->NumberValue()); } else if (args.Length() == 3) { if (args[2]->IsNumber()) clutter_actor_set_scale_with_gravity(CLUTTER_ACTOR(instance), args[0]->NumberValue(), args[1]->NumberValue(), (ClutterGravity)args[2]->Int32Value()); } else if (args.Length() == 4) { if (args[2]->IsNumber() && args[3]->IsNumber()) clutter_actor_set_scale_full(CLUTTER_ACTOR(instance), args[0]->NumberValue(), args[1]->NumberValue(), args[2]->NumberValue(), args[3]->NumberValue()); } } return args.This(); } } <commit_msg>convert argument to integer<commit_after>#include <v8.h> #include <node.h> #include <clutter/clutter.h> #include "clutter.hpp" #include "actor.hpp" namespace clutter { using namespace node; using namespace v8; Actor::Actor() : ObjectWrap() {} void Actor::Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); Local<String> name = String::NewSymbol("Actor"); PrototypeMethodsInit(tpl); target->Set(name, tpl->GetFunction()); } void Actor::PrototypeMethodsInit(Handle<FunctionTemplate> constructor_template) { HandleScope scope; NODE_SET_PROTOTYPE_METHOD(constructor_template, "show", Actor::Show); NODE_SET_PROTOTYPE_METHOD(constructor_template, "showAll", Actor::ShowAll); NODE_SET_PROTOTYPE_METHOD(constructor_template, "hide", Actor::Hide); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setOpacity", Actor::SetOpacity); NODE_SET_PROTOTYPE_METHOD(constructor_template, "resize", Actor::Resize); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setWidth", Actor::SetWidth); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getWidth", Actor::GetWidth); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setHeight", Actor::SetHeight); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getHeight", Actor::GetHeight); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setPosition", Actor::SetPosition); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setDepth", Actor::SetDepth); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getDepth", Actor::GetDepth); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setX", Actor::SetX); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getX", Actor::GetX); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setY", Actor::SetY); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getY", Actor::GetY); NODE_SET_PROTOTYPE_METHOD(constructor_template, "scale", Actor::Scale); } Handle<Value> Actor::New(const Arguments& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use the new operator to create instances of this object.")) ); } // Creates a new instance object of this type and wraps it. Actor* obj = new Actor(); obj->Wrap(args.This()); return args.This(); } Handle<Value> Actor::Show(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_show(instance); return args.This(); } Handle<Value> Actor::ShowAll(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_show_all(instance); return args.This(); } Handle<Value> Actor::Hide(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_hide(instance); return args.This(); } Handle<Value> Actor::SetOpacity(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_opacity(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::Resize(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber() && args[1]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_size(CLUTTER_ACTOR(instance), args[0]->NumberValue(), args[1]->NumberValue()); } return args.This(); } Handle<Value> Actor::SetWidth(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_width(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::GetWidth(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; return scope.Close( Number::New(clutter_actor_get_width(CLUTTER_ACTOR(instance))) ); } Handle<Value> Actor::SetHeight(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_height(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::GetHeight(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; return scope.Close( Number::New(clutter_actor_get_height(CLUTTER_ACTOR(instance))) ); } Handle<Value> Actor::SetPosition(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber() && args[1]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_position(CLUTTER_ACTOR(instance), args[0]->NumberValue(), args[1]->NumberValue()); } return args.This(); } Handle<Value> Actor::SetX(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_x(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::GetX(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; return scope.Close( Number::New(clutter_actor_get_x(CLUTTER_ACTOR(instance))) ); } Handle<Value> Actor::SetY(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_y(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::GetY(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; return scope.Close( Number::New(clutter_actor_get_y(CLUTTER_ACTOR(instance))) ); } Handle<Value> Actor::SetDepth(const Arguments &args) { HandleScope scope; if (args[0]->IsNumber()) { ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; clutter_actor_set_depth(CLUTTER_ACTOR(instance), args[0]->NumberValue()); } return args.This(); } Handle<Value> Actor::GetDepth(const Arguments &args) { HandleScope scope; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; return scope.Close( Number::New(clutter_actor_get_depth(CLUTTER_ACTOR(instance))) ); } Handle<Value> Actor::Scale(const Arguments &args) { HandleScope scope; static gdouble scale_x, scale_y; ClutterActor *instance = ObjectWrap::Unwrap<Actor>(args.This())->_actor; if (args[0]->IsUndefined() || args[0]->IsNull()) { Local<Object> o; clutter_actor_get_scale(CLUTTER_ACTOR(instance), &scale_x, &scale_y); /* create a JavaScript Object */ o = Object::New(); o->Set(String::New("scale_x"), Number::New(scale_x)); o->Set(String::New("scale_y"), Number::New(scale_y)); return scope.Close(o); } if (args[0]->IsNumber() && args[1]->IsNumber()) { if (args.Length() == 2) { clutter_actor_set_scale(CLUTTER_ACTOR(instance), args[0]->NumberValue(), args[1]->NumberValue()); } else if (args.Length() == 3) { if (args[2]->IsNumber()) clutter_actor_set_scale_with_gravity(CLUTTER_ACTOR(instance), args[0]->NumberValue(), args[1]->NumberValue(), (ClutterGravity)args[2]->ToInteger()->Value()); } else if (args.Length() == 4) { if (args[2]->IsNumber() && args[3]->IsNumber()) clutter_actor_set_scale_full(CLUTTER_ACTOR(instance), args[0]->NumberValue(), args[1]->NumberValue(), args[2]->NumberValue(), args[3]->NumberValue()); } } return args.This(); } } <|endoftext|>
<commit_before>/* This file is part of the Multivariate Splines library. Copyright (C) 2012 Bjarne Grimstad (bjarne.grimstad@gmail.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "include/basis.h" #include "include/mykroneckerproduct.h" #include "unsupported/Eigen/KroneckerProduct" #include <iostream> using std::cout; using std::endl; namespace MultivariateSplines { Basis::Basis() { } Basis::Basis(std::vector< std::vector<double> > &X, std::vector<unsigned int> basisDegrees) : Basis(X, basisDegrees, KnotVectorType::FREE) { } Basis::Basis(std::vector< std::vector<double> > &X, std::vector<unsigned int> basisDegrees, KnotVectorType knotVectorType) { assert(X.size() == basisDegrees.size()); setUnivariateBases(X, basisDegrees, knotVectorType); } void Basis::setUnivariateBases(std::vector< std::vector<double> > &X, std::vector<unsigned int> &basisDegrees, KnotVectorType knotVectorType) { bases.clear(); numVariables = X.size(); for (unsigned int i = 0; i < numVariables; i++) { bases.push_back(Basis1D(X.at(i), basisDegrees.at(i), knotVectorType)); } } SparseVector Basis::eval(const DenseVector &x) const { // Set correct starting size and values: one element of 1. SparseMatrix tv1(1,1); //tv1.resize(1); tv1.reserve(1); tv1.insert(0,0) = 1; SparseMatrix tv2 = tv1; // Evaluate all basisfunctions in each dimension i and generate the tensor product of the function values for (int dim = 0; dim < x.size(); dim++) { SparseVector xi = bases.at(dim).evaluate(x(dim)); // Avoid matrix copy if (dim % 2 == 0) { tv1 = kroneckerProduct(tv2, xi); // tv1 = tv1 x xi } else { tv2 = kroneckerProduct(tv1, xi); // tv2 = tv1 x xi } } // Return correct vector if(tv1.size() == numBasisFunctions()) { return tv1; } return tv2; } // Old implementation of Jacobian DenseMatrix Basis::evalBasisJacobianOld(DenseVector &x) const { // Jacobian basis matrix DenseMatrix J; J.setZero(numBasisFunctions(), numVariables); // Calculate partial derivatives for (unsigned int i = 0; i < numVariables; i++) { // One column in basis jacobian DenseVector bi; bi.setOnes(1); for (unsigned int j = 0; j < numVariables; j++) { DenseVector temp = bi; DenseVector xi; if(j == i) { // Differentiated basis xi = bases.at(j).evaluateFirstDerivative(x(j)); } else { // Normal basis xi = bases.at(j).evaluate(x(j)); } bi = kroneckerProduct(temp, xi); //bi = kroneckerProduct(bi, xi).eval(); } // Fill out column J.block(0,i,bi.rows(),1) = bi.block(0,0,bi.rows(),1); } return J; } SparseMatrix Basis::evalBasisJacobian(DenseVector &x) const { // Jacobian basis matrix SparseMatrix J(numBasisFunctions(), numVariables); //J.setZero(numBasisFunctions(), numInputs); // Calculate partial derivatives for(unsigned int i = 0; i < numVariables; i++) { // One column in basis jacobian SparseMatrix Ji(1,1); Ji.insert(0,0) = 1; for (unsigned int j = 0; j < numVariables; j++) { SparseMatrix temp = Ji; SparseMatrix xi; if(j == i) { // Differentiated basis xi = bases.at(j).evaluateDerivative(x(j),1); } else { // Normal basis xi = bases.at(j).evaluate(x(j)); } Ji = kroneckerProduct(temp, xi); //myKroneckerProduct(temp,xi,Ji); //Ji = kroneckerProduct(Ji, xi).eval(); } // Fill out column for(int k = 0; k < Ji.outerSize(); ++k) for(SparseMatrix::InnerIterator it(Ji,k); it; ++it) { if(it.value() != 0) J.insert(it.row(),i) = it.value(); } //J.block(0,i,Ji.rows(),1) = bi.block(0,0,Ji.rows(),1); } J.makeCompressed(); return J; } SparseMatrix Basis::evalBasisHessian(DenseVector &x) const { // Hessian basis matrix /* Hij = B1 x ... x DBi x ... x DBj x ... x Bn * (Hii = B1 x ... x DDBi x ... x Bn) * Where B are basis functions evaluated at x, * DB are the derivative of the basis functions, * and x is the kronecker product. * Hij is in R^(numBasisFunctions x 1) * so that basis hessian H is in R^(numBasisFunctions*numInputs x numInputs) * The real B-spline Hessian is calculated as (c^T x 1^(numInputs x 1))*H */ SparseMatrix H(numBasisFunctions()*numVariables, numVariables); //H.setZero(numBasisFunctions()*numInputs, numInputs); // Calculate partial derivatives // Utilizing that Hessian is symmetric // Filling out lower left triangular for(unsigned int i = 0; i < numVariables; i++) // row { for(unsigned int j = 0; j <= i; j++) // col { // One column in basis jacobian SparseMatrix Hi(1,1); Hi.insert(0,0) = 1; for(unsigned int k = 0; k < numVariables; k++) { SparseMatrix temp = Hi; SparseMatrix Bk; if(i == j && k == i) { // Diagonal element Bk = bases.at(k).evaluateDerivative(x(k),2); } else if(k == i || k == j) { Bk = bases.at(k).evaluateDerivative(x(k),1); } else { Bk = bases.at(k).evaluate(x(k)); } Hi = kroneckerProduct(temp, Bk); } // Fill out column for(int k = 0; k < Hi.outerSize(); ++k) for(SparseMatrix::InnerIterator it(Hi,k); it; ++it) { if(it.value() != 0) { int row = i*numBasisFunctions()+it.row(); int col = j; H.insert(row,col) = it.value(); } } } } H.makeCompressed(); return H; } bool Basis::insertKnots(SparseMatrix &A, double tau, unsigned int dim, unsigned int multiplicity) { A.resize(1,1); A.insert(0,0) = 1; // Calculate multivariate knot insertion matrix for(unsigned int i = 0; i < numVariables; i++) { SparseMatrix temp = A; SparseMatrix Ai; if(i == dim) { // Build knot insertion matrix if (!bases.at(i).insertKnots(Ai, tau, multiplicity)) return false; } else { // No insertion - identity matrix int m = bases.at(i).numBasisFunctions(); Ai.resize(m,m); Ai.setIdentity(); } //A = kroneckerProduct(temp, Ai); myKroneckerProduct(temp,Ai,A); } A.makeCompressed(); return true; } bool Basis::refineKnots(SparseMatrix &A) { A.resize(1,1); A.insert(0,0) = 1; for(unsigned int i = 0; i < numVariables; i++) { SparseMatrix temp = A; SparseMatrix Ai; if(!bases.at(i).refineKnots(Ai)) return false; //A = kroneckerProduct(temp, Ai); myKroneckerProduct(temp,Ai,A); } A.makeCompressed(); return true; } bool Basis::reduceSupport(std::vector<double>& lb, std::vector<double>& ub, SparseMatrix &A) { assert(lb.size() == ub.size()); assert(lb.size() == numVariables); A.resize(1,1); A.insert(0,0) = 1; for(unsigned int i = 0; i < numVariables; i++) { SparseMatrix temp = A; SparseMatrix Ai; if(!bases.at(i).reduceSupport(lb.at(i), ub.at(i), Ai)) return false; //A = kroneckerProduct(temp, Ai); myKroneckerProduct(temp, Ai, A); } A.makeCompressed(); return true; } unsigned int Basis::getBasisDegree(unsigned int dim) const { return bases.at(dim).getBasisDegree(); } unsigned int Basis::numBasisFunctions(unsigned int dim) const { return bases.at(dim).numBasisFunctions(); } unsigned int Basis::numBasisFunctions() const { unsigned int prod = 1; for(unsigned int dim = 0; dim < numVariables; dim++) { prod *= bases.at(dim).numBasisFunctions(); } return prod; } Basis1D Basis::getSingleBasis(int dim) { return bases.at(dim); } std::vector<double> Basis::getKnotVector(int dim) const { return bases.at(dim).getKnotVector(); } std::vector< std::vector<double> > Basis::getKnotVectors() const { std::vector< std::vector<double> > knots; for(unsigned int i = 0; i < numVariables; i++) knots.push_back(bases.at(i).getKnotVector()); return knots; } unsigned int Basis::getKnotMultiplicity(const unsigned int& dim, const double& tau) const { return bases.at(dim).knotMultiplicity(tau); } double Basis::getKnotValue(int dim, int index) const { return bases.at(dim).getKnotValue(index); } unsigned int Basis::getLargestKnotInterval(unsigned int dim) const { return bases.at(dim).indexLongestInterval(); } std::vector<int> Basis::getTensorIndexDimension() const { std::vector<int> ret; for(unsigned int dim = 0; dim < numVariables; dim++) { ret.push_back(bases.at(dim).numBasisFunctions()); } return ret; } std::vector<int> Basis::getTensorIndexDimensionTarget() const { std::vector<int> ret; for(unsigned int dim = 0; dim < numVariables; dim++) { ret.push_back(bases.at(dim).numBasisFunctionsTarget() ); } return ret; } int Basis::supportedPrInterval() const { int ret = 1; for(unsigned int dim = 0; dim < numVariables; dim++) { ret *= (bases.at(dim).getBasisDegree() + 1); } return ret; } bool Basis::valueInsideSupport(DenseVector &x) const { if(x.size() != numVariables) { return false; } for(unsigned int dim = 0; dim < numVariables; dim++) { if(!bases.at(dim).insideSupport(x(dim))) { return false; } } return true; } std::vector<double> Basis::getSupportLowerBound() const { std::vector<double> lb; for(unsigned int dim = 0; dim < numVariables; dim++) { std::vector<double> knots = bases.at(dim).getKnotVector(); lb.push_back(knots.front()); } return lb; } std::vector<double> Basis::getSupportUpperBound() const { std::vector<double> ub; for(unsigned int dim = 0; dim < numVariables; dim++) { std::vector<double> knots = bases.at(dim).getKnotVector(); ub.push_back(knots.back()); } return ub; } } // namespace MultivariateSplines <commit_msg>Removed some unnecessary spacing<commit_after>/* This file is part of the Multivariate Splines library. Copyright (C) 2012 Bjarne Grimstad (bjarne.grimstad@gmail.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "include/basis.h" #include "include/mykroneckerproduct.h" #include "unsupported/Eigen/KroneckerProduct" #include <iostream> using std::cout; using std::endl; namespace MultivariateSplines { Basis::Basis() { } Basis::Basis(std::vector< std::vector<double> > &X, std::vector<unsigned int> basisDegrees) : Basis(X, basisDegrees, KnotVectorType::FREE) { } Basis::Basis(std::vector< std::vector<double> > &X, std::vector<unsigned int> basisDegrees, KnotVectorType knotVectorType) { assert(X.size() == basisDegrees.size()); setUnivariateBases(X, basisDegrees, knotVectorType); } void Basis::setUnivariateBases(std::vector< std::vector<double> > &X, std::vector<unsigned int> &basisDegrees, KnotVectorType knotVectorType) { bases.clear(); numVariables = X.size(); for(unsigned int i = 0; i < numVariables; i++) { bases.push_back(Basis1D(X.at(i), basisDegrees.at(i), knotVectorType)); } } SparseVector Basis::eval(const DenseVector &x) const { // Set correct starting size and values: one element of 1. SparseMatrix tv1(1,1); //tv1.resize(1); tv1.reserve(1); tv1.insert(0,0) = 1; SparseMatrix tv2 = tv1; // Evaluate all basisfunctions in each dimension i and generate the tensor product of the function values for(int dim = 0; dim < x.size(); dim++) { SparseVector xi = bases.at(dim).evaluate(x(dim)); // Avoid matrix copy if(dim % 2 == 0) { tv1 = kroneckerProduct(tv2, xi); // tv1 = tv1 x xi } else { tv2 = kroneckerProduct(tv1, xi); // tv2 = tv1 x xi } } // Return correct vector if(tv1.size() == numBasisFunctions()) { return tv1; } return tv2; } // Old implementation of Jacobian DenseMatrix Basis::evalBasisJacobianOld(DenseVector &x) const { // Jacobian basis matrix DenseMatrix J; J.setZero(numBasisFunctions(), numVariables); // Calculate partial derivatives for(unsigned int i = 0; i < numVariables; i++) { // One column in basis jacobian DenseVector bi; bi.setOnes(1); for(unsigned int j = 0; j < numVariables; j++) { DenseVector temp = bi; DenseVector xi; if(j == i) { // Differentiated basis xi = bases.at(j).evaluateFirstDerivative(x(j)); } else { // Normal basis xi = bases.at(j).evaluate(x(j)); } bi = kroneckerProduct(temp, xi); //bi = kroneckerProduct(bi, xi).eval(); } // Fill out column J.block(0,i,bi.rows(),1) = bi.block(0,0,bi.rows(),1); } return J; } SparseMatrix Basis::evalBasisJacobian(DenseVector &x) const { // Jacobian basis matrix SparseMatrix J(numBasisFunctions(), numVariables); //J.setZero(numBasisFunctions(), numInputs); // Calculate partial derivatives for(unsigned int i = 0; i < numVariables; i++) { // One column in basis jacobian SparseMatrix Ji(1,1); Ji.insert(0,0) = 1; for(unsigned int j = 0; j < numVariables; j++) { SparseMatrix temp = Ji; SparseMatrix xi; if(j == i) { // Differentiated basis xi = bases.at(j).evaluateDerivative(x(j),1); } else { // Normal basis xi = bases.at(j).evaluate(x(j)); } Ji = kroneckerProduct(temp, xi); //myKroneckerProduct(temp,xi,Ji); //Ji = kroneckerProduct(Ji, xi).eval(); } // Fill out column for(int k = 0; k < Ji.outerSize(); ++k) for(SparseMatrix::InnerIterator it(Ji,k); it; ++it) { if(it.value() != 0) J.insert(it.row(),i) = it.value(); } //J.block(0,i,Ji.rows(),1) = bi.block(0,0,Ji.rows(),1); } J.makeCompressed(); return J; } SparseMatrix Basis::evalBasisHessian(DenseVector &x) const { // Hessian basis matrix /* Hij = B1 x ... x DBi x ... x DBj x ... x Bn * (Hii = B1 x ... x DDBi x ... x Bn) * Where B are basis functions evaluated at x, * DB are the derivative of the basis functions, * and x is the kronecker product. * Hij is in R^(numBasisFunctions x 1) * so that basis hessian H is in R^(numBasisFunctions*numInputs x numInputs) * The real B-spline Hessian is calculated as (c^T x 1^(numInputs x 1))*H */ SparseMatrix H(numBasisFunctions()*numVariables, numVariables); //H.setZero(numBasisFunctions()*numInputs, numInputs); // Calculate partial derivatives // Utilizing that Hessian is symmetric // Filling out lower left triangular for(unsigned int i = 0; i < numVariables; i++) // row { for(unsigned int j = 0; j <= i; j++) // col { // One column in basis jacobian SparseMatrix Hi(1,1); Hi.insert(0,0) = 1; for(unsigned int k = 0; k < numVariables; k++) { SparseMatrix temp = Hi; SparseMatrix Bk; if(i == j && k == i) { // Diagonal element Bk = bases.at(k).evaluateDerivative(x(k),2); } else if(k == i || k == j) { Bk = bases.at(k).evaluateDerivative(x(k),1); } else { Bk = bases.at(k).evaluate(x(k)); } Hi = kroneckerProduct(temp, Bk); } // Fill out column for(int k = 0; k < Hi.outerSize(); ++k) for(SparseMatrix::InnerIterator it(Hi,k); it; ++it) { if(it.value() != 0) { int row = i*numBasisFunctions()+it.row(); int col = j; H.insert(row,col) = it.value(); } } } } H.makeCompressed(); return H; } bool Basis::insertKnots(SparseMatrix &A, double tau, unsigned int dim, unsigned int multiplicity) { A.resize(1,1); A.insert(0,0) = 1; // Calculate multivariate knot insertion matrix for(unsigned int i = 0; i < numVariables; i++) { SparseMatrix temp = A; SparseMatrix Ai; if(i == dim) { // Build knot insertion matrix if (!bases.at(i).insertKnots(Ai, tau, multiplicity)) return false; } else { // No insertion - identity matrix int m = bases.at(i).numBasisFunctions(); Ai.resize(m,m); Ai.setIdentity(); } //A = kroneckerProduct(temp, Ai); myKroneckerProduct(temp,Ai,A); } A.makeCompressed(); return true; } bool Basis::refineKnots(SparseMatrix &A) { A.resize(1,1); A.insert(0,0) = 1; for(unsigned int i = 0; i < numVariables; i++) { SparseMatrix temp = A; SparseMatrix Ai; if(!bases.at(i).refineKnots(Ai)) return false; //A = kroneckerProduct(temp, Ai); myKroneckerProduct(temp,Ai,A); } A.makeCompressed(); return true; } bool Basis::reduceSupport(std::vector<double>& lb, std::vector<double>& ub, SparseMatrix &A) { assert(lb.size() == ub.size()); assert(lb.size() == numVariables); A.resize(1,1); A.insert(0,0) = 1; for(unsigned int i = 0; i < numVariables; i++) { SparseMatrix temp = A; SparseMatrix Ai; if(!bases.at(i).reduceSupport(lb.at(i), ub.at(i), Ai)) return false; //A = kroneckerProduct(temp, Ai); myKroneckerProduct(temp, Ai, A); } A.makeCompressed(); return true; } unsigned int Basis::getBasisDegree(unsigned int dim) const { return bases.at(dim).getBasisDegree(); } unsigned int Basis::numBasisFunctions(unsigned int dim) const { return bases.at(dim).numBasisFunctions(); } unsigned int Basis::numBasisFunctions() const { unsigned int prod = 1; for(unsigned int dim = 0; dim < numVariables; dim++) { prod *= bases.at(dim).numBasisFunctions(); } return prod; } Basis1D Basis::getSingleBasis(int dim) { return bases.at(dim); } std::vector<double> Basis::getKnotVector(int dim) const { return bases.at(dim).getKnotVector(); } std::vector< std::vector<double> > Basis::getKnotVectors() const { std::vector< std::vector<double> > knots; for(unsigned int i = 0; i < numVariables; i++) knots.push_back(bases.at(i).getKnotVector()); return knots; } unsigned int Basis::getKnotMultiplicity(const unsigned int& dim, const double& tau) const { return bases.at(dim).knotMultiplicity(tau); } double Basis::getKnotValue(int dim, int index) const { return bases.at(dim).getKnotValue(index); } unsigned int Basis::getLargestKnotInterval(unsigned int dim) const { return bases.at(dim).indexLongestInterval(); } std::vector<int> Basis::getTensorIndexDimension() const { std::vector<int> ret; for(unsigned int dim = 0; dim < numVariables; dim++) { ret.push_back(bases.at(dim).numBasisFunctions()); } return ret; } std::vector<int> Basis::getTensorIndexDimensionTarget() const { std::vector<int> ret; for(unsigned int dim = 0; dim < numVariables; dim++) { ret.push_back(bases.at(dim).numBasisFunctionsTarget() ); } return ret; } int Basis::supportedPrInterval() const { int ret = 1; for(unsigned int dim = 0; dim < numVariables; dim++) { ret *= (bases.at(dim).getBasisDegree() + 1); } return ret; } bool Basis::valueInsideSupport(DenseVector &x) const { if(x.size() != numVariables) { return false; } for(unsigned int dim = 0; dim < numVariables; dim++) { if(!bases.at(dim).insideSupport(x(dim))) { return false; } } return true; } std::vector<double> Basis::getSupportLowerBound() const { std::vector<double> lb; for(unsigned int dim = 0; dim < numVariables; dim++) { std::vector<double> knots = bases.at(dim).getKnotVector(); lb.push_back(knots.front()); } return lb; } std::vector<double> Basis::getSupportUpperBound() const { std::vector<double> ub; for(unsigned int dim = 0; dim < numVariables; dim++) { std::vector<double> knots = bases.at(dim).getKnotVector(); ub.push_back(knots.back()); } return ub; } } // namespace MultivariateSplines <|endoftext|>
<commit_before>#include <iostream> #include <SDL2/SDL.h> void logSdlError(std::ostream &os, const std::string &msg) { os << msg << " error: " << SDL_GetError() << std::endl; } int main(int argc, char **argv) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { logSdlError(std::cerr, "SDL_Init"); return 1; } } <commit_msg>Making a pixed green.<commit_after>#include <iostream> #include <SDL2/SDL.h> void logSdlError(std::ostream &os, const std::string &msg) { os << msg << " error: " << SDL_GetError() << std::endl; } void putPixel(SDL_Surface *surface, int x, int y, Uint32 pixel) { int bpp = surface->format->BytesPerPixel; Uint8 *p = (Uint8*)surface->pixels + y * surface->pitch + x * bpp; switch (bpp) { case 1: *p = pixel; break; case 2: *(Uint16 *)p = pixel; break; case 3: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) { p[0] = (pixel >> 16) & 0xff; p[1] = (pixel >> 8) & 0xff; p[2] = pixel & 0xff; } else { p[0] = pixel & 0xff; p[1] = (pixel >> 8) & 0xff; p[2] = (pixel >> 16) & 0xff; } break; case 4: *(Uint32 *)p = pixel; break; } } int main(int argc, char **argv) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { logSdlError(std::cerr, "SDL_Init"); return 1; } SDL_Window* window = SDL_CreateWindow("Blamo", 100, 100, 640, 480, SDL_WINDOW_SHOWN); if (window == nullptr) { logSdlError(std::cerr, "SDL_CreateWindow"); return 2; } // Create a surface and directly access the pixels SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer == nullptr) { logSdlError(std::cerr, "SDL_CreateRenderer"); return 3; } Uint32 format = SDL_GetWindowPixelFormat(window); int bpp; Uint32 Rmask, Gmask, Bmask, Amask = 0; SDL_PixelFormatEnumToMasks(format, &bpp, &Rmask, &Gmask, &Bmask, &Amask); SDL_Surface* field = SDL_CreateRGBSurface(0, 640, 480, 32, Rmask, Gmask, Bmask, Amask); Uint32 ground = SDL_MapRGB(field->format, 0, 255, 0); SDL_LockSurface(field); putPixel(field, 10, 10, ground); SDL_UnlockSurface(field); SDL_Texture *texture = nullptr; texture = SDL_CreateTextureFromSurface(renderer, field); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); SDL_Delay(2000); SDL_FreeSurface(field); SDL_DestroyTexture(texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>#include "board.hpp" #include <cstring> #include <boost/lexical_cast.hpp> #include "exception.hpp" #include "walk_move.hpp" namespace Quoridor { Board::Board(int row_num, int col_num) : sides_(), pawn_sides_(), walls_(), occ_nodes_(), pawn_nodes_(), bg_() { set_size(row_num, col_num); sides_.push_back(std::pair<int, int>(0, 0)); sides_.push_back(std::pair<int, int>(2, 0)); sides_.push_back(std::pair<int, int>(1, 0)); sides_.push_back(std::pair<int, int>(3, 0)); } Board::~Board() { } void Board::set_size(int row_num, int col_num) { if (row_num <= 0) { throw Exception("illegal row number: " + boost::lexical_cast<std::string>(row_num)); } if (col_num <= 0) { throw Exception("illegal column number: " + boost::lexical_cast<std::string>(col_num)); } if (row_num % 2 == 0) { throw Exception("row number must be odd: " + boost::lexical_cast<std::string>(row_num)); } if (col_num % 2 == 0) { throw Exception("column number must be odd: " + boost::lexical_cast<std::string>(col_num)); } row_num_ = row_num; col_num_ = col_num; bg_.set_size(row_num_, col_num_); } int Board::next_side() const { for (auto &side : sides_) { if (side.second == 0) { side.second = 1; return side.first; } } return -1; } int Board::add_pawn(std::shared_ptr<Pawn> pawn) { pawn_sides_[pawn] = next_side(); int n; switch (pawn_sides_[pawn]) { case 0: n = col_num_ / 2; break; case 1: n = (row_num_ / 2) * col_num_; break; case 2: n = (row_num_ - 1) * col_num_ + col_num_ / 2; break; case 3: n = (row_num_ / 2) * col_num_ + col_num_ - 1; break; default: throw Exception("invalid pawn side: " + boost::lexical_cast<std::string>(pawn_sides_[pawn])); } occ_nodes_[n] = pawn; pawn_nodes_[pawn] = n; bg_.block_neighbours(n); return 0; } bool Board::is_occupied(int node) const { return occ_nodes_.find(node) != occ_nodes_.end(); } pos_t Board::pawn_pos(std::shared_ptr<Pawn> pawn) const { int node = pawn_nodes_.at(pawn); pos_t pos; pos.row = row(node); pos.col = col(node); return pos; } bool Board::is_at_opposite_side(std::shared_ptr<Pawn> pawn) const { int n = pawn_nodes_.at(pawn); switch (pawn_sides_.at(pawn)) { case 0: return row(n) == row_num_ - 1; case 1: return col(n) == col_num_ - 1; case 2: return row(n) == 0; case 3: return col(n) == 0; default: throw Exception("invalid board side: " + boost::lexical_cast<std::string>(pawn_sides_.at(pawn))); } } int Board::make_walking_move(std::shared_ptr<Pawn> pawn, int goal_node) { int cur_node = pawn_nodes_[pawn]; if (!is_possible_move(cur_node, goal_node)) { return -1; } // update pawn's position occ_nodes_.erase(pawn_nodes_[pawn]); bg_.unblock_neighbours(pawn_nodes_[pawn]); pawn_nodes_[pawn] = goal_node; occ_nodes_[goal_node] = pawn; bg_.block_neighbours(goal_node); return 0; } int Board::add_wall(const Wall &wall) { std::vector<std::pair<int, int>> edges; if (try_add_wall(wall, &edges) < 0) { return -1; } walls_[wall.orientation()][wall.line()].insert(std::map<int, Wall>::value_type(wall.start_pos(), Wall(wall))); for (auto edge : edges) { bg_.remove_edges(edge.first, edge.second); } return 0; } int Board::try_add_wall(const Wall &wall, std::vector<std::pair<int, int>> *edges) { int line_lim = (wall.orientation() ? col_num() : row_num()) - 1; int start_pos_lim = (wall.orientation() ? row_num() : col_num()) - 1; if ((wall.line() >= line_lim) || (wall.end_pos() > start_pos_lim)) { return -1; } if (wall_intersects(wall)) { return -1; } bg_.reset_filters(); int node1; int node2; int node_tmp; if (wall.orientation() == 0) { for (int i = 0; i < wall.cnt(); ++i) { node1 = wall.line() * col_num_ + wall.start_pos() + i; node2 = (wall.line() + 1) * col_num_ + wall.start_pos() + i; bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = (wall.line() + 2) * col_num_ + wall.start_pos() + i; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = (wall.line() - 1) * col_num_ + wall.start_pos() + i; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = (wall.line() + 1) * col_num_ + wall.start_pos() + j; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = wall.line() * col_num_ + wall.start_pos() + j; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } else { for (int i = 0; i < wall.cnt(); ++i) { node1 = (wall.start_pos() + i) * row_num_ + wall.line(); node2 = (wall.start_pos() + i) * row_num_ + wall.line() + 1; bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = (wall.start_pos() + i) * row_num_ + wall.line() + 2; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = (wall.start_pos() + i) * row_num_ + wall.line() - 1; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = (wall.start_pos() + j) * row_num_ + wall.line() + 1; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = (wall.start_pos() + j) * row_num_ + wall.line(); if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } bool path_blocked = false; for (auto pawn_node : pawn_nodes_) { std::vector<int> nodes; int side = (pawn_sides_[pawn_node.first] + 2) % 4; path_blocked = true; side_nodes(side, &nodes); for (auto node : nodes) { if (bg_.is_path_exists(pawn_node.second, node)) { path_blocked = false; break; } } // wall blocks all pathes to the opposite side for one of pawns if (path_blocked) { break; } } if (path_blocked) { return -1; } return 0; } void Board::pawn_final_nodes(std::shared_ptr<Pawn> pawn, std::vector<int> *nodes) const { int side = (pawn_sides_.at(pawn) + 2) % 4; side_nodes(side, nodes); } bool Board::get_path(std::shared_ptr<Pawn> pawn, int end_node, std::list<int> *nodes) const { return bg_.find_path(pawn_nodes_.at(pawn), end_node, nodes); } bool Board::is_win(std::shared_ptr<Pawn> pawn) const { return is_at_opposite_side(pawn); } bool Board::is_possible_move(int cur_node, int goal_node) const { return bg_.is_adjacent(cur_node, goal_node); } bool Board::wall_intersects(const Wall &wall) const { // check intersections if (walls_.count(1 - wall.orientation()) > 0) { for (int i = 0; i < wall.cnt() - 1; ++i) { // there are walls on the intersected line if (walls_.at(1 - wall.orientation()).count(wall.start_pos()) != 0) { auto line_walls = walls_.at(1 - wall.orientation()).at(wall.start_pos() + i); auto it = line_walls.upper_bound(wall.line()); // all walls on the line are settled before new wall if (it == line_walls.end()) { auto rit = line_walls.rbegin(); if (rit->second.end_pos() >= wall.line()) { return true; } } else if (it != line_walls.begin()) { --it; if (it->second.end_pos() >= wall.line()) { return true; } } } } } // check overlaps if (walls_.count(wall.orientation()) > 0) { if (walls_.at(wall.orientation()).count(wall.line()) != 0) { auto line_walls = walls_.at(wall.orientation()).at(wall.line()); auto it = line_walls.upper_bound(wall.start_pos()); // all walls on the line are settled before new wall if (it == line_walls.end()) { auto rit = line_walls.rbegin(); if (rit->second.end_pos() >= wall.start_pos()) { return true; } } else { // check if new wall overlaps over next wall on the line if (wall.end_pos() >= it->second.start_pos()) { return true; } if (it != line_walls.begin()) { --it; if (it->second.end_pos() >= wall.start_pos()) { return true; } } } } } return false; } void Board::side_nodes(int side, std::vector<int> *nodes) const { switch (side) { case 0: for (int i = 0; i < col_num_; ++i) { nodes->push_back(i); } break; case 1: for (int i = 0; i < row_num_; ++i) { nodes->push_back(i * col_num_); } break; case 2: for (int i = 0; i < col_num_; ++i) { nodes->push_back((row_num_ - 1 ) * col_num_ + i); } break; case 3: for (int i = 0; i < row_num_; ++i) { nodes->push_back(i * col_num_ + col_num_ - 1); } break; default: break; } } } /* namespace Quoridor */ <commit_msg>Fix Board ctor.<commit_after>#include "board.hpp" #include <cstring> #include <boost/lexical_cast.hpp> #include "exception.hpp" #include "walk_move.hpp" namespace Quoridor { Board::Board(int row_num, int col_num) : row_num_(), col_num_(), sides_(), pawn_sides_(), walls_(), occ_nodes_(), pawn_nodes_(), bg_() { set_size(row_num, col_num); sides_.push_back(std::pair<int, int>(0, 0)); sides_.push_back(std::pair<int, int>(2, 0)); sides_.push_back(std::pair<int, int>(1, 0)); sides_.push_back(std::pair<int, int>(3, 0)); } Board::~Board() { } void Board::set_size(int row_num, int col_num) { if (row_num <= 0) { throw Exception("illegal row number: " + boost::lexical_cast<std::string>(row_num)); } if (col_num <= 0) { throw Exception("illegal column number: " + boost::lexical_cast<std::string>(col_num)); } if (row_num % 2 == 0) { throw Exception("row number must be odd: " + boost::lexical_cast<std::string>(row_num)); } if (col_num % 2 == 0) { throw Exception("column number must be odd: " + boost::lexical_cast<std::string>(col_num)); } row_num_ = row_num; col_num_ = col_num; bg_.set_size(row_num_, col_num_); } int Board::next_side() const { for (auto &side : sides_) { if (side.second == 0) { side.second = 1; return side.first; } } return -1; } int Board::add_pawn(std::shared_ptr<Pawn> pawn) { pawn_sides_[pawn] = next_side(); int n; switch (pawn_sides_[pawn]) { case 0: n = col_num_ / 2; break; case 1: n = (row_num_ / 2) * col_num_; break; case 2: n = (row_num_ - 1) * col_num_ + col_num_ / 2; break; case 3: n = (row_num_ / 2) * col_num_ + col_num_ - 1; break; default: throw Exception("invalid pawn side: " + boost::lexical_cast<std::string>(pawn_sides_[pawn])); } occ_nodes_[n] = pawn; pawn_nodes_[pawn] = n; bg_.block_neighbours(n); return 0; } bool Board::is_occupied(int node) const { return occ_nodes_.find(node) != occ_nodes_.end(); } pos_t Board::pawn_pos(std::shared_ptr<Pawn> pawn) const { int node = pawn_nodes_.at(pawn); pos_t pos; pos.row = row(node); pos.col = col(node); return pos; } bool Board::is_at_opposite_side(std::shared_ptr<Pawn> pawn) const { int n = pawn_nodes_.at(pawn); switch (pawn_sides_.at(pawn)) { case 0: return row(n) == row_num_ - 1; case 1: return col(n) == col_num_ - 1; case 2: return row(n) == 0; case 3: return col(n) == 0; default: throw Exception("invalid board side: " + boost::lexical_cast<std::string>(pawn_sides_.at(pawn))); } } int Board::make_walking_move(std::shared_ptr<Pawn> pawn, int goal_node) { int cur_node = pawn_nodes_[pawn]; if (!is_possible_move(cur_node, goal_node)) { return -1; } // update pawn's position occ_nodes_.erase(pawn_nodes_[pawn]); bg_.unblock_neighbours(pawn_nodes_[pawn]); pawn_nodes_[pawn] = goal_node; occ_nodes_[goal_node] = pawn; bg_.block_neighbours(goal_node); return 0; } int Board::add_wall(const Wall &wall) { std::vector<std::pair<int, int>> edges; if (try_add_wall(wall, &edges) < 0) { return -1; } walls_[wall.orientation()][wall.line()].insert(std::map<int, Wall>::value_type(wall.start_pos(), Wall(wall))); for (auto edge : edges) { bg_.remove_edges(edge.first, edge.second); } return 0; } int Board::try_add_wall(const Wall &wall, std::vector<std::pair<int, int>> *edges) { int line_lim = (wall.orientation() ? col_num() : row_num()) - 1; int start_pos_lim = (wall.orientation() ? row_num() : col_num()) - 1; if ((wall.line() >= line_lim) || (wall.end_pos() > start_pos_lim)) { return -1; } if (wall_intersects(wall)) { return -1; } bg_.reset_filters(); int node1; int node2; int node_tmp; if (wall.orientation() == 0) { for (int i = 0; i < wall.cnt(); ++i) { node1 = wall.line() * col_num_ + wall.start_pos() + i; node2 = (wall.line() + 1) * col_num_ + wall.start_pos() + i; bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = (wall.line() + 2) * col_num_ + wall.start_pos() + i; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = (wall.line() - 1) * col_num_ + wall.start_pos() + i; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = (wall.line() + 1) * col_num_ + wall.start_pos() + j; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = wall.line() * col_num_ + wall.start_pos() + j; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } else { for (int i = 0; i < wall.cnt(); ++i) { node1 = (wall.start_pos() + i) * row_num_ + wall.line(); node2 = (wall.start_pos() + i) * row_num_ + wall.line() + 1; bg_.filter_edges(node1, node2); edges->push_back(std::make_pair(node1, node2)); node_tmp = (wall.start_pos() + i) * row_num_ + wall.line() + 2; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = (wall.start_pos() + i) * row_num_ + wall.line() - 1; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } for (int j = i - 1; j <= i + 1; j += 2) { node_tmp = (wall.start_pos() + j) * row_num_ + wall.line() + 1; if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node1, node_tmp); edges->push_back(std::make_pair(node1, node_tmp)); } node_tmp = (wall.start_pos() + j) * row_num_ + wall.line(); if ((node_tmp >= 0) && (node_tmp < row_num_ * col_num_)) { bg_.filter_edges(node_tmp, node2); edges->push_back(std::make_pair(node_tmp, node2)); } } } } bool path_blocked = false; for (auto pawn_node : pawn_nodes_) { std::vector<int> nodes; int side = (pawn_sides_[pawn_node.first] + 2) % 4; path_blocked = true; side_nodes(side, &nodes); for (auto node : nodes) { if (bg_.is_path_exists(pawn_node.second, node)) { path_blocked = false; break; } } // wall blocks all pathes to the opposite side for one of pawns if (path_blocked) { break; } } if (path_blocked) { return -1; } return 0; } void Board::pawn_final_nodes(std::shared_ptr<Pawn> pawn, std::vector<int> *nodes) const { int side = (pawn_sides_.at(pawn) + 2) % 4; side_nodes(side, nodes); } bool Board::get_path(std::shared_ptr<Pawn> pawn, int end_node, std::list<int> *nodes) const { return bg_.find_path(pawn_nodes_.at(pawn), end_node, nodes); } bool Board::is_win(std::shared_ptr<Pawn> pawn) const { return is_at_opposite_side(pawn); } bool Board::is_possible_move(int cur_node, int goal_node) const { return bg_.is_adjacent(cur_node, goal_node); } bool Board::wall_intersects(const Wall &wall) const { // check intersections if (walls_.count(1 - wall.orientation()) > 0) { for (int i = 0; i < wall.cnt() - 1; ++i) { // there are walls on the intersected line if (walls_.at(1 - wall.orientation()).count(wall.start_pos()) != 0) { auto line_walls = walls_.at(1 - wall.orientation()).at(wall.start_pos() + i); auto it = line_walls.upper_bound(wall.line()); // all walls on the line are settled before new wall if (it == line_walls.end()) { auto rit = line_walls.rbegin(); if (rit->second.end_pos() >= wall.line()) { return true; } } else if (it != line_walls.begin()) { --it; if (it->second.end_pos() >= wall.line()) { return true; } } } } } // check overlaps if (walls_.count(wall.orientation()) > 0) { if (walls_.at(wall.orientation()).count(wall.line()) != 0) { auto line_walls = walls_.at(wall.orientation()).at(wall.line()); auto it = line_walls.upper_bound(wall.start_pos()); // all walls on the line are settled before new wall if (it == line_walls.end()) { auto rit = line_walls.rbegin(); if (rit->second.end_pos() >= wall.start_pos()) { return true; } } else { // check if new wall overlaps over next wall on the line if (wall.end_pos() >= it->second.start_pos()) { return true; } if (it != line_walls.begin()) { --it; if (it->second.end_pos() >= wall.start_pos()) { return true; } } } } } return false; } void Board::side_nodes(int side, std::vector<int> *nodes) const { switch (side) { case 0: for (int i = 0; i < col_num_; ++i) { nodes->push_back(i); } break; case 1: for (int i = 0; i < row_num_; ++i) { nodes->push_back(i * col_num_); } break; case 2: for (int i = 0; i < col_num_; ++i) { nodes->push_back((row_num_ - 1 ) * col_num_ + i); } break; case 3: for (int i = 0; i < row_num_; ++i) { nodes->push_back(i * col_num_ + col_num_ - 1); } break; default: break; } } } /* namespace Quoridor */ <|endoftext|>
<commit_before>#include "box2d.hpp" #include <exception> #include <iostream> #include <stdexcept> Box2D::Box2D(Box2D && obj) { swap(obj); } Box2D & Box2D::operator = (Box2D const & obj) { if (this == &obj) return *this; Box2D tmp(obj); swap(tmp); return *this; } Box2D & Box2D::operator = (Box2D && obj) { swap(obj); return *this; } bool Box2D::operator == (Box2D const & obj) const { return m_boxMin == obj.m_boxMin && m_boxMax == obj.m_boxMax; } void Box2D::swap(Box2D & obj) { std::swap(m_boxMin, obj.m_boxMin); std::swap(m_boxMax, obj.m_boxMax); } bool Box2D::checkInside(const Box2D & box, const Point2D & point) { return ((point.x() >= box.m_boxMin.x() && point.x() <= box.m_boxMax.x() && point.y() >= box.m_boxMin.y() && point.y() <= box.m_boxMax.y()) || (point.x() >= box.m_boxMax.x() && point.x() <= box.m_boxMin.x() && point.y() >= box.m_boxMax.y() && point.y() <= box.m_boxMin.y()) ); } bool Box2D::checkBoxes(const Box2D & box1, const Box2D & box2) { // If two boxes are not intersected with each other // then return false. return not ( box1.boxMax().x() <= box2.boxMin().x() || box2.boxMax().x() <= box1.boxMin().x() || box1.boxMin().y() >= box2.boxMax().y() || box2.boxMin().y() >= box1.boxMax().y() ); } Box2D Box2D::createBox(const Point2D & minPoint, const Point2D & maxPoint) { if(minPoint.x()>=maxPoint.x() || minPoint.y()>=maxPoint.y()) throw std::invalid_argument("You must create correct box"); return Box2D(minPoint,maxPoint); } <commit_msg>edit checkInside<commit_after>#include "box2d.hpp" #include <exception> #include <iostream> #include <stdexcept> Box2D::Box2D(Box2D && obj) { swap(obj); } Box2D & Box2D::operator = (Box2D const & obj) { if (this == &obj) return *this; Box2D tmp(obj); swap(tmp); return *this; } Box2D & Box2D::operator = (Box2D && obj) { swap(obj); return *this; } bool Box2D::operator == (Box2D const & obj) const { return m_boxMin == obj.m_boxMin && m_boxMax == obj.m_boxMax; } void Box2D::swap(Box2D & obj) { std::swap(m_boxMin, obj.m_boxMin); std::swap(m_boxMax, obj.m_boxMax); } bool Box2D::checkInside(const Box2D & box, const Point2D & point) { return not (point.x() < box.boxMin().x() || point.x() > box.boxMax().x() || point.y() < box.boxMin().y() || point.y() > box.boxMax().y()); } bool Box2D::checkBoxes(const Box2D & box1, const Box2D & box2) { // If two boxes are not intersected with each other // then return false. return not ( box1.boxMax().x() <= box2.boxMin().x() || box2.boxMax().x() <= box1.boxMin().x() || box1.boxMin().y() >= box2.boxMax().y() || box2.boxMin().y() >= box1.boxMax().y() ); } Box2D Box2D::createBox(const Point2D & minPoint, const Point2D & maxPoint) { if(minPoint.x()>=maxPoint.x() || minPoint.y()>=maxPoint.y()) throw std::invalid_argument("You must create correct box"); return Box2D(minPoint,maxPoint); } <|endoftext|>
<commit_before>#include <stdlib.h> #include <arpa/inet.h> #include <arpa/nameser.h> #include <resolv.h> #include <ares.h> #include <iostream> #include <memory> #include "cache.h" #include "skull_protos.h" using namespace skull::service::dns; #define MAX_DNS_REPLY_ADDRS 100 #define MAX_RECORD_EXPIRED_TIME 2 // unit: second // ====================== Internal Functions =================================== class UpdateJobdata { private: std::string domain_; adns::Cache::QType qtype; adns::Cache::DnsRecords records_; public: UpdateJobdata(const std::string& domain, adns::Cache::QType qtype) { this->domain_ = domain; this->qtype = qtype; this->records_.start_ = time(NULL); } void append(const adns::Cache::RDnsRecord& record) { this->records_.records_.push_back(record); } const std::string& domain() const { return this->domain_; } adns::Cache::QType queryType() const { return this->qtype; } adns::Cache::DnsRecords& records() { return this->records_; } const adns::Cache::DnsRecords& records() const { return this->records_; } }; static void _dnsrecord_updating(skullcpp::Service& service, const std::shared_ptr<UpdateJobdata>& jobData) { auto dnsCache = (adns::Cache*)service.get(); if (!jobData.get()) return; if (jobData->domain().empty()) return; if (jobData->records().records_.empty()) return; const std::string& domain = jobData->domain(); adns::Cache::QType qtype = jobData->queryType(); adns::Cache::DnsRecords& records = jobData->records(); dnsCache->updateCache(service, domain, qtype, records); SKULLCPP_LOG_INFO("RecordUpdating", "dnsrecord_updating done, domain: " << domain); } // dns callback functions static ssize_t _dns_reply_unpack(const void* data, size_t len) { SKULLCPP_LOG_DEBUG("EPClient dns _unpack len: " << len); return (ssize_t)len; } static void _dns_resp_cb(const skullcpp::Service& service, skullcpp::EPClientRet& ret, std::shared_ptr<std::string>& domain, adns::Cache::QType qtype) { // 1. Prepare and validate ep status SKULLCPP_LOG_DEBUG("dns_resp_cb: response len: " << ret.responseSize() << ", status: " << ret.status() << ", latency: " << ret.latency()); auto& apiData = ret.apiData(); auto& queryReq = (const query_req&)apiData.request(); auto& queryResp = (query_resp&)apiData.response(); if (ret.status() != skullcpp::EPClient::Status::OK) { SKULLCPP_LOG_ERROR("svc.dns.query-3", "Dns query failed due to network issue: " << domain, "Check network or dns server status"); queryResp.set_code(1); queryResp.set_error("Dns query failed"); return; } // 2. Parse dns answers int naddrs = MAX_DNS_REPLY_ADDRS; struct ares_addrttl addrs[MAX_DNS_REPLY_ADDRS]; memset(addrs, 0, sizeof(struct ares_addrttl) * MAX_DNS_REPLY_ADDRS); const auto* response = (const unsigned char *)ret.response(); int r = ares_parse_a_reply(response, (int)ret.responseSize(), NULL, addrs, &naddrs); if (r != ARES_SUCCESS) { SKULLCPP_LOG_ERROR("svc.dns.query-4", "dns parse reply failed: " << ares_strerror(r) << " domain: " << queryReq.question(), "Check whether queried domain is correct"); queryResp.set_code(1); queryResp.set_error("Dns query failed, check whether domain is correct"); return; } SKULLCPP_LOG_DEBUG("Got " << naddrs << " dns records"); if (!naddrs) { queryResp.set_code(1); queryResp.set_error("Dns query failed, no ip returned"); return; } // 3. Fill the api response queryResp.set_code(0); auto jobData = std::make_shared<UpdateJobdata>(queryReq.question(), qtype); for (int i = 0; i < naddrs; i++) { // 1. Fill jobData for updating the cache char ip [INET_ADDRSTRLEN]; inet_ntop(AF_INET, &addrs[i].ipaddr, ip, INET_ADDRSTRLEN); adns::Cache::RDnsRecord rRecord; rRecord.ip = ip; rRecord.ttl = addrs[i].ttl; jobData->append(rRecord); SKULLCPP_LOG_DEBUG(" - ip: " << ip << "; ttl: " << addrs[i].ttl); // 2. Fill the service response auto* record = queryResp.add_record(); record->set_ip(ip); record->set_ttl(addrs[i].ttl); } // 4. Update it via a service job service.createJob(0, 0, skull_BindSvcJobNPW(_dnsrecord_updating, jobData), NULL); } static void _dns6_resp_cb(const skullcpp::Service& service, skullcpp::EPClientRet& ret, std::shared_ptr<std::string>& domain, adns::Cache::QType qtype) { // 1. Prepare and validate ep status SKULLCPP_LOG_DEBUG("dns6_resp_cb: response len: " << ret.responseSize() << ", status: " << ret.status() << ", latency: " << ret.latency()); auto& apiData = ret.apiData(); auto& queryReq = (const query_req&)apiData.request(); auto& queryResp = (query_resp&)apiData.response(); if (ret.status() != skullcpp::EPClient::Status::OK) { SKULLCPP_LOG_ERROR("svc.dns6.query-3", "Dns query failed due to network issue: " << domain, "Check network or dns server status"); queryResp.set_code(1); queryResp.set_error("Dns query failed"); return; } // 2. Parse dns answers int naddrs = MAX_DNS_REPLY_ADDRS; struct ares_addr6ttl addrs[MAX_DNS_REPLY_ADDRS]; memset(addrs, 0, sizeof(struct ares_addr6ttl) * MAX_DNS_REPLY_ADDRS); const auto* response = (const unsigned char *)ret.response(); int r = ares_parse_aaaa_reply(response, (int)ret.responseSize(), NULL, addrs, &naddrs); if (r != ARES_SUCCESS) { SKULLCPP_LOG_ERROR("svc.dns6.query-4", "dns parse reply failed: " << ares_strerror(r) << " domain: " << queryReq.question(), "Check whether queried domain is correct"); queryResp.set_code(1); queryResp.set_error("Dns6 query failed, check whether domain is correct"); return; } SKULLCPP_LOG_DEBUG("Got " << naddrs << " dns AAAA records"); if (!naddrs) { queryResp.set_code(1); queryResp.set_error("Dns query failed, no ip returned"); return; } // 3. Fill the api response queryResp.set_code(0); auto jobData = std::make_shared<UpdateJobdata>(queryReq.question(), qtype); for (int i = 0; i < naddrs; i++) { // 1. Fill jobData for updating the cache char ip [INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &addrs[i].ip6addr, ip, INET6_ADDRSTRLEN); adns::Cache::RDnsRecord rRecord; rRecord.ip = ip; rRecord.ttl = addrs[i].ttl; jobData->append(rRecord); SKULLCPP_LOG_DEBUG(" - ip: " << ip << "; ttl: " << addrs[i].ttl); // 2. Fill the service response auto* record = queryResp.add_record(); record->set_ip(ip); record->set_ttl(addrs[i].ttl); } // 4. Update it via a service job service.createJob(0, 0, skull_BindSvcJobNPW(_dnsrecord_updating, jobData), NULL); } namespace adns { Cache::Cache() { // 1. Init ares library int ret = ares_library_init(ARES_LIB_INIT_ALL); if (ret) { SKULLCPP_LOG_FATAL("Init", "Init ares library failed: " << ares_strerror(ret), ""); exit(1); } // 2. Init Resolver res_init(); // 3. Init name servers initNameServers(); } Cache::~Cache() { ares_library_cleanup(); } void Cache::queryFromCache(const skullcpp::Service& service, const std::string& domain, QType qtype, RDnsRecordVec& rRecords) const { auto* cache = &this->recordsA_; if (qtype == QType::AAAA) { cache = &this->records4A_; } auto it = cache->find(domain); if (it == cache->end()) { return; } // Reture the 1st unexpired record const DnsRecords& records = it->second; size_t nrec = records.records_.size(); if (!nrec) { return; } time_t now = time(NULL); for (const auto& record : records.records_) { const auto& ip = record.ip; int ttl = record.ttl; if (now - records.start_ >= ttl) { continue; } int newTTL = ttl - (int)(now - records.start_); RDnsRecord rRecord; rRecord.ip = ip; rRecord.ttl = newTTL; rRecords.push_back(rRecord); } } bool Cache::queryFromDNS(const skullcpp::Service& service, const std::string& question, QType qtype) const { // Create a simple internet query for ipv4 address and recursion is desired unsigned char* query = NULL; int query_len = 0; __ns_type type = qtype == QType::A ? ns_t_a : ns_t_aaaa; SKULLCPP_LOG_DEBUG("Got question: " << question << ", " << "qtype: " << qtype); // To backward compatible, here we use `ares_mkquery`, if your // platform support higher version of ares, then recommend to use // `ares_create_query` int ret = ares_mkquery(question.c_str(), ns_c_in, // Internet class type, // A or AAAA 0, // identifier 1, // recursion is desired &query, &query_len); if (ret != ARES_SUCCESS) { SKULLCPP_LOG_ERROR("svc.dns.query-2", "create dns query failed: " << ares_strerror(ret), "Check whether queried domain is correct"); ares_free_string(query); return false; } // Create EPClient to send the query string to DNS server skullcpp::EPClient epClient; epClient.setType(skullcpp::EPClient::UDP); epClient.setIP(getNameServerIP()); epClient.setPort(53); epClient.setTimeout(1000); epClient.setUnpack(_dns_reply_unpack); auto queryDomain = std::make_shared<std::string>(question); auto epCb = qtype == QType::A ? skull_BindEpCb(_dns_resp_cb, queryDomain, qtype) : skull_BindEpCb(_dns6_resp_cb, queryDomain, qtype); skullcpp::EPClient::Status st = epClient.send(service, query, (size_t)query_len, epCb); ares_free_string(query); if (st != skullcpp::EPClient::Status::OK) { return false; } else { return true; } } void Cache::updateCache(skullcpp::Service& service, const std::string& domain, QType qtype, DnsRecords& newRecords) { auto* cache = &this->recordsA_; if (qtype == QType::AAAA) { cache = &this->records4A_; } auto it = cache->find(domain); if (it == cache->end()) { cache->insert(std::make_pair(domain, newRecords)); return; } DnsRecords& oldRecords = it->second; if (newRecords.start_ > oldRecords.start_) { cache->erase(it); cache->insert(std::make_pair(domain, newRecords)); } } void Cache::initNameServers() { if (_res.nscount == 0) { SKULLCPP_LOG_FATAL("Init", "Not found any name server, exit", ""); exit(1); } for (int i = 0; i < _res.nscount; i++) { char ip [INET_ADDRSTRLEN]; inet_ntop(AF_INET, &_res.nsaddr_list[i].sin_addr, ip, INET_ADDRSTRLEN); SKULLCPP_LOG_INFO("Init", "init name server: " << ip << std::endl) this->nservers_.push_back(ip); } } const std::string& Cache::getNameServerIP() const { return this->nservers_[0]; } } // End of namespace <commit_msg>Fix incorrect question in error log issue<commit_after>#include <stdlib.h> #include <arpa/inet.h> #include <arpa/nameser.h> #include <resolv.h> #include <ares.h> #include <iostream> #include <memory> #include "cache.h" #include "skull_protos.h" using namespace skull::service::dns; #define MAX_DNS_REPLY_ADDRS 100 #define MAX_RECORD_EXPIRED_TIME 2 // unit: second // ====================== Internal Functions =================================== class UpdateJobdata { private: std::string domain_; adns::Cache::QType qtype; adns::Cache::DnsRecords records_; public: UpdateJobdata(const std::string& domain, adns::Cache::QType qtype) { this->domain_ = domain; this->qtype = qtype; this->records_.start_ = time(NULL); } void append(const adns::Cache::RDnsRecord& record) { this->records_.records_.push_back(record); } const std::string& domain() const { return this->domain_; } adns::Cache::QType queryType() const { return this->qtype; } adns::Cache::DnsRecords& records() { return this->records_; } const adns::Cache::DnsRecords& records() const { return this->records_; } }; static void _dnsrecord_updating(skullcpp::Service& service, const std::shared_ptr<UpdateJobdata>& jobData) { auto dnsCache = (adns::Cache*)service.get(); if (!jobData.get()) return; if (jobData->domain().empty()) return; if (jobData->records().records_.empty()) return; const std::string& domain = jobData->domain(); adns::Cache::QType qtype = jobData->queryType(); adns::Cache::DnsRecords& records = jobData->records(); dnsCache->updateCache(service, domain, qtype, records); SKULLCPP_LOG_INFO("RecordUpdating", "dnsrecord_updating done, domain: " << domain); } // dns callback functions static ssize_t _dns_reply_unpack(const void* data, size_t len) { SKULLCPP_LOG_DEBUG("EPClient dns _unpack len: " << len); return (ssize_t)len; } static void _dns_resp_cb(const skullcpp::Service& service, skullcpp::EPClientRet& ret, std::shared_ptr<std::string>& domain, adns::Cache::QType qtype) { // 1. Prepare and validate ep status SKULLCPP_LOG_DEBUG("dns_resp_cb: response len: " << ret.responseSize() << ", status: " << ret.status() << ", latency: " << ret.latency()); auto& apiData = ret.apiData(); auto& queryReq = (const query_req&)apiData.request(); auto& queryResp = (query_resp&)apiData.response(); if (ret.status() != skullcpp::EPClient::Status::OK) { SKULLCPP_LOG_ERROR("svc.dns.query-3", "Dns query failed due to network issue: " << *domain, "Check network or dns server status"); queryResp.set_code(1); queryResp.set_error("Dns query failed"); return; } // 2. Parse dns answers int naddrs = MAX_DNS_REPLY_ADDRS; struct ares_addrttl addrs[MAX_DNS_REPLY_ADDRS]; memset(addrs, 0, sizeof(struct ares_addrttl) * MAX_DNS_REPLY_ADDRS); const auto* response = (const unsigned char *)ret.response(); int r = ares_parse_a_reply(response, (int)ret.responseSize(), NULL, addrs, &naddrs); if (r != ARES_SUCCESS) { SKULLCPP_LOG_ERROR("svc.dns.query-4", "dns parse reply failed: " << ares_strerror(r) << " domain: " << queryReq.question(), "Check whether queried domain is correct"); queryResp.set_code(1); queryResp.set_error("Dns query failed, check whether domain is correct"); return; } SKULLCPP_LOG_DEBUG("Got " << naddrs << " dns records"); if (!naddrs) { queryResp.set_code(1); queryResp.set_error("Dns query failed, no ip returned"); return; } // 3. Fill the api response queryResp.set_code(0); auto jobData = std::make_shared<UpdateJobdata>(queryReq.question(), qtype); for (int i = 0; i < naddrs; i++) { // 1. Fill jobData for updating the cache char ip [INET_ADDRSTRLEN]; inet_ntop(AF_INET, &addrs[i].ipaddr, ip, INET_ADDRSTRLEN); adns::Cache::RDnsRecord rRecord; rRecord.ip = ip; rRecord.ttl = addrs[i].ttl; jobData->append(rRecord); SKULLCPP_LOG_DEBUG(" - ip: " << ip << "; ttl: " << addrs[i].ttl); // 2. Fill the service response auto* record = queryResp.add_record(); record->set_ip(ip); record->set_ttl(addrs[i].ttl); } // 4. Update it via a service job service.createJob(0, 0, skull_BindSvcJobNPW(_dnsrecord_updating, jobData), NULL); } static void _dns6_resp_cb(const skullcpp::Service& service, skullcpp::EPClientRet& ret, std::shared_ptr<std::string>& domain, adns::Cache::QType qtype) { // 1. Prepare and validate ep status SKULLCPP_LOG_DEBUG("dns6_resp_cb: response len: " << ret.responseSize() << ", status: " << ret.status() << ", latency: " << ret.latency()); auto& apiData = ret.apiData(); auto& queryReq = (const query_req&)apiData.request(); auto& queryResp = (query_resp&)apiData.response(); if (ret.status() != skullcpp::EPClient::Status::OK) { SKULLCPP_LOG_ERROR("svc.dns6.query-3", "Dns query failed due to network issue: " << *domain, "Check network or dns server status"); queryResp.set_code(1); queryResp.set_error("Dns query failed"); return; } // 2. Parse dns answers int naddrs = MAX_DNS_REPLY_ADDRS; struct ares_addr6ttl addrs[MAX_DNS_REPLY_ADDRS]; memset(addrs, 0, sizeof(struct ares_addr6ttl) * MAX_DNS_REPLY_ADDRS); const auto* response = (const unsigned char *)ret.response(); int r = ares_parse_aaaa_reply(response, (int)ret.responseSize(), NULL, addrs, &naddrs); if (r != ARES_SUCCESS) { SKULLCPP_LOG_ERROR("svc.dns6.query-4", "dns parse reply failed: " << ares_strerror(r) << " domain: " << queryReq.question(), "Check whether queried domain is correct"); queryResp.set_code(1); queryResp.set_error("Dns6 query failed, check whether domain is correct"); return; } SKULLCPP_LOG_DEBUG("Got " << naddrs << " dns AAAA records"); if (!naddrs) { queryResp.set_code(1); queryResp.set_error("Dns query failed, no ip returned"); return; } // 3. Fill the api response queryResp.set_code(0); auto jobData = std::make_shared<UpdateJobdata>(queryReq.question(), qtype); for (int i = 0; i < naddrs; i++) { // 1. Fill jobData for updating the cache char ip [INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &addrs[i].ip6addr, ip, INET6_ADDRSTRLEN); adns::Cache::RDnsRecord rRecord; rRecord.ip = ip; rRecord.ttl = addrs[i].ttl; jobData->append(rRecord); SKULLCPP_LOG_DEBUG(" - ip: " << ip << "; ttl: " << addrs[i].ttl); // 2. Fill the service response auto* record = queryResp.add_record(); record->set_ip(ip); record->set_ttl(addrs[i].ttl); } // 4. Update it via a service job service.createJob(0, 0, skull_BindSvcJobNPW(_dnsrecord_updating, jobData), NULL); } namespace adns { Cache::Cache() { // 1. Init ares library int ret = ares_library_init(ARES_LIB_INIT_ALL); if (ret) { SKULLCPP_LOG_FATAL("Init", "Init ares library failed: " << ares_strerror(ret), ""); exit(1); } // 2. Init Resolver res_init(); // 3. Init name servers initNameServers(); } Cache::~Cache() { ares_library_cleanup(); } void Cache::queryFromCache(const skullcpp::Service& service, const std::string& domain, QType qtype, RDnsRecordVec& rRecords) const { auto* cache = &this->recordsA_; if (qtype == QType::AAAA) { cache = &this->records4A_; } auto it = cache->find(domain); if (it == cache->end()) { return; } // Reture the 1st unexpired record const DnsRecords& records = it->second; size_t nrec = records.records_.size(); if (!nrec) { return; } time_t now = time(NULL); for (const auto& record : records.records_) { const auto& ip = record.ip; int ttl = record.ttl; if (now - records.start_ >= ttl) { continue; } int newTTL = ttl - (int)(now - records.start_); RDnsRecord rRecord; rRecord.ip = ip; rRecord.ttl = newTTL; rRecords.push_back(rRecord); } } bool Cache::queryFromDNS(const skullcpp::Service& service, const std::string& question, QType qtype) const { // Create a simple internet query for ipv4 address and recursion is desired unsigned char* query = NULL; int query_len = 0; __ns_type type = qtype == QType::A ? ns_t_a : ns_t_aaaa; SKULLCPP_LOG_DEBUG("Got question: " << question << ", " << "qtype: " << qtype); // To backward compatible, here we use `ares_mkquery`, if your // platform support higher version of ares, then recommend to use // `ares_create_query` int ret = ares_mkquery(question.c_str(), ns_c_in, // Internet class type, // A or AAAA 0, // identifier 1, // recursion is desired &query, &query_len); if (ret != ARES_SUCCESS) { SKULLCPP_LOG_ERROR("svc.dns.query-2", "create dns query failed: " << ares_strerror(ret), "Check whether queried domain is correct"); ares_free_string(query); return false; } // Create EPClient to send the query string to DNS server skullcpp::EPClient epClient; epClient.setType(skullcpp::EPClient::UDP); epClient.setIP(getNameServerIP()); epClient.setPort(53); epClient.setTimeout(1000); epClient.setUnpack(_dns_reply_unpack); auto queryDomain = std::make_shared<std::string>(question); auto epCb = qtype == QType::A ? skull_BindEpCb(_dns_resp_cb, queryDomain, qtype) : skull_BindEpCb(_dns6_resp_cb, queryDomain, qtype); skullcpp::EPClient::Status st = epClient.send(service, query, (size_t)query_len, epCb); ares_free_string(query); if (st != skullcpp::EPClient::Status::OK) { return false; } else { return true; } } void Cache::updateCache(skullcpp::Service& service, const std::string& domain, QType qtype, DnsRecords& newRecords) { auto* cache = &this->recordsA_; if (qtype == QType::AAAA) { cache = &this->records4A_; } auto it = cache->find(domain); if (it == cache->end()) { cache->insert(std::make_pair(domain, newRecords)); return; } DnsRecords& oldRecords = it->second; if (newRecords.start_ > oldRecords.start_) { cache->erase(it); cache->insert(std::make_pair(domain, newRecords)); } } void Cache::initNameServers() { if (_res.nscount == 0) { SKULLCPP_LOG_FATAL("Init", "Not found any name server, exit", ""); exit(1); } for (int i = 0; i < _res.nscount; i++) { char ip [INET_ADDRSTRLEN]; inet_ntop(AF_INET, &_res.nsaddr_list[i].sin_addr, ip, INET_ADDRSTRLEN); SKULLCPP_LOG_INFO("Init", "init name server: " << ip << std::endl) this->nservers_.push_back(ip); } } const std::string& Cache::getNameServerIP() const { return this->nservers_[0]; } } // End of namespace <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chain.h" using namespace std; /** * CChain implementation */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == NULL) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } <commit_msg>Update chain.cpp<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chain.h" using namespace std; /** * CChain implementation */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == NULL) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } <|endoftext|>
<commit_before>// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coins.h" #include "consensus/consensus.h" #include "memusage.h" #include "random.h" #include <assert.h> // Gulden specific includes #include "Gulden/util.h" bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; } bool CCoinsView::HaveCoin(const COutPoint &outpoint) const { return false; } uint256 CCoinsView::GetBestBlock() const { return uint256(); } bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; } CCoinsViewCursor *CCoinsView::Cursor() const { return 0; } CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { } bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); } bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); } uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); } void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; } bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); } CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); } size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); } SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {} CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0), pChainedWitView(nullptr) {} CCoinsViewCache::CCoinsViewCache(CCoinsViewCache *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0), pChainedWitView(baseIn->pChainedWitView?std::shared_ptr<CCoinsViewCache>(new CCoinsViewCache(baseIn->pChainedWitView.get())):nullptr) {} size_t CCoinsViewCache::DynamicMemoryUsage() const { return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage; } CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const { CCoinsMap::iterator it = cacheCoins.find(outpoint); if (it != cacheCoins.end()) return it; Coin tmp; if (!base->GetCoin(outpoint, tmp)) return cacheCoins.end(); CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first; if (ret->second.coin.IsSpent()) { // The parent only has an empty entry for this outpoint; we can consider our // version as fresh. ret->second.flags = CCoinsCacheEntry::FRESH; } cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage(); return ret; } bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it != cacheCoins.end()) { coin = it->second.coin; return true; } return false; } void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) { if (pChainedWitView) { if ( IsPow2WitnessOutput(coin.out) ) { //LogPrintf(">>>CCoinsViewCache: AddCoin %d %s %s\n", GetDepth(), outpoint.ToString(), coin.out.ToString()); pChainedWitView->AddCoin(outpoint, Coin(coin.out, coin.nHeight, coin.fCoinBase, coin.fSegSig), possible_overwrite); } } assert(!coin.IsSpent()); if (coin.out.IsUnspendable()) return; CTxOut out = coin.out; CCoinsMap::iterator it; bool inserted; std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>()); bool fresh = false; if (!inserted) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); } if (!possible_overwrite) { if (!it->second.coin.IsSpent()) { throw std::logic_error("Adding new coin that replaces non-pruned entry"); } fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY); } it->second.coin = std::move(coin); it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0); cachedCoinsUsage += it->second.coin.DynamicMemoryUsage(); } void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight) { bool fCoinbase = tx.IsCoinBase(); const uint256& txid = tx.GetHash(); for (size_t i = 0; i < tx.vout.size(); ++i) { // Pass fCoinbase as the possible_overwrite flag to AddCoin, in order to correctly // deal with the pre-BIP30 occurrences of duplicate coinbase transactions. cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase, (tx.nVersion >= CTransaction::SEGSIG_ACTIVATION_VERSION)), fCoinbase); } } void CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout, bool nodeletefresh) { if (pChainedWitView) { //LogPrintf(">>>CCoinsViewCache: SpendCoin %d %s\n", GetDepth(), outpoint.ToString()); // NB! The below is essential for the operation of GetWitness function, otherwise it returns unpredictable and incorrect results. // For chained view we force everything to 'dirty' because we need to know about fresh coins that have been removed and can't just erase them. pChainedWitView->SpendCoin(outpoint, NULL, true); } CCoinsMap::iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) return; cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); if (moveout) { *moveout = std::move(it->second.coin); } if (!nodeletefresh && it->second.flags & CCoinsCacheEntry::FRESH) { cacheCoins.erase(it); } else { it->second.flags |= CCoinsCacheEntry::DIRTY; it->second.coin.Clear(); } } static const Coin coinEmpty; const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) { return coinEmpty; } else { return it->second.coin; } } bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); return (it != cacheCoins.end() && !it->second.coin.IsSpent()); } bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = cacheCoins.find(outpoint); return it != cacheCoins.end(); } uint256 CCoinsViewCache::GetBestBlock() const { if (hashBlock.IsNull()) hashBlock = base->GetBestBlock(); return hashBlock; } void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) { hashBlock = hashBlockIn; } bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) { for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization). CCoinsMap::iterator itUs = cacheCoins.find(it->first); if (itUs == cacheCoins.end()) { // The parent cache does not have an entry, while the child does // We can ignore it if it's both FRESH and pruned in the child if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) { // Otherwise we will need to create it in the parent // and move the data up and mark it as dirty CCoinsCacheEntry& entry = cacheCoins[it->first]; entry.coin = std::move(it->second.coin); cachedCoinsUsage += entry.coin.DynamicMemoryUsage(); entry.flags = CCoinsCacheEntry::DIRTY; // We can mark it FRESH in the parent if it was FRESH in the child // Otherwise it might have just been flushed from the parent's cache // and already exist in the grandparent if (it->second.flags & CCoinsCacheEntry::FRESH) entry.flags |= CCoinsCacheEntry::FRESH; } } else { // Assert that the child cache entry was not marked FRESH if the // parent cache entry has unspent outputs. If this ever happens, // it means the FRESH flag was misapplied and there is a logic // error in the calling code. if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) throw std::logic_error("FRESH flag misapplied to cache entry for base transaction with spendable outputs"); // Found the entry in the parent cache if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) { // The grandparent does not have an entry, and the child is // modified and being pruned. This means we can just delete // it from the parent. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); cacheCoins.erase(itUs); } else { // A normal modification. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); itUs->second.coin = std::move(it->second.coin); cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage(); itUs->second.flags |= CCoinsCacheEntry::DIRTY; // NOTE: It is possible the child has a FRESH flag here in // the event the entry we found in the parent is pruned. But // we must not copy that FRESH flag to the parent as that // pruned state likely still needs to be communicated to the // grandparent. } } } CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } hashBlock = hashBlockIn; return true; } bool CCoinsViewCache::Flush() { if (pChainedWitView) pChainedWitView->Flush(); bool fOk = base->BatchWrite(cacheCoins, hashBlock); cacheCoins.clear(); cachedCoinsUsage = 0; return fOk; } void CCoinsViewCache::Uncache(const COutPoint& hash) { if (pChainedWitView) pChainedWitView->Uncache(hash); CCoinsMap::iterator it = cacheCoins.find(hash); if (it != cacheCoins.end() && it->second.flags == 0) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); cacheCoins.erase(it); } } unsigned int CCoinsViewCache::GetCacheSize() const { return cacheCoins.size(); } CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const { if (tx.IsCoinBase() && !tx.IsPoW2WitnessCoinBase()) return 0; CAmount nResult = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { CAmount coinAmount = AccessCoin(tx.vin[i].prevout).out.nValue; if (coinAmount != -1) { nResult += coinAmount; } } return nResult; } bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const { if (!tx.IsCoinBase()) { for (unsigned int i = 0; i < tx.vin.size(); i++) { if (!HaveCoin(tx.vin[i].prevout)) { return false; } } } return true; } //fixme: (GULDEN) (HIGH) static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_BASE_SIZE / 2;//::GetSerializeSize(CTxOut(), SER_NETWORK, PROTOCOL_VERSION); // TODO: merge with similar definition in undo.h. const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid) { COutPoint iter(txid, 0); while (iter.n < MAX_OUTPUTS_PER_BLOCK) { const Coin& alternate = view.AccessCoin(iter); if (!alternate.IsSpent()) return alternate; ++iter.n; } return coinEmpty; } <commit_msg>Fix CCoinsViewCache::HaveInputs to work correctly for witness coinbase inputs.<commit_after>// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coins.h" #include "consensus/consensus.h" #include "memusage.h" #include "random.h" #include <assert.h> // Gulden specific includes #include "Gulden/util.h" bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; } bool CCoinsView::HaveCoin(const COutPoint &outpoint) const { return false; } uint256 CCoinsView::GetBestBlock() const { return uint256(); } bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; } CCoinsViewCursor *CCoinsView::Cursor() const { return 0; } CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { } bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); } bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); } uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); } void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; } bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); } CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); } size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); } SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {} CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0), pChainedWitView(nullptr) {} CCoinsViewCache::CCoinsViewCache(CCoinsViewCache *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0), pChainedWitView(baseIn->pChainedWitView?std::shared_ptr<CCoinsViewCache>(new CCoinsViewCache(baseIn->pChainedWitView.get())):nullptr) {} size_t CCoinsViewCache::DynamicMemoryUsage() const { return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage; } CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const { CCoinsMap::iterator it = cacheCoins.find(outpoint); if (it != cacheCoins.end()) return it; Coin tmp; if (!base->GetCoin(outpoint, tmp)) return cacheCoins.end(); CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first; if (ret->second.coin.IsSpent()) { // The parent only has an empty entry for this outpoint; we can consider our // version as fresh. ret->second.flags = CCoinsCacheEntry::FRESH; } cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage(); return ret; } bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it != cacheCoins.end()) { coin = it->second.coin; return true; } return false; } void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) { if (pChainedWitView) { if ( IsPow2WitnessOutput(coin.out) ) { //LogPrintf(">>>CCoinsViewCache: AddCoin %d %s %s\n", GetDepth(), outpoint.ToString(), coin.out.ToString()); pChainedWitView->AddCoin(outpoint, Coin(coin.out, coin.nHeight, coin.fCoinBase, coin.fSegSig), possible_overwrite); } } assert(!coin.IsSpent()); if (coin.out.IsUnspendable()) return; CTxOut out = coin.out; CCoinsMap::iterator it; bool inserted; std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>()); bool fresh = false; if (!inserted) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); } if (!possible_overwrite) { if (!it->second.coin.IsSpent()) { throw std::logic_error("Adding new coin that replaces non-pruned entry"); } fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY); } it->second.coin = std::move(coin); it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0); cachedCoinsUsage += it->second.coin.DynamicMemoryUsage(); } void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight) { bool fCoinbase = tx.IsCoinBase(); const uint256& txid = tx.GetHash(); for (size_t i = 0; i < tx.vout.size(); ++i) { // Pass fCoinbase as the possible_overwrite flag to AddCoin, in order to correctly // deal with the pre-BIP30 occurrences of duplicate coinbase transactions. cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase, (tx.nVersion >= CTransaction::SEGSIG_ACTIVATION_VERSION)), fCoinbase); } } void CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout, bool nodeletefresh) { if (pChainedWitView) { //LogPrintf(">>>CCoinsViewCache: SpendCoin %d %s\n", GetDepth(), outpoint.ToString()); // NB! The below is essential for the operation of GetWitness function, otherwise it returns unpredictable and incorrect results. // For chained view we force everything to 'dirty' because we need to know about fresh coins that have been removed and can't just erase them. pChainedWitView->SpendCoin(outpoint, NULL, true); } CCoinsMap::iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) return; cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); if (moveout) { *moveout = std::move(it->second.coin); } if (!nodeletefresh && it->second.flags & CCoinsCacheEntry::FRESH) { cacheCoins.erase(it); } else { it->second.flags |= CCoinsCacheEntry::DIRTY; it->second.coin.Clear(); } } static const Coin coinEmpty; const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) { return coinEmpty; } else { return it->second.coin; } } bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); return (it != cacheCoins.end() && !it->second.coin.IsSpent()); } bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = cacheCoins.find(outpoint); return it != cacheCoins.end(); } uint256 CCoinsViewCache::GetBestBlock() const { if (hashBlock.IsNull()) hashBlock = base->GetBestBlock(); return hashBlock; } void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) { hashBlock = hashBlockIn; } bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) { for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization). CCoinsMap::iterator itUs = cacheCoins.find(it->first); if (itUs == cacheCoins.end()) { // The parent cache does not have an entry, while the child does // We can ignore it if it's both FRESH and pruned in the child if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) { // Otherwise we will need to create it in the parent // and move the data up and mark it as dirty CCoinsCacheEntry& entry = cacheCoins[it->first]; entry.coin = std::move(it->second.coin); cachedCoinsUsage += entry.coin.DynamicMemoryUsage(); entry.flags = CCoinsCacheEntry::DIRTY; // We can mark it FRESH in the parent if it was FRESH in the child // Otherwise it might have just been flushed from the parent's cache // and already exist in the grandparent if (it->second.flags & CCoinsCacheEntry::FRESH) entry.flags |= CCoinsCacheEntry::FRESH; } } else { // Assert that the child cache entry was not marked FRESH if the // parent cache entry has unspent outputs. If this ever happens, // it means the FRESH flag was misapplied and there is a logic // error in the calling code. if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) throw std::logic_error("FRESH flag misapplied to cache entry for base transaction with spendable outputs"); // Found the entry in the parent cache if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) { // The grandparent does not have an entry, and the child is // modified and being pruned. This means we can just delete // it from the parent. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); cacheCoins.erase(itUs); } else { // A normal modification. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); itUs->second.coin = std::move(it->second.coin); cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage(); itUs->second.flags |= CCoinsCacheEntry::DIRTY; // NOTE: It is possible the child has a FRESH flag here in // the event the entry we found in the parent is pruned. But // we must not copy that FRESH flag to the parent as that // pruned state likely still needs to be communicated to the // grandparent. } } } CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } hashBlock = hashBlockIn; return true; } bool CCoinsViewCache::Flush() { if (pChainedWitView) pChainedWitView->Flush(); bool fOk = base->BatchWrite(cacheCoins, hashBlock); cacheCoins.clear(); cachedCoinsUsage = 0; return fOk; } void CCoinsViewCache::Uncache(const COutPoint& hash) { if (pChainedWitView) pChainedWitView->Uncache(hash); CCoinsMap::iterator it = cacheCoins.find(hash); if (it != cacheCoins.end() && it->second.flags == 0) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); cacheCoins.erase(it); } } unsigned int CCoinsViewCache::GetCacheSize() const { return cacheCoins.size(); } CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const { if (tx.IsCoinBase() && !tx.IsPoW2WitnessCoinBase()) return 0; CAmount nResult = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { CAmount coinAmount = AccessCoin(tx.vin[i].prevout).out.nValue; if (coinAmount != -1) { nResult += coinAmount; } } return nResult; } bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const { if (!tx.IsCoinBase() || tx.IsPoW2WitnessCoinBase()) { for (unsigned int i = 0; i < tx.vin.size(); i++) { if (!HaveCoin(tx.vin[i].prevout)) { if (!tx.IsPoW2WitnessCoinBase() || !tx.vin[i].prevout.IsNull()) return false; } } } return true; } //fixme: (GULDEN) (HIGH) static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_BASE_SIZE / 2;//::GetSerializeSize(CTxOut(), SER_NETWORK, PROTOCOL_VERSION); // TODO: merge with similar definition in undo.h. const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid) { COutPoint iter(txid, 0); while (iter.n < MAX_OUTPUTS_PER_BLOCK) { const Coin& alternate = view.AccessCoin(iter); if (!alternate.IsSpent()) return alternate; ++iter.n; } return coinEmpty; } <|endoftext|>
<commit_before>#pragma once #include <QString> namespace chatterino { static const char *ANONYMOUS_USERNAME_LABEL = " - anonymous - "; namespace providers { namespace twitch { static const char *ANONYMOUS_USERNAME = "justinfan64537"; } // namespace twitch } // namespace providers } // namespace chatterino <commit_msg>Specify that the variables in const.hpp are allowed to be unused<commit_after>#pragma once #include <QString> namespace chatterino { static const char *ANONYMOUS_USERNAME_LABEL __attribute__((unused)) = " - anonymous - "; namespace providers { namespace twitch { static const char *ANONYMOUS_USERNAME __attribute__((unused)) = "justinfan64537"; } // namespace twitch } // namespace providers } // namespace chatterino <|endoftext|>
<commit_before>#include "dDNNF.h" #include <unordered_map> double dDNNF::dDNNFEvaluation(gate_t g) const { static std::unordered_map<gate_t, double> cache; auto it = cache.find(g); if(it!=cache.end()) return it->second; double result; if(getGateType(g)==BooleanGate::IN) result = getProb(g); else if(getGateType(g)==BooleanGate::NOT) result = 1-getProb(*getWires(g).begin()); else { result=(getGateType(g)==BooleanGate::AND?1:0); for(auto s: getWires(g)) { double d = dDNNFEvaluation(s); if(getGateType(g)==BooleanGate::AND) result*=d; else result+=d; } } cache[g]=result; return result; } <commit_msg>Turn dDNNFEvaluation into an iterative algorithm to avoid stack overflow<commit_after>#include "dDNNF.h" #include <unordered_map> #include <stack> #include <variant> #include <cassert> double dDNNF::dDNNFEvaluation(gate_t root) const { // We memoize results static std::unordered_map<gate_t, double> cache; // Unfortunately, dDNNFs can be quite deep so we need to simulate // recursion with a heap-based stack, to avoid exhausting the actual // memory stack using RecursionParams = struct { gate_t g; size_t children_processed; double partial_value; }; using RecursionResult = double; std::stack<std::variant<RecursionParams,RecursionResult>> stack; stack.emplace(RecursionParams{root,0,0.}); while(1) { double child_value{0.}; if(stack.top().index()==1) { // RecursionResult child_value=std::get<1>(stack.top()); stack.pop(); } auto [g, children_processed, partial_value]=std::get<0>(stack.top()); stack.pop(); auto it = cache.find(g); double result; if(it!=cache.end()) { if(stack.empty()) return it->second; else stack.emplace(it->second); } else { if(children_processed==0) { switch(getGateType(g)) { case BooleanGate::IN: partial_value = getProb(g); break; case BooleanGate::NOT: partial_value = 1-getProb(*getWires(g).begin()); break; case BooleanGate::AND: partial_value = 1; break; case BooleanGate::OR: partial_value = 0; break; default: assert(false); } } else { if(getGateType(g) == BooleanGate::AND) { partial_value *= child_value; } else { // BooleanGate::OR partial_value += child_value; } } if(getGateType(g)!=BooleanGate::NOT && children_processed<getWires(g).size()) { stack.emplace(RecursionParams{g,children_processed+1,partial_value}); stack.emplace(RecursionParams{getWires(g)[children_processed],0,0.}); } else { result = partial_value; cache[g]=result; if(stack.empty()) return result; else stack.emplace(result); } } } // We return from within the while loop, when the stack is empty assert(false); } <|endoftext|>
<commit_before>/*$Id$ * * This source file is a part of the Berlin Project. * Copyright (C) 2000 Stefan Seefeld <stefan@berlin-consortium.org> * http://www.berlin-consortium.org * * 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. */ #ifndef _Console_hh #define _Console_hh #include <Warsaw/config.hh> #include <Warsaw/Types.hh> #include <Warsaw/Input.hh> #include <Warsaw/Drawable.hh> #include <Warsaw/Raster.hh> #include <Berlin/config.hh> #include <stdexcept> #include <iosfwd> #include <vector> //. This is an abstraction of the underlying graphics libraries Berlin uses. //. The DrawingKits call the methods of this object. class Console { public: class Drawable; //. Extensions are a means to provide special APIs //. that are not supported on all Consoles class Extension { public: virtual ~Extension(){} }; private: typedef std::vector<Extension *> elist_t; //. Deletes this Console in its Destrcuctor. struct Reaper { ~Reaper(); }; friend struct Reaper; public: class Pointer; //. A helperclass to get the Console-module into memory. class Loader { public: virtual ~Loader() {} virtual Console *load(int &, char **) = 0; }; template <typename T> class LoaderT : public Loader { public: virtual T *load(int &argc, char **argv) { return new T(argc, argv);} }; //. Sets up the graphics library. It gets passed the commandline arguments //. of the server (argc and argv), checks them for any console-related options and //. afterwards passes them on to the graphic's library. Finally you need to pass //. the POA to this method. static int open(const std::string &, int argc, char **argv, PortableServer::POA_ptr) throw(std::runtime_error); //. Get the active instance of the Console. static Console *instance(); //. Get a pointerobject to use on this Console. virtual Pointer *pointer(Warsaw::Raster_ptr) = 0; //. Get the 'root-drawable' used by this Console. That's the chunk of video //. memory covering the whole screen. virtual Drawable *drawable() = 0; //. Creates a new Drawable of the given size (x, y) and depth. virtual Drawable *create_drawable(Warsaw::PixelCoord, //.< Requested x size. Warsaw::PixelCoord, //.< Requested y size. Warsaw::PixelCoord) = 0; //.< Requested color depth. //. Activates a given drawable: After activation it can recieve requests via CORBA. Warsaw::Drawable_ptr activate_drawable(Drawable *); //. FIXME: Missing documentation! PortableServer::Servant reference_to_servant(Warsaw::Drawable_ptr); //. FIXME: Missing documentation! virtual void device_info(std::ostream &) = 0; //. FIXME: Missing documentation! virtual Warsaw::Input::Event *next_event() = 0; //. FIXME: Missing documentation! virtual void wakeup() = 0; //. FIXME: Missing documentation! virtual void activate_autoplay() = 0; //. Highlight the specified region to aid debugging. //. You can set the color of the highlight by passing a //. red, green and blue betwenn 0.0 and 1.0. If //. you do not pass a color it defaults to red. virtual void highlight_screen(Warsaw::Coord, Warsaw::Coord, Warsaw::Coord, Warsaw::Coord, float red = 1.0, float green = 0.0, float blue = 0.0) = 0; template <typename T> T *get_extension(const std::string &id) { Extension *extension = create_extension(id); T *t = dynamic_cast<T *>(extension); if (!t) { delete extension; throw (std::runtime_error(id + ": no such extension")); } _extensions.push_back(extension); return t; } protected: Console() {} virtual ~Console() {} private: virtual Extension *create_extension(const std::string &) = 0; PortableServer::POA_var _poa; static Console *_console; static Reaper _reaper; elist_t _extensions; }; //. This is a chunk of (video-) memory that is used to store raster data. class Console::Drawable : public virtual POA_Warsaw::Drawable, public virtual PortableServer::RefCountServantBase { public: class Extension : public virtual Console::Extension { public: virtual void attach(Drawable *) = 0; }; typedef char data_type; Drawable() {} virtual ~Drawable() {} //. FIXME: Missing documentation! virtual Warsaw::Drawable::PixelFormat pixel_format() = 0; //. FIXME: Missing documentation! virtual Warsaw::Drawable::BufferFormat buffer_format() = 0; //. FIXME: Missing documentation! virtual Warsaw::PixelCoord width() const = 0; //. FIXME: Missing documentation! virtual Warsaw::PixelCoord height() const = 0; //. FIXME: Missing documentation! virtual Warsaw::PixelCoord vwidth() const = 0; //. FIXME: Missing documentation! virtual Warsaw::PixelCoord vheight() const = 0; //. FIXME: Missing documentation! virtual Warsaw::Coord resolution(Warsaw::Axis) const = 0; //. FIXME: Missing documentation! virtual Warsaw::Coord dpi(Warsaw::Axis) const = 0; //. FIXME: Missing documentation! virtual Warsaw::PixelCoord row_length() const = 0; //. FIXME: Missing documentation! virtual void flush() = 0; //. FIXME: Missing documentation! virtual void flush(Warsaw::PixelCoord, Warsaw::PixelCoord, Warsaw::PixelCoord, Warsaw::PixelCoord) = 0; //. Called by the server when the scene is about to be drawn. //. This is a suitable place to add calls for building display //. lists (for example). virtual void init() = 0; //. Called by the server as soon as the scene finished drawing. virtual void finish() = 0; //. Copy part of this Drawable to a new location in the same Drawable. //. These locations may overlap. virtual void blit(Warsaw::PixelCoord, //.< x position of one corner of the source area Warsaw::PixelCoord, //.< y position of one corner of the source area Warsaw::PixelCoord, //.< width of the source area Warsaw::PixelCoord, //.< height of the source area Warsaw::PixelCoord, //.< x position of correspnding corner of the //.< destination area Warsaw::PixelCoord) = 0; //.< y position of correspnding corner //.< of the destination area //. Copy parts of the given Drawable to the specified position in this Drawable. virtual void blit(const Drawable &, //.< source Drawable Warsaw::PixelCoord, //.< x position of one corner of the source area Warsaw::PixelCoord, //.< y position of one corner of the source area Warsaw::PixelCoord, //.< width of the source area Warsaw::PixelCoord, //.< height of the source area Warsaw::PixelCoord, //.< x position of correspnding corner of the //.< destination area Warsaw::PixelCoord) = 0; //.< y position of correspnding corner //.< of the destination area //. Copy parts of the given Drawable to the specified position in this Drawable virtual void blit(Warsaw::Drawable_ptr, //.< source Drawable Warsaw::PixelCoord, //.< x position of one corner of the source area Warsaw::PixelCoord, //.< y position of one corner of the source area Warsaw::PixelCoord, //.< width of the source area Warsaw::PixelCoord, //.< height of the source area Warsaw::PixelCoord, //.< x position of correspnding corner of the //.< destination area Warsaw::PixelCoord) = 0; //.< y position of correspnding corner //.< of the destination area private: Drawable(const Drawable &); Drawable &operator = (const Drawable &); }; //. This class is used to render the mousepointer. class Console::Pointer : public virtual PortableServer::RefCountServantBase { public: virtual ~Pointer() {} //. return the raster associated with this pointer virtual Warsaw::Raster_ptr raster() = 0; //. Move the pointer to the given Pixelcoordinate. virtual void move(Warsaw::Coord, Warsaw::Coord) = 0; //. FIXME: Missing documentation! virtual void draw() = 0; //. FIXME: Missing documentation! virtual void save() = 0; //. FIXME: Missing documentation! virtual void restore() = 0; //. FIXME: Missing documentation! virtual bool intersects(Warsaw::Coord, Warsaw::Coord, Warsaw::Coord, Warsaw::Coord) = 0; }; #endif <commit_msg>Fix build bustage.<commit_after>/*$Id$ * * This source file is a part of the Berlin Project. * Copyright (C) 2000 Stefan Seefeld <stefan@berlin-consortium.org> * http://www.berlin-consortium.org * * 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. */ #ifndef _Console_hh #define _Console_hh #include <Warsaw/config.hh> #include <Warsaw/Types.hh> #include <Warsaw/Input.hh> #include <Warsaw/Drawable.hh> #include <Warsaw/Raster.hh> #include <Berlin/config.hh> #include <stdexcept> #include <iosfwd> #include <vector> //. This is an abstraction of the underlying graphics libraries Berlin uses. //. The DrawingKits call the methods of this object. class Console { public: class Drawable; //. Extensions are a means to provide special APIs //. that are not supported on all Consoles class Extension { public: virtual ~Extension(){} }; private: typedef std::vector<Extension *> elist_t; //. Deletes this Console in its Destrcuctor. struct Reaper { ~Reaper(); }; friend struct Reaper; public: class Pointer; //. A helperclass to get the Console-module into memory. class Loader { public: virtual ~Loader() {} virtual Console *load(int &, char **) = 0; }; template <typename T> class LoaderT : public Loader { public: virtual T *load(int &argc, char **argv) { return new T(argc, argv);} }; //. Sets up the graphics library. It gets passed the commandline arguments //. of the server (argc and argv), checks them for any console-related options and //. afterwards passes them on to the graphic's library. Finally you need to pass //. the POA to this method. static int open(const std::string &, int argc, char **argv, PortableServer::POA_ptr) throw(std::runtime_error); //. Get the active instance of the Console. static Console *instance(); //. Get a pointerobject to use on this Console. virtual Pointer *pointer(Warsaw::Raster_ptr) = 0; //. Get the 'root-drawable' used by this Console. That's the chunk of video //. memory covering the whole screen. virtual Drawable *drawable() = 0; //. Creates a new Drawable of the given size (x, y) and depth. virtual Drawable *create_drawable(Warsaw::PixelCoord, //.< Requested x size. Warsaw::PixelCoord, //.< Requested y size. Warsaw::PixelCoord) = 0; //.< Requested color depth. //. Activates a given drawable: After activation it can recieve requests via CORBA. Warsaw::Drawable_ptr activate_drawable(Drawable *); //. FIXME: Missing documentation! PortableServer::Servant reference_to_servant(Warsaw::Drawable_ptr); //. FIXME: Missing documentation! virtual void device_info(std::ostream &) = 0; //. FIXME: Missing documentation! virtual Warsaw::Input::Event *next_event() = 0; //. FIXME: Missing documentation! virtual void wakeup() = 0; //. FIXME: Missing documentation! virtual void activate_autoplay() = 0; #ifdef RMDEBUG //. Highlight the specified region to aid debugging. //. You can set the color of the highlight by passing a //. red, green and blue betwenn 0.0 and 1.0. If //. you do not pass a color it defaults to red. virtual void highlight_screen(Warsaw::Coord, Warsaw::Coord, Warsaw::Coord, Warsaw::Coord, float red = 1.0, float green = 0.0, float blue = 0.0) = 0; #endif template <typename T> T *get_extension(const std::string &id) { Extension *extension = create_extension(id); T *t = dynamic_cast<T *>(extension); if (!t) { delete extension; throw (std::runtime_error(id + ": no such extension")); } _extensions.push_back(extension); return t; } protected: Console() {} virtual ~Console() {} private: virtual Extension *create_extension(const std::string &) = 0; PortableServer::POA_var _poa; static Console *_console; static Reaper _reaper; elist_t _extensions; }; //. This is a chunk of (video-) memory that is used to store raster data. class Console::Drawable : public virtual POA_Warsaw::Drawable, public virtual PortableServer::RefCountServantBase { public: class Extension : public virtual Console::Extension { public: virtual void attach(Drawable *) = 0; }; typedef char data_type; Drawable() {} virtual ~Drawable() {} //. FIXME: Missing documentation! virtual Warsaw::Drawable::PixelFormat pixel_format() = 0; //. FIXME: Missing documentation! virtual Warsaw::Drawable::BufferFormat buffer_format() = 0; //. FIXME: Missing documentation! virtual Warsaw::PixelCoord width() const = 0; //. FIXME: Missing documentation! virtual Warsaw::PixelCoord height() const = 0; //. FIXME: Missing documentation! virtual Warsaw::PixelCoord vwidth() const = 0; //. FIXME: Missing documentation! virtual Warsaw::PixelCoord vheight() const = 0; //. FIXME: Missing documentation! virtual Warsaw::Coord resolution(Warsaw::Axis) const = 0; //. FIXME: Missing documentation! virtual Warsaw::Coord dpi(Warsaw::Axis) const = 0; //. FIXME: Missing documentation! virtual Warsaw::PixelCoord row_length() const = 0; //. FIXME: Missing documentation! virtual void flush() = 0; //. FIXME: Missing documentation! virtual void flush(Warsaw::PixelCoord, Warsaw::PixelCoord, Warsaw::PixelCoord, Warsaw::PixelCoord) = 0; //. Called by the server when the scene is about to be drawn. //. This is a suitable place to add calls for building display //. lists (for example). virtual void init() = 0; //. Called by the server as soon as the scene finished drawing. virtual void finish() = 0; //. Copy part of this Drawable to a new location in the same Drawable. //. These locations may overlap. virtual void blit(Warsaw::PixelCoord, //.< x position of one corner of the source area Warsaw::PixelCoord, //.< y position of one corner of the source area Warsaw::PixelCoord, //.< width of the source area Warsaw::PixelCoord, //.< height of the source area Warsaw::PixelCoord, //.< x position of correspnding corner of the //.< destination area Warsaw::PixelCoord) = 0; //.< y position of correspnding corner //.< of the destination area //. Copy parts of the given Drawable to the specified position in this Drawable. virtual void blit(const Drawable &, //.< source Drawable Warsaw::PixelCoord, //.< x position of one corner of the source area Warsaw::PixelCoord, //.< y position of one corner of the source area Warsaw::PixelCoord, //.< width of the source area Warsaw::PixelCoord, //.< height of the source area Warsaw::PixelCoord, //.< x position of correspnding corner of the //.< destination area Warsaw::PixelCoord) = 0; //.< y position of correspnding corner //.< of the destination area //. Copy parts of the given Drawable to the specified position in this Drawable virtual void blit(Warsaw::Drawable_ptr, //.< source Drawable Warsaw::PixelCoord, //.< x position of one corner of the source area Warsaw::PixelCoord, //.< y position of one corner of the source area Warsaw::PixelCoord, //.< width of the source area Warsaw::PixelCoord, //.< height of the source area Warsaw::PixelCoord, //.< x position of correspnding corner of the //.< destination area Warsaw::PixelCoord) = 0; //.< y position of correspnding corner //.< of the destination area private: Drawable(const Drawable &); Drawable &operator = (const Drawable &); }; //. This class is used to render the mousepointer. class Console::Pointer : public virtual PortableServer::RefCountServantBase { public: virtual ~Pointer() {} //. return the raster associated with this pointer virtual Warsaw::Raster_ptr raster() = 0; //. Move the pointer to the given Pixelcoordinate. virtual void move(Warsaw::Coord, Warsaw::Coord) = 0; //. FIXME: Missing documentation! virtual void draw() = 0; //. FIXME: Missing documentation! virtual void save() = 0; //. FIXME: Missing documentation! virtual void restore() = 0; //. FIXME: Missing documentation! virtual bool intersects(Warsaw::Coord, Warsaw::Coord, Warsaw::Coord, Warsaw::Coord) = 0; }; #endif <|endoftext|>
<commit_before>// (C) Copyright Gennadiy Rozental 2001-2005. // (C) Copyright Beman Dawes 2001. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : tests an ability of Unit Test Framework to catch all kinds // of test errors in a user code and properly report it. // *************************************************************************** // Boost.Test #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> #include <boost/test/unit_test_log.hpp> #include <boost/test/framework.hpp> #include <boost/test/detail/unit_test_parameters.hpp> #include <boost/test/output/compiler_log_formatter.hpp> #include <boost/test/results_reporter.hpp> // STL #include <iostream> #include <stdexcept> using namespace boost::unit_test; using namespace boost::test_tools; #if defined(__GNUC__) || defined(__SUNPRO_CC) #define LIMITED_TEST #endif namespace { struct this_test_log_formatter : public boost::unit_test::output::compiler_log_formatter { void print_prefix( std::ostream& output, boost::unit_test::const_string, std::size_t line ) { output << line << ": "; } void test_unit_finish( std::ostream& output, test_unit const& tu, unsigned long elapsed ) { output << "Leaving test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl; } }; //____________________________________________________________________________// char const* log_level_name[] = { "log_successful_tests", "log_test_suites", "log_messages", "log_warnings", "log_all_errors", "log_cpp_exception_errors", "log_system_errors", "log_fatal_errors", "log_nothing" }; enum error_type_enum { et_begin, et_none = et_begin, et_message, et_warning, et_user, et_cpp_exception, #ifdef LIMITED_TEST et_fatal_user, #else et_system, et_fatal_user, et_fatal_system, #endif et_end } error_type; char const* error_type_name[] = { "no error", "user message", "user warning", "user non-fatal error", "cpp exception", " system error", "user fatal error", "system fatal error" }; int divide_by_zero = 0; void error_on_demand() { switch( error_type ) { case et_none: BOOST_CHECK_MESSAGE( divide_by_zero == 0, "no error" ); break; case et_message: BOOST_MESSAGE( "message" ); break; case et_warning: BOOST_WARN_MESSAGE( divide_by_zero != 0, "warning" ); break; case et_user: BOOST_ERROR( "non-fatal error" ); break; case et_fatal_user: BOOST_FAIL( "fatal error" ); BOOST_ERROR( "Should never reach this code!" ); break; case et_cpp_exception: BOOST_CHECKPOINT( "error_on_demand() throw runtime_error" ); throw std::runtime_error( "test std::runtime error what() message" ); #ifndef LIMITED_TEST case et_system: BOOST_CHECKPOINT( "error_on_demand() divide by zero" ); divide_by_zero = 1 / divide_by_zero; break; case et_fatal_system: BOOST_CHECKPOINT( "write to an invalid address" ); { int* p = 0; *p = 0; BOOST_ERROR( "Should never reach this code!" ); } break; #endif default: BOOST_ERROR( "Should never reach this code!" ); } return; } } // local namespace //____________________________________________________________________________// int test_main( int argc, char * argv[] ) { #define PATTERN_FILE_NAME "errors_handling_test.pattern" std::string pattern_file_name( argc <= 1 ? (runtime_config::save_pattern() ? PATTERN_FILE_NAME : "./test_files/" PATTERN_FILE_NAME ) : argv[1] ); #ifdef LIMITED_TEST pattern_file_name += "2"; #endif output_test_stream test_output( pattern_file_name, !runtime_config::save_pattern() ); test_case* test = BOOST_TEST_CASE( &error_on_demand ); // for each log level for( log_level level = log_successful_tests; level <= log_nothing; level = static_cast<log_level>(level+1) ) { // for each error type for( error_type = et_begin; error_type != et_end; error_type = static_cast<error_type_enum>(error_type+1) ) { test_output << "\n===========================\n" << "log level: " << log_level_name[level] << ';' << " error type: " << error_type_name[error_type] << ";\n" << std::endl; unit_test_log.set_stream( test_output ); unit_test_log.set_formatter( new this_test_log_formatter ); unit_test_log.set_threshold_level( level ); framework::run( test ); unit_test_log.set_stream( std::cout ); unit_test_log.set_format( runtime_config::log_format() ); unit_test_log.set_threshold_level( runtime_config::log_level() != invalid_log_level ? runtime_config::log_level() : log_all_errors ); BOOST_CHECK( test_output.match_pattern() ); } } return 0; } // main //____________________________________________________________________________// // *************************************************************************** // Revision History : // // $Log$ // Revision 1.34 2005/06/11 19:20:58 rogeeff // *** empty log message *** // // Revision 1.33 2005/05/11 05:07:56 rogeeff // licence update // // Revision 1.32 2005/03/23 21:06:39 rogeeff // Sunpro CC 5.3 fixes // // Revision 1.31 2005/03/22 07:14:44 rogeeff // no message // // Revision 1.30 2005/02/23 06:36:01 vawjr // Deleted - extraneous \r characters in the file // // Revision 1.29 2005/02/20 08:28:34 rogeeff // This a major update for Boost.Test framework. See release docs for complete list of fixes/updates // // *************************************************************************** // EOF <commit_msg>Use limited tests with Tru64/CXX.<commit_after>// (C) Copyright Gennadiy Rozental 2001-2005. // (C) Copyright Beman Dawes 2001. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : tests an ability of Unit Test Framework to catch all kinds // of test errors in a user code and properly report it. // *************************************************************************** // Boost.Test #include <boost/test/unit_test.hpp> #include <boost/test/output_test_stream.hpp> #include <boost/test/unit_test_log.hpp> #include <boost/test/framework.hpp> #include <boost/test/detail/unit_test_parameters.hpp> #include <boost/test/output/compiler_log_formatter.hpp> #include <boost/test/results_reporter.hpp> // STL #include <iostream> #include <stdexcept> using namespace boost::unit_test; using namespace boost::test_tools; #if defined(__GNUC__) || defined(__SUNPRO_CC) || defined(__DECCXX_VER) #define LIMITED_TEST #endif namespace { struct this_test_log_formatter : public boost::unit_test::output::compiler_log_formatter { void print_prefix( std::ostream& output, boost::unit_test::const_string, std::size_t line ) { output << line << ": "; } void test_unit_finish( std::ostream& output, test_unit const& tu, unsigned long elapsed ) { output << "Leaving test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl; } }; //____________________________________________________________________________// char const* log_level_name[] = { "log_successful_tests", "log_test_suites", "log_messages", "log_warnings", "log_all_errors", "log_cpp_exception_errors", "log_system_errors", "log_fatal_errors", "log_nothing" }; enum error_type_enum { et_begin, et_none = et_begin, et_message, et_warning, et_user, et_cpp_exception, #ifdef LIMITED_TEST et_fatal_user, #else et_system, et_fatal_user, et_fatal_system, #endif et_end } error_type; char const* error_type_name[] = { "no error", "user message", "user warning", "user non-fatal error", "cpp exception", " system error", "user fatal error", "system fatal error" }; int divide_by_zero = 0; void error_on_demand() { switch( error_type ) { case et_none: BOOST_CHECK_MESSAGE( divide_by_zero == 0, "no error" ); break; case et_message: BOOST_MESSAGE( "message" ); break; case et_warning: BOOST_WARN_MESSAGE( divide_by_zero != 0, "warning" ); break; case et_user: BOOST_ERROR( "non-fatal error" ); break; case et_fatal_user: BOOST_FAIL( "fatal error" ); BOOST_ERROR( "Should never reach this code!" ); break; case et_cpp_exception: BOOST_CHECKPOINT( "error_on_demand() throw runtime_error" ); throw std::runtime_error( "test std::runtime error what() message" ); #ifndef LIMITED_TEST case et_system: BOOST_CHECKPOINT( "error_on_demand() divide by zero" ); divide_by_zero = 1 / divide_by_zero; break; case et_fatal_system: BOOST_CHECKPOINT( "write to an invalid address" ); { int* p = 0; *p = 0; BOOST_ERROR( "Should never reach this code!" ); } break; #endif default: BOOST_ERROR( "Should never reach this code!" ); } return; } } // local namespace //____________________________________________________________________________// int test_main( int argc, char * argv[] ) { #define PATTERN_FILE_NAME "errors_handling_test.pattern" std::string pattern_file_name( argc <= 1 ? (runtime_config::save_pattern() ? PATTERN_FILE_NAME : "./test_files/" PATTERN_FILE_NAME ) : argv[1] ); #ifdef LIMITED_TEST pattern_file_name += "2"; #endif output_test_stream test_output( pattern_file_name, !runtime_config::save_pattern() ); test_case* test = BOOST_TEST_CASE( &error_on_demand ); // for each log level for( log_level level = log_successful_tests; level <= log_nothing; level = static_cast<log_level>(level+1) ) { // for each error type for( error_type = et_begin; error_type != et_end; error_type = static_cast<error_type_enum>(error_type+1) ) { test_output << "\n===========================\n" << "log level: " << log_level_name[level] << ';' << " error type: " << error_type_name[error_type] << ";\n" << std::endl; unit_test_log.set_stream( test_output ); unit_test_log.set_formatter( new this_test_log_formatter ); unit_test_log.set_threshold_level( level ); framework::run( test ); unit_test_log.set_stream( std::cout ); unit_test_log.set_format( runtime_config::log_format() ); unit_test_log.set_threshold_level( runtime_config::log_level() != invalid_log_level ? runtime_config::log_level() : log_all_errors ); BOOST_CHECK( test_output.match_pattern() ); } } return 0; } // main //____________________________________________________________________________// // *************************************************************************** // Revision History : // // $Log$ // Revision 1.35 2005/06/13 11:46:26 schoepflin // Use limited tests with Tru64/CXX. // // Revision 1.34 2005/06/11 19:20:58 rogeeff // *** empty log message *** // // Revision 1.33 2005/05/11 05:07:56 rogeeff // licence update // // Revision 1.32 2005/03/23 21:06:39 rogeeff // Sunpro CC 5.3 fixes // // Revision 1.31 2005/03/22 07:14:44 rogeeff // no message // // Revision 1.30 2005/02/23 06:36:01 vawjr // Deleted - extraneous \r characters in the file // // Revision 1.29 2005/02/20 08:28:34 rogeeff // This a major update for Boost.Test framework. See release docs for complete list of fixes/updates // // *************************************************************************** // EOF <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <algorithm> #include <iostream> #include <iomanip> #include "libtorrent/entry.hpp" #include "libtorrent/config.hpp" #if defined(_MSC_VER) namespace std { using ::isprint; } #define for if (false) {} else for #endif namespace { template <class T> void call_destructor(T* o) { TORRENT_ASSERT(o); o->~T(); } struct compare_string { compare_string(char const* s): m_str(s) {} bool operator()( std::pair<std::string , libtorrent::entry> const& e) const { return m_str && e.first == m_str; } char const* m_str; }; } namespace libtorrent { namespace detail { TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val) { int sign = 0; if (val < 0) { sign = 1; val = -val; } buf[--size] = '\0'; if (val == 0) buf[--size] = '0'; for (; size > sign && val != 0;) { buf[--size] = '0' + char(val % 10); val /= 10; } if (sign) buf[--size] = '-'; return buf + size; } } entry& entry::operator[](char const* key) { dictionary_type::iterator i = dict().find(key); if (i != dict().end()) return i->second; dictionary_type::iterator ret = dict().insert( dict().begin() , std::make_pair(std::string(key), entry())); return ret->second; } entry& entry::operator[](std::string const& key) { return (*this)[key.c_str()]; } entry* entry::find_key(char const* key) { dictionary_type::iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) return 0; return &i->second; } entry const* entry::find_key(char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) return 0; return &i->second; } #ifndef BOOST_NO_EXCEPTIONS const entry& entry::operator[](char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) throw type_error( (std::string("key not found: ") + key).c_str()); return i->second; } const entry& entry::operator[](std::string const& key) const { return (*this)[key.c_str()]; } #endif entry::entry(): m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(data_type t): m_type(t) { construct(t); #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(const entry& e) { copy(e); #ifndef NDEBUG m_type_queried = e.m_type_queried; #endif } entry::entry(dictionary_type const& v) { #ifndef NDEBUG m_type_queried = true; #endif new(data) dictionary_type(v); m_type = dictionary_t; } entry::entry(string_type const& v) { #ifndef NDEBUG m_type_queried = true; #endif new(data) string_type(v); m_type = string_t; } entry::entry(list_type const& v) { #ifndef NDEBUG m_type_queried = true; #endif new(data) list_type(v); m_type = list_t; } entry::entry(integer_type const& v) { #ifndef NDEBUG m_type_queried = true; #endif new(data) integer_type(v); m_type = int_t; } void entry::operator=(dictionary_type const& v) { destruct(); new(data) dictionary_type(v); m_type = dictionary_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(string_type const& v) { destruct(); new(data) string_type(v); m_type = string_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(list_type const& v) { destruct(); new(data) list_type(v); m_type = list_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(integer_type const& v) { destruct(); new(data) integer_type(v); m_type = int_t; #ifndef NDEBUG m_type_queried = true; #endif } bool entry::operator==(entry const& e) const { if (m_type != e.m_type) return false; switch(m_type) { case int_t: return integer() == e.integer(); case string_t: return string() == e.string(); case list_t: return list() == e.list(); case dictionary_t: return dict() == e.dict(); default: TORRENT_ASSERT(m_type == undefined_t); return true; } } void entry::construct(data_type t) { m_type = t; switch(m_type) { case int_t: new(data) integer_type; break; case string_t: new(data) string_type; break; case list_t: new(data) list_type; break; case dictionary_t: new (data) dictionary_type; break; default: TORRENT_ASSERT(m_type == undefined_t); m_type = undefined_t; } #ifndef NDEBUG m_type_queried = true; #endif } void entry::copy(entry const& e) { m_type = e.type(); switch(m_type) { case int_t: new(data) integer_type(e.integer()); break; case string_t: new(data) string_type(e.string()); break; case list_t: new(data) list_type(e.list()); break; case dictionary_t: new (data) dictionary_type(e.dict()); break; default: m_type = undefined_t; } #ifndef NDEBUG m_type_queried = true; #endif } void entry::destruct() { switch(m_type) { case int_t: call_destructor(reinterpret_cast<integer_type*>(data)); break; case string_t: call_destructor(reinterpret_cast<string_type*>(data)); break; case list_t: call_destructor(reinterpret_cast<list_type*>(data)); break; case dictionary_t: call_destructor(reinterpret_cast<dictionary_type*>(data)); break; default: TORRENT_ASSERT(m_type == undefined_t); break; } #ifndef NDEBUG m_type_queried = false; #endif } void entry::swap(entry& e) { // not implemented TORRENT_ASSERT(false); } void entry::print(std::ostream& os, int indent) const { TORRENT_ASSERT(indent >= 0); for (int i = 0; i < indent; ++i) os << " "; switch (m_type) { case int_t: os << integer() << "\n"; break; case string_t: { bool binary_string = false; for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) { if (!std::isprint(static_cast<unsigned char>(*i))) { binary_string = true; break; } } if (binary_string) { os.unsetf(std::ios_base::dec); os.setf(std::ios_base::hex); for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) os << std::setfill('0') << std::setw(2) << static_cast<unsigned int>((unsigned char)*i); os.unsetf(std::ios_base::hex); os.setf(std::ios_base::dec); os << "\n"; } else { os << string() << "\n"; } } break; case list_t: { os << "list\n"; for (list_type::const_iterator i = list().begin(); i != list().end(); ++i) { i->print(os, indent+1); } } break; case dictionary_t: { os << "dictionary\n"; for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i) { for (int j = 0; j < indent+1; ++j) os << " "; os << "[" << i->first << "]"; if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n"; else os << " "; i->second.print(os, indent+2); } } break; default: os << "<uninitialized>\n"; } } } <commit_msg>exception safety fixes to entry.cpp<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <algorithm> #include <iostream> #include <iomanip> #include "libtorrent/entry.hpp" #include "libtorrent/config.hpp" #if defined(_MSC_VER) namespace std { using ::isprint; } #define for if (false) {} else for #endif namespace { template <class T> void call_destructor(T* o) { TORRENT_ASSERT(o); o->~T(); } struct compare_string { compare_string(char const* s): m_str(s) {} bool operator()( std::pair<std::string , libtorrent::entry> const& e) const { return m_str && e.first == m_str; } char const* m_str; }; } namespace libtorrent { namespace detail { TORRENT_EXPORT char const* integer_to_str(char* buf, int size, entry::integer_type val) { int sign = 0; if (val < 0) { sign = 1; val = -val; } buf[--size] = '\0'; if (val == 0) buf[--size] = '0'; for (; size > sign && val != 0;) { buf[--size] = '0' + char(val % 10); val /= 10; } if (sign) buf[--size] = '-'; return buf + size; } } entry& entry::operator[](char const* key) { dictionary_type::iterator i = dict().find(key); if (i != dict().end()) return i->second; dictionary_type::iterator ret = dict().insert( dict().begin() , std::make_pair(std::string(key), entry())); return ret->second; } entry& entry::operator[](std::string const& key) { return (*this)[key.c_str()]; } entry* entry::find_key(char const* key) { dictionary_type::iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) return 0; return &i->second; } entry const* entry::find_key(char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) return 0; return &i->second; } #ifndef BOOST_NO_EXCEPTIONS const entry& entry::operator[](char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) throw type_error( (std::string("key not found: ") + key).c_str()); return i->second; } const entry& entry::operator[](std::string const& key) const { return (*this)[key.c_str()]; } #endif entry::entry() : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(data_type t) : m_type(undefined_t) { construct(t); #ifndef NDEBUG m_type_queried = true; #endif } entry::entry(const entry& e) : m_type(undefined_t) { copy(e); #ifndef NDEBUG m_type_queried = e.m_type_queried; #endif } entry::entry(dictionary_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) dictionary_type(v); m_type = dictionary_t; } entry::entry(string_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) string_type(v); m_type = string_t; } entry::entry(list_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) list_type(v); m_type = list_t; } entry::entry(integer_type const& v) : m_type(undefined_t) { #ifndef NDEBUG m_type_queried = true; #endif new(data) integer_type(v); m_type = int_t; } void entry::operator=(dictionary_type const& v) { destruct(); new(data) dictionary_type(v); m_type = dictionary_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(string_type const& v) { destruct(); new(data) string_type(v); m_type = string_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(list_type const& v) { destruct(); new(data) list_type(v); m_type = list_t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::operator=(integer_type const& v) { destruct(); new(data) integer_type(v); m_type = int_t; #ifndef NDEBUG m_type_queried = true; #endif } bool entry::operator==(entry const& e) const { if (m_type != e.m_type) return false; switch(m_type) { case int_t: return integer() == e.integer(); case string_t: return string() == e.string(); case list_t: return list() == e.list(); case dictionary_t: return dict() == e.dict(); default: TORRENT_ASSERT(m_type == undefined_t); return true; } } void entry::construct(data_type t) { switch(t) { case int_t: new(data) integer_type; break; case string_t: new(data) string_type; break; case list_t: new(data) list_type; break; case dictionary_t: new (data) dictionary_type; break; default: TORRENT_ASSERT(t == undefined_t); } m_type = t; #ifndef NDEBUG m_type_queried = true; #endif } void entry::copy(entry const& e) { switch (e.type()) { case int_t: new(data) integer_type(e.integer()); break; case string_t: new(data) string_type(e.string()); break; case list_t: new(data) list_type(e.list()); break; case dictionary_t: new (data) dictionary_type(e.dict()); break; default: TORRENT_ASSERT(e.type() == undefined_t); } m_type = e.type(); #ifndef NDEBUG m_type_queried = true; #endif } void entry::destruct() { switch(m_type) { case int_t: call_destructor(reinterpret_cast<integer_type*>(data)); break; case string_t: call_destructor(reinterpret_cast<string_type*>(data)); break; case list_t: call_destructor(reinterpret_cast<list_type*>(data)); break; case dictionary_t: call_destructor(reinterpret_cast<dictionary_type*>(data)); break; default: TORRENT_ASSERT(m_type == undefined_t); break; } m_type = undefined_t; #ifndef NDEBUG m_type_queried = false; #endif } void entry::swap(entry& e) { // not implemented TORRENT_ASSERT(false); } void entry::print(std::ostream& os, int indent) const { TORRENT_ASSERT(indent >= 0); for (int i = 0; i < indent; ++i) os << " "; switch (m_type) { case int_t: os << integer() << "\n"; break; case string_t: { bool binary_string = false; for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) { if (!std::isprint(static_cast<unsigned char>(*i))) { binary_string = true; break; } } if (binary_string) { os.unsetf(std::ios_base::dec); os.setf(std::ios_base::hex); for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) os << std::setfill('0') << std::setw(2) << static_cast<unsigned int>((unsigned char)*i); os.unsetf(std::ios_base::hex); os.setf(std::ios_base::dec); os << "\n"; } else { os << string() << "\n"; } } break; case list_t: { os << "list\n"; for (list_type::const_iterator i = list().begin(); i != list().end(); ++i) { i->print(os, indent+1); } } break; case dictionary_t: { os << "dictionary\n"; for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i) { for (int j = 0; j < indent+1; ++j) os << " "; os << "[" << i->first << "]"; if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n"; else os << " "; i->second.print(os, indent+2); } } break; default: os << "<uninitialized>\n"; } } } <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef GUARD_TENSOR_HOLDER_HPP #define GUARD_TENSOR_HOLDER_HPP #include "ford.hpp" #include "network_data.hpp" #include <miopen/tensor.hpp> #include <miopen/functional.hpp> template <class F> void visit_tensor_size(std::size_t n, F f) { switch(n) { case 0: { f(std::integral_constant<std::size_t, 0>{}); break; } case 1: { f(std::integral_constant<std::size_t, 1>{}); break; } case 2: { f(std::integral_constant<std::size_t, 2>{}); break; } case 3: { f(std::integral_constant<std::size_t, 3>{}); break; } case 4: { f(std::integral_constant<std::size_t, 4>{}); break; } case 5: { f(std::integral_constant<std::size_t, 5>{}); break; } default: throw std::runtime_error("Unknown tensor size"); } } template <class T> struct tensor { miopen::TensorDescriptor desc; std::vector<T> data; tensor() {} template <class X> tensor(const std::vector<X>& dims) : desc(miopenFloat, dims.data(), static_cast<int>(dims.size())), data(desc.GetElementSize()) { } tensor(std::size_t n, std::size_t c, std::size_t h, std::size_t w) : desc(miopenFloat, {n, c, h, w}), data(n * c * h * w) { } tensor(miopen::TensorDescriptor rhs) : desc(std::move(rhs)) { data.resize(desc.GetElementSpace()); } template <class G> tensor& generate(G g) & { this->generate_impl(g); return *this; } template <class G> tensor&& generate(G g) && { this->generate_impl(g); return std::move(*this); } template <class G> void generate_impl(G g) { auto iterator = data.begin(); auto assign = [&](T x) { assert(iterator < data.end()); *iterator = x; ++iterator; }; this->for_each(miopen::compose(assign, std::move(g))); } template <class Loop, class F> struct for_each_unpacked { Loop loop; F f; template <class... Ts> auto operator()(Ts... xs) const -> decltype(f(xs...), void()) { loop(xs...)(std::move(f)); } struct any { any() {} template<class X> any(X) {} }; void operator()(any={},any={},any={},any={},any={},any={},any={},any={},any={}) const { throw std::runtime_error("Arguments to for_each do not match tensor size"); } }; struct for_each_handler { template <class Self, class Loop, class F, class Size> void operator()(Self* self, Loop loop, F f, Size size) const { auto dims = miopen::tien<size>(self->desc.GetLengths()); miopen::unpack(for_each_unpacked<Loop, F>{loop, std::move(f)}, dims); } }; template <class F> void for_each(F f) const { visit_tensor_size( desc.GetLengths().size(), std::bind(for_each_handler{}, this, ford, std::move(f), std::placeholders::_1)); } template <class F> void par_for_each(F f) const { visit_tensor_size( desc.GetLengths().size(), std::bind(for_each_handler{}, this, par_ford, std::move(f), std::placeholders::_1)); } template <class... Ts> T& operator()(Ts... xs) { assert(this->desc.GetIndex(xs...) < data.size()); return this->data[this->desc.GetIndex(xs...)]; } template <class... Ts> const T& operator()(Ts... xs) const { assert(this->desc.GetIndex(xs...) < data.size()); return this->data[this->desc.GetIndex(xs...)]; } T& operator[](std::size_t i) { return data.at(i); } const T& operator[](std::size_t i) const { return data.at(i); } typename std::vector<T>::iterator begin() { return data.begin(); } typename std::vector<T>::iterator end() { return data.end(); } typename std::vector<T>::const_iterator begin() const { return data.begin(); } typename std::vector<T>::const_iterator end() const { return data.end(); } }; template <class T, class G> tensor<T> make_tensor(std::initializer_list<std::size_t> dims, G g) { // TODO: Compute float return tensor<T>{miopen::TensorDescriptor{miopenFloat, dims}}.generate(g); } template <class T, class X> tensor<T> make_tensor(const std::vector<X>& dims) { // TODO: Compute float return tensor<T>{ miopen::TensorDescriptor{miopenFloat, dims.data(), static_cast<int>(dims.size())}}; } template <class T, class X> tensor<T> make_tensor(const tensor<T> super_tensor, const std::vector<X>& dims, const std::vector<X>& strides) { // TODO: Compute float tensor<T> t = tensor<T>{miopen::TensorDescriptor{ miopenFloat, dims.data(), strides.data(), static_cast<int>(dims.size())}}; t.data = super_tensor.data; return t; } template <class T, class X, class G> tensor<T> make_tensor(const std::vector<X>& dims, G g) { return make_tensor<T>(dims).generate(g); } struct tensor_generate { template <class Tensor, class G> Tensor&& operator()(Tensor&& t, G g) const { return std::forward<Tensor>(t.generate(g)); } }; template <class F> struct protect_void_fn { F f; protect_void_fn(F x) : f(std::move(x)) {} // template<class... Ts> // auto operator()(Ts&&... xs) const MIOPEN_RETURNS // (f(std::forward<Ts>(xs)...)); template <class... Ts> void operator()(Ts&&... xs) const { f(std::forward<Ts>(xs)...); } }; template <class F> protect_void_fn<F> protect_void(F f) { return {std::move(f)}; } struct cross_args_apply { template <class F, class T, class... Ts> void operator()(F f, T&& x, Ts&&... xs) const { miopen::each_args(std::bind(f, std::forward<T>(x), std::placeholders::_1), std::forward<Ts>(xs)...); } }; template <class F, class... Ts> void cross_args(F f, Ts&&... xs) { miopen::each_args(std::bind(cross_args_apply{}, protect_void(std::move(f)), std::placeholders::_1, std::forward<Ts>(xs)...), std::forward<Ts>(xs)...); } template <class T> struct generate_both_visitation { template <class F, class G1, class G2> void operator()(F f, G1 g1, G2 g2) const { for(auto&& input : get_inputs()) for(auto&& weights : get_weights()) if(input.at(1) == weights.at(1)) // channels must match f(make_tensor<T>(input, g1), make_tensor<T>(weights, g2)); } }; template <class T, class F, class... Gs> void generate_binary_all(F f, Gs... gs) { cross_args(std::bind(generate_both_visitation<T>{}, protect_void(f), std::placeholders::_1, std::placeholders::_2), gs...); } template <class T, class F, class G> void generate_binary_one(F f, std::vector<int> input, std::vector<int> weights, G g) { f(make_tensor<T>(input, g), make_tensor<T>(weights, g)); } template <class T> struct generate_activ_visitation { template <class F, class G> void operator()(F f, G g) const { for(auto&& input : get_inputs()) f(make_tensor<T>(input, g)); } }; template <class T, class F, class... Gs> void generate_unary_all(F f, Gs... gs) { miopen::each_args( std::bind(generate_activ_visitation<T>{}, protect_void(f), std::placeholders::_1), gs...); } template <class T, class F, class G> void generate_unary_one(F f, std::vector<int> input, G g) { f(make_tensor<T>(input, g)); } #endif <commit_msg>Formatting<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef GUARD_TENSOR_HOLDER_HPP #define GUARD_TENSOR_HOLDER_HPP #include "ford.hpp" #include "network_data.hpp" #include <miopen/tensor.hpp> #include <miopen/functional.hpp> template <class F> void visit_tensor_size(std::size_t n, F f) { switch(n) { case 0: { f(std::integral_constant<std::size_t, 0>{}); break; } case 1: { f(std::integral_constant<std::size_t, 1>{}); break; } case 2: { f(std::integral_constant<std::size_t, 2>{}); break; } case 3: { f(std::integral_constant<std::size_t, 3>{}); break; } case 4: { f(std::integral_constant<std::size_t, 4>{}); break; } case 5: { f(std::integral_constant<std::size_t, 5>{}); break; } default: throw std::runtime_error("Unknown tensor size"); } } template <class T> struct tensor { miopen::TensorDescriptor desc; std::vector<T> data; tensor() {} template <class X> tensor(const std::vector<X>& dims) : desc(miopenFloat, dims.data(), static_cast<int>(dims.size())), data(desc.GetElementSize()) { } tensor(std::size_t n, std::size_t c, std::size_t h, std::size_t w) : desc(miopenFloat, {n, c, h, w}), data(n * c * h * w) { } tensor(miopen::TensorDescriptor rhs) : desc(std::move(rhs)) { data.resize(desc.GetElementSpace()); } template <class G> tensor& generate(G g) & { this->generate_impl(g); return *this; } template <class G> tensor&& generate(G g) && { this->generate_impl(g); return std::move(*this); } template <class G> void generate_impl(G g) { auto iterator = data.begin(); auto assign = [&](T x) { assert(iterator < data.end()); *iterator = x; ++iterator; }; this->for_each(miopen::compose(assign, std::move(g))); } template <class Loop, class F> struct for_each_unpacked { Loop loop; F f; template <class... Ts> auto operator()(Ts... xs) const -> decltype(f(xs...), void()) { loop(xs...)(std::move(f)); } struct any { any() {} template <class X> any(X) { } }; void operator()(any = {}, any = {}, any = {}, any = {}, any = {}, any = {}, any = {}, any = {}, any = {}) const { throw std::runtime_error("Arguments to for_each do not match tensor size"); } }; struct for_each_handler { template <class Self, class Loop, class F, class Size> void operator()(Self* self, Loop loop, F f, Size size) const { auto dims = miopen::tien<size>(self->desc.GetLengths()); miopen::unpack(for_each_unpacked<Loop, F>{loop, std::move(f)}, dims); } }; template <class F> void for_each(F f) const { visit_tensor_size( desc.GetLengths().size(), std::bind(for_each_handler{}, this, ford, std::move(f), std::placeholders::_1)); } template <class F> void par_for_each(F f) const { visit_tensor_size( desc.GetLengths().size(), std::bind(for_each_handler{}, this, par_ford, std::move(f), std::placeholders::_1)); } template <class... Ts> T& operator()(Ts... xs) { assert(this->desc.GetIndex(xs...) < data.size()); return this->data[this->desc.GetIndex(xs...)]; } template <class... Ts> const T& operator()(Ts... xs) const { assert(this->desc.GetIndex(xs...) < data.size()); return this->data[this->desc.GetIndex(xs...)]; } T& operator[](std::size_t i) { return data.at(i); } const T& operator[](std::size_t i) const { return data.at(i); } typename std::vector<T>::iterator begin() { return data.begin(); } typename std::vector<T>::iterator end() { return data.end(); } typename std::vector<T>::const_iterator begin() const { return data.begin(); } typename std::vector<T>::const_iterator end() const { return data.end(); } }; template <class T, class G> tensor<T> make_tensor(std::initializer_list<std::size_t> dims, G g) { // TODO: Compute float return tensor<T>{miopen::TensorDescriptor{miopenFloat, dims}}.generate(g); } template <class T, class X> tensor<T> make_tensor(const std::vector<X>& dims) { // TODO: Compute float return tensor<T>{ miopen::TensorDescriptor{miopenFloat, dims.data(), static_cast<int>(dims.size())}}; } template <class T, class X> tensor<T> make_tensor(const tensor<T> super_tensor, const std::vector<X>& dims, const std::vector<X>& strides) { // TODO: Compute float tensor<T> t = tensor<T>{miopen::TensorDescriptor{ miopenFloat, dims.data(), strides.data(), static_cast<int>(dims.size())}}; t.data = super_tensor.data; return t; } template <class T, class X, class G> tensor<T> make_tensor(const std::vector<X>& dims, G g) { return make_tensor<T>(dims).generate(g); } struct tensor_generate { template <class Tensor, class G> Tensor&& operator()(Tensor&& t, G g) const { return std::forward<Tensor>(t.generate(g)); } }; template <class F> struct protect_void_fn { F f; protect_void_fn(F x) : f(std::move(x)) {} // template<class... Ts> // auto operator()(Ts&&... xs) const MIOPEN_RETURNS // (f(std::forward<Ts>(xs)...)); template <class... Ts> void operator()(Ts&&... xs) const { f(std::forward<Ts>(xs)...); } }; template <class F> protect_void_fn<F> protect_void(F f) { return {std::move(f)}; } struct cross_args_apply { template <class F, class T, class... Ts> void operator()(F f, T&& x, Ts&&... xs) const { miopen::each_args(std::bind(f, std::forward<T>(x), std::placeholders::_1), std::forward<Ts>(xs)...); } }; template <class F, class... Ts> void cross_args(F f, Ts&&... xs) { miopen::each_args(std::bind(cross_args_apply{}, protect_void(std::move(f)), std::placeholders::_1, std::forward<Ts>(xs)...), std::forward<Ts>(xs)...); } template <class T> struct generate_both_visitation { template <class F, class G1, class G2> void operator()(F f, G1 g1, G2 g2) const { for(auto&& input : get_inputs()) for(auto&& weights : get_weights()) if(input.at(1) == weights.at(1)) // channels must match f(make_tensor<T>(input, g1), make_tensor<T>(weights, g2)); } }; template <class T, class F, class... Gs> void generate_binary_all(F f, Gs... gs) { cross_args(std::bind(generate_both_visitation<T>{}, protect_void(f), std::placeholders::_1, std::placeholders::_2), gs...); } template <class T, class F, class G> void generate_binary_one(F f, std::vector<int> input, std::vector<int> weights, G g) { f(make_tensor<T>(input, g), make_tensor<T>(weights, g)); } template <class T> struct generate_activ_visitation { template <class F, class G> void operator()(F f, G g) const { for(auto&& input : get_inputs()) f(make_tensor<T>(input, g)); } }; template <class T, class F, class... Gs> void generate_unary_all(F f, Gs... gs) { miopen::each_args( std::bind(generate_activ_visitation<T>{}, protect_void(f), std::placeholders::_1), gs...); } template <class T, class F, class G> void generate_unary_one(F f, std::vector<int> input, G g) { f(make_tensor<T>(input, g)); } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/create_torrent.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include <fstream> #include "test.hpp" #include "setup_transfer.hpp" using namespace boost::filesystem; using namespace libtorrent; // proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file, int proxy) { using namespace libtorrent; session ses; session_settings settings; settings.ignore_limits_on_local_network = false; ses.set_settings(settings); ses.set_severity_level(alert::debug); ses.listen_on(std::make_pair(51000, 52000)); ses.set_download_rate_limit(torrent_file->total_size() / 10); remove_all("./tmp1"); char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"}; std::cerr << " ==== TESTING " << test_name[proxy] << " proxy ====" << std::endl; if (proxy) { start_proxy(8002, proxy); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8002; ps.username = "testuser"; ps.password = "testpass"; ps.type = (proxy_settings::proxy_type)proxy; ses.set_web_seed_proxy(ps); } torrent_handle th = ses.add_torrent(*torrent_file, "./tmp1"); std::vector<announce_entry> empty; th.replace_trackers(empty); const size_type total_size = torrent_file->total_size(); float rate_sum = 0.f; float ses_rate_sum = 0.f; for (int i = 0; i < 30; ++i) { torrent_status s = th.status(); session_status ss = ses.status(); std::cerr << (s.progress * 100.f) << " %" << " torrent rate: " << (s.download_rate / 1000.f) << " kB/s" << " session rate: " << (ss.download_rate / 1000.f) << " kB/s" << " session total: " << ss.total_payload_download << " torrent total: " << s.total_payload_download << std::endl; rate_sum += s.download_payload_rate; ses_rate_sum += ss.payload_download_rate; print_alerts(ses, "ses"); if (th.is_seed() && ss.download_rate == 0.f) { TEST_CHECK(ses.status().total_payload_download == total_size); TEST_CHECK(th.status().total_payload_download == total_size); break; } test_sleep(1000); } std::cerr << "total_size: " << total_size << " rate_sum: " << rate_sum << " session_rate_sum: " << ses_rate_sum << std::endl; // the rates for each second should sum up to the total, with a 10% error margin TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f); TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f); TEST_CHECK(th.is_seed()); if (proxy) stop_proxy(8002); remove_all("./tmp1"); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; create_directory("test_torrent"); char random_data[300000]; std::srand(std::time(0)); std::generate(random_data, random_data + sizeof(random_data), &std::rand); std::ofstream("./test_torrent/test1").write(random_data, 35); std::ofstream("./test_torrent/test2").write(random_data, 16536 - 35); std::ofstream("./test_torrent/test3").write(random_data, 16536); std::ofstream("./test_torrent/test4").write(random_data, 17); std::ofstream("./test_torrent/test5").write(random_data, 16536); std::ofstream("./test_torrent/test6").write(random_data, 300000); std::ofstream("./test_torrent/test7").write(random_data, 300000); file_storage fs; add_files(fs, path("test_torrent")); libtorrent::create_torrent t(fs, 16 * 1024); t.add_url_seed("http://127.0.0.1:8000/"); start_web_server(8000); // calculate the hash for all pieces int num = t.num_pieces(); std::vector<char> buf(t.piece_length()); file_pool fp; boost::scoped_ptr<storage_interface> s(default_storage_constructor( fs, ".", fp)); for (int i = 0; i < num; ++i) { s->read(&buf[0], i, 0, fs.piece_size(i)); hasher h(&buf[0], fs.piece_size(i)); t.set_hash(i, h.final()); } boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(t.generate())); for (int i = 0; i < 6; ++i) test_transfer(torrent_file, i); stop_web_server(8000); remove_all("./test_torrent"); return 0; } <commit_msg>fix to test_web_seed<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/create_torrent.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include <fstream> #include "test.hpp" #include "setup_transfer.hpp" using namespace boost::filesystem; using namespace libtorrent; // proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file, int proxy) { using namespace libtorrent; session ses; session_settings settings; settings.ignore_limits_on_local_network = false; ses.set_settings(settings); ses.set_severity_level(alert::debug); ses.listen_on(std::make_pair(51000, 52000)); ses.set_download_rate_limit(torrent_file->total_size() / 10); remove_all("./tmp1"); char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"}; std::cerr << " ==== TESTING " << test_name[proxy] << " proxy ====" << std::endl; if (proxy) { start_proxy(8002, proxy); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8002; ps.username = "testuser"; ps.password = "testpass"; ps.type = (proxy_settings::proxy_type)proxy; ses.set_web_seed_proxy(ps); } torrent_handle th = ses.add_torrent(*torrent_file, "./tmp1"); std::vector<announce_entry> empty; th.replace_trackers(empty); const size_type total_size = torrent_file->total_size(); float rate_sum = 0.f; float ses_rate_sum = 0.f; for (int i = 0; i < 30; ++i) { torrent_status s = th.status(); session_status ss = ses.status(); std::cerr << (s.progress * 100.f) << " %" << " torrent rate: " << (s.download_rate / 1000.f) << " kB/s" << " session rate: " << (ss.download_rate / 1000.f) << " kB/s" << " session total: " << ss.total_payload_download << " torrent total: " << s.total_payload_download << std::endl; rate_sum += s.download_payload_rate; ses_rate_sum += ss.payload_download_rate; print_alerts(ses, "ses"); if (th.is_seed() && ss.download_rate == 0.f) { TEST_CHECK(ses.status().total_payload_download == total_size); TEST_CHECK(th.status().total_payload_download == total_size); break; } test_sleep(1000); } std::cerr << "total_size: " << total_size << " rate_sum: " << rate_sum << " session_rate_sum: " << ses_rate_sum << std::endl; // the rates for each second should sum up to the total, with a 10% error margin TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f); TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f); TEST_CHECK(th.is_seed()); if (proxy) stop_proxy(8002); remove_all("./tmp1"); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; try { create_directory("test_torrent"); } catch (std::exception&) {} char random_data[300000]; std::srand(std::time(0)); std::generate(random_data, random_data + sizeof(random_data), &std::rand); std::ofstream("./test_torrent/test1").write(random_data, 35); std::ofstream("./test_torrent/test2").write(random_data, 16536 - 35); std::ofstream("./test_torrent/test3").write(random_data, 16536); std::ofstream("./test_torrent/test4").write(random_data, 17); std::ofstream("./test_torrent/test5").write(random_data, 16536); std::ofstream("./test_torrent/test6").write(random_data, 300000); std::ofstream("./test_torrent/test7").write(random_data, 300000); file_storage fs; add_files(fs, path("test_torrent")); libtorrent::create_torrent t(fs, 16 * 1024); t.add_url_seed("http://127.0.0.1:8000/"); start_web_server(8000); // calculate the hash for all pieces int num = t.num_pieces(); std::vector<char> buf(t.piece_length()); file_pool fp; boost::scoped_ptr<storage_interface> s(default_storage_constructor( fs, ".", fp)); for (int i = 0; i < num; ++i) { s->read(&buf[0], i, 0, fs.piece_size(i)); hasher h(&buf[0], fs.piece_size(i)); t.set_hash(i, h.final()); } boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(t.generate())); for (int i = 0; i < 6; ++i) test_transfer(torrent_file, i); stop_web_server(8000); remove_all("./test_torrent"); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/create_torrent.hpp" #include "libtorrent/thread.hpp" #include <boost/tuple/tuple.hpp> #include <fstream> #include <iostream> #include "test.hpp" #include "setup_transfer.hpp" using namespace libtorrent; // proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file , int proxy, int port, char const* protocol, bool url_seed, bool chunked_encoding) { using namespace libtorrent; session ses(fingerprint(" ", 0,0,0,0), 0); session_settings settings; settings.max_queued_disk_bytes = 256 * 1024; ses.set_settings(settings); ses.set_alert_mask(~(alert::progress_notification | alert::stats_notification)); ses.listen_on(std::make_pair(51000, 52000)); error_code ec; remove_all("./tmp2_web_seed", ec); char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"}; fprintf(stderr, "\n\n ==== TESTING === proxy: %s ==== protocol: %s ==== seed: %s === transfer-encoding: %s\n\n\n" , test_name[proxy], protocol, url_seed ? "URL seed" : "HTTP seed", chunked_encoding ? "chunked": "none"); if (proxy) { start_proxy(8002, proxy); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8002; ps.username = "testuser"; ps.password = "testpass"; ps.type = (proxy_settings::proxy_type)proxy; ses.set_proxy(ps); } add_torrent_params p; p.auto_managed = false; p.paused = false; p.ti = torrent_file; p.save_path = "./tmp2_web_seed"; p.storage_mode = storage_mode_compact; torrent_handle th = ses.add_torrent(p, ec); std::vector<announce_entry> empty; th.replace_trackers(empty); const size_type total_size = torrent_file->total_size(); float rate_sum = 0.f; float ses_rate_sum = 0.f; cache_status cs; for (int i = 0; i < 30; ++i) { torrent_status s = th.status(); session_status ss = ses.status(); rate_sum += s.download_payload_rate; ses_rate_sum += ss.payload_download_rate; cs = ses.get_cache_status(); if (cs.blocks_read < 1) cs.blocks_read = 1; if (cs.blocks_written < 1) cs.blocks_written = 1; std::cerr << (s.progress * 100.f) << " %" << " torrent rate: " << (s.download_rate / 1000.f) << " kB/s" << " session rate: " << (ss.download_rate / 1000.f) << " kB/s" << " session total: " << ss.total_payload_download << " torrent total: " << s.total_payload_download << " rate sum:" << ses_rate_sum << " cache: " << cs.cache_size << " rcache: " << cs.read_cache_size << " buffers: " << cs.total_used_buffers << std::endl; print_alerts(ses, " >> ses"); if (s.is_seeding /* && ss.download_rate == 0.f*/) { TEST_EQUAL(s.total_payload_download - s.total_redundant_bytes, total_size); // we need to sleep here a bit to let the session sync with the torrent stats test_sleep(1000); TEST_EQUAL(ses.status().total_payload_download - ses.status().total_redundant_bytes , total_size); break; } test_sleep(500); } TEST_EQUAL(cs.cache_size, 0); TEST_EQUAL(cs.total_used_buffers, 0); std::cerr << "total_size: " << total_size << " rate_sum: " << rate_sum << " session_rate_sum: " << ses_rate_sum << " session total download: " << ses.status().total_payload_download << " torrent total download: " << th.status().total_payload_download << " redundant: " << th.status().total_redundant_bytes << std::endl; // the rates for each second should sum up to the total, with a 10% error margin // TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f); // TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f); TEST_CHECK(th.status().is_seeding); if (proxy) stop_proxy(8002); TEST_CHECK(exists(combine_path("./tmp2_web_seed", torrent_file->files().file_path( torrent_file->file_at(0))))); remove_all("./tmp2_web_seed", ec); } void save_file(char const* filename, char const* data, int size) { error_code ec; file out(filename, file::write_only, ec); TEST_CHECK(!ec); if (ec) { fprintf(stderr, "ERROR opening file '%s': %s\n", filename, ec.message().c_str()); return; } file::iovec_t b = { (void*)data, size }; out.writev(0, &b, 1, ec); TEST_CHECK(!ec); if (ec) { fprintf(stderr, "ERROR writing file '%s': %s\n", filename, ec.message().c_str()); return; } } sha1_hash file_hash(std::string const& name) { std::vector<char> buf; error_code ec; load_file(name, buf, ec); if (buf.empty()) return sha1_hash(0); hasher h(&buf[0], buf.size()); return h.final(); } // test_url_seed determines whether to use url-seed or http-seed int run_suite(char const* protocol, bool test_url_seed, bool chunked_encoding) { using namespace libtorrent; error_code ec; create_directories("./tmp1_web_seed/test_torrent_dir", ec); file_storage fs; std::srand(10); int piece_size = 16; if (test_url_seed) { int file_sizes[] = { 5, 16 - 5, 16, 17, 10, 30, 30, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ,1,1,1,1,1,1,13,65,34,75,2,3,4,5,23,9,43,4,43,6, 4}; char* random_data = (char*)malloc(300000); for (int i = 0; i != sizeof(file_sizes)/sizeof(file_sizes[0]); ++i) { std::generate(random_data, random_data + 300000, &std::rand); char filename[200]; snprintf(filename, sizeof(filename), "./tmp1_web_seed/test_torrent_dir/test%d", i); save_file(filename, random_data, file_sizes[i]); } add_files(fs, "./tmp1_web_seed/test_torrent_dir"); free(random_data); } else { piece_size = 64 * 1024; char* random_data = (char*)malloc(64 * 1024 * 25); std::generate(random_data, random_data + 64 * 1024 * 25, &std::rand); save_file("./tmp1_web_seed/seed", random_data, 64 * 1024 * 25); fs.add_file("seed", 64 * 1024 * 25); free(random_data); } int port = start_web_server(strcmp(protocol, "https") == 0, chunked_encoding); libtorrent::create_torrent t(fs, piece_size, 0, libtorrent::create_torrent::calculate_file_hashes); char tmp[512]; if (test_url_seed) { snprintf(tmp, sizeof(tmp), "%s://127.0.0.1:%d/tmp1_web_seed", protocol, port); t.add_url_seed(tmp); } else { snprintf(tmp, sizeof(tmp), "http://127.0.0.1:%d/seed", port); t.add_http_seed(tmp); } // calculate the hash for all pieces set_piece_hashes(t, "./tmp1_web_seed", ec); if (ec) { fprintf(stderr, "error creating hashes for test torrent: %s\n" , ec.message().c_str()); TEST_CHECK(false); return 0; } std::vector<char> buf; bencode(std::back_inserter(buf), t.generate()); boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(&buf[0], buf.size(), ec)); // verify that the file hashes are correct for (int i = 0; i < torrent_file->num_files(); ++i) { sha1_hash h1 = torrent_file->file_at(i).filehash; sha1_hash h2 = file_hash(combine_path("./tmp1_web_seed" , torrent_file->file_at(i).path)); fprintf(stderr, "%s: %s == %s\n" , torrent_file->file_at(i).path.c_str() , to_hex(h1.to_string()).c_str(), to_hex(h2.to_string()).c_str()); TEST_EQUAL(h1, h2); } for (int i = 0; i < 6; ++i) test_transfer(torrent_file, i, port, protocol, test_url_seed, chunked_encoding); if (test_url_seed) { torrent_file->rename_file(0, "./tmp2_web_seed/test_torrent_dir/renamed_test1"); test_transfer(torrent_file, 0, port, protocol, test_url_seed, chunked_encoding); } stop_web_server(); remove_all("./tmp1_web_seed", ec); return 0; } int test_main() { int ret = 0; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { #ifdef TORRENT_USE_OPENSSL run_suite("https", i, j); #endif run_suite("http", i, j); } } return ret; } <commit_msg>don't print so much in test_web_seed<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/storage.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/create_torrent.hpp" #include "libtorrent/thread.hpp" #include <boost/tuple/tuple.hpp> #include <fstream> #include <iostream> #include "test.hpp" #include "setup_transfer.hpp" using namespace libtorrent; // proxy: 0=none, 1=socks4, 2=socks5, 3=socks5_pw 4=http 5=http_pw void test_transfer(boost::intrusive_ptr<torrent_info> torrent_file , int proxy, int port, char const* protocol, bool url_seed, bool chunked_encoding) { using namespace libtorrent; session ses(fingerprint(" ", 0,0,0,0), 0); session_settings settings; settings.max_queued_disk_bytes = 256 * 1024; ses.set_settings(settings); ses.set_alert_mask(~(alert::progress_notification | alert::stats_notification)); ses.listen_on(std::make_pair(51000, 52000)); error_code ec; remove_all("./tmp2_web_seed", ec); char const* test_name[] = {"no", "SOCKS4", "SOCKS5", "SOCKS5 password", "HTTP", "HTTP password"}; fprintf(stderr, "\n\n ==== TESTING === proxy: %s ==== protocol: %s ==== seed: %s === transfer-encoding: %s\n\n\n" , test_name[proxy], protocol, url_seed ? "URL seed" : "HTTP seed", chunked_encoding ? "chunked": "none"); if (proxy) { start_proxy(8002, proxy); proxy_settings ps; ps.hostname = "127.0.0.1"; ps.port = 8002; ps.username = "testuser"; ps.password = "testpass"; ps.type = (proxy_settings::proxy_type)proxy; ses.set_proxy(ps); } add_torrent_params p; p.auto_managed = false; p.paused = false; p.ti = torrent_file; p.save_path = "./tmp2_web_seed"; p.storage_mode = storage_mode_compact; torrent_handle th = ses.add_torrent(p, ec); std::vector<announce_entry> empty; th.replace_trackers(empty); const size_type total_size = torrent_file->total_size(); float rate_sum = 0.f; float ses_rate_sum = 0.f; cache_status cs; for (int i = 0; i < 30; ++i) { torrent_status s = th.status(); session_status ss = ses.status(); rate_sum += s.download_payload_rate; ses_rate_sum += ss.payload_download_rate; cs = ses.get_cache_status(); if (cs.blocks_read < 1) cs.blocks_read = 1; if (cs.blocks_written < 1) cs.blocks_written = 1; /* std::cerr << (s.progress * 100.f) << " %" << " torrent rate: " << (s.download_rate / 1000.f) << " kB/s" << " session rate: " << (ss.download_rate / 1000.f) << " kB/s" << " session total: " << ss.total_payload_download << " torrent total: " << s.total_payload_download << " rate sum:" << ses_rate_sum << " cache: " << cs.cache_size << " rcache: " << cs.read_cache_size << " buffers: " << cs.total_used_buffers << std::endl; */ print_alerts(ses, " >> ses"); if (s.is_seeding /* && ss.download_rate == 0.f*/) { TEST_EQUAL(s.total_payload_download - s.total_redundant_bytes, total_size); // we need to sleep here a bit to let the session sync with the torrent stats test_sleep(1000); TEST_EQUAL(ses.status().total_payload_download - ses.status().total_redundant_bytes , total_size); break; } test_sleep(500); } TEST_EQUAL(cs.cache_size, 0); TEST_EQUAL(cs.total_used_buffers, 0); std::cerr << "total_size: " << total_size << " rate_sum: " << rate_sum << " session_rate_sum: " << ses_rate_sum << " session total download: " << ses.status().total_payload_download << " torrent total download: " << th.status().total_payload_download << " redundant: " << th.status().total_redundant_bytes << std::endl; // the rates for each second should sum up to the total, with a 10% error margin // TEST_CHECK(fabs(rate_sum - total_size) < total_size * .1f); // TEST_CHECK(fabs(ses_rate_sum - total_size) < total_size * .1f); TEST_CHECK(th.status().is_seeding); if (proxy) stop_proxy(8002); TEST_CHECK(exists(combine_path("./tmp2_web_seed", torrent_file->files().file_path( torrent_file->file_at(0))))); remove_all("./tmp2_web_seed", ec); } void save_file(char const* filename, char const* data, int size) { error_code ec; file out(filename, file::write_only, ec); TEST_CHECK(!ec); if (ec) { fprintf(stderr, "ERROR opening file '%s': %s\n", filename, ec.message().c_str()); return; } file::iovec_t b = { (void*)data, size }; out.writev(0, &b, 1, ec); TEST_CHECK(!ec); if (ec) { fprintf(stderr, "ERROR writing file '%s': %s\n", filename, ec.message().c_str()); return; } } sha1_hash file_hash(std::string const& name) { std::vector<char> buf; error_code ec; load_file(name, buf, ec); if (buf.empty()) return sha1_hash(0); hasher h(&buf[0], buf.size()); return h.final(); } // test_url_seed determines whether to use url-seed or http-seed int run_suite(char const* protocol, bool test_url_seed, bool chunked_encoding) { using namespace libtorrent; error_code ec; create_directories("./tmp1_web_seed/test_torrent_dir", ec); file_storage fs; std::srand(10); int piece_size = 16; if (test_url_seed) { int file_sizes[] = { 5, 16 - 5, 16, 17, 10, 30, 30, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ,1,1,1,1,1,1,13,65,34,75,2,3,4,5,23,9,43,4,43,6, 4}; char* random_data = (char*)malloc(300000); for (int i = 0; i != sizeof(file_sizes)/sizeof(file_sizes[0]); ++i) { std::generate(random_data, random_data + 300000, &std::rand); char filename[200]; snprintf(filename, sizeof(filename), "./tmp1_web_seed/test_torrent_dir/test%d", i); save_file(filename, random_data, file_sizes[i]); } add_files(fs, "./tmp1_web_seed/test_torrent_dir"); free(random_data); } else { piece_size = 64 * 1024; char* random_data = (char*)malloc(64 * 1024 * 25); std::generate(random_data, random_data + 64 * 1024 * 25, &std::rand); save_file("./tmp1_web_seed/seed", random_data, 64 * 1024 * 25); fs.add_file("seed", 64 * 1024 * 25); free(random_data); } int port = start_web_server(strcmp(protocol, "https") == 0, chunked_encoding); libtorrent::create_torrent t(fs, piece_size, 0, libtorrent::create_torrent::calculate_file_hashes); char tmp[512]; if (test_url_seed) { snprintf(tmp, sizeof(tmp), "%s://127.0.0.1:%d/tmp1_web_seed", protocol, port); t.add_url_seed(tmp); } else { snprintf(tmp, sizeof(tmp), "http://127.0.0.1:%d/seed", port); t.add_http_seed(tmp); } // calculate the hash for all pieces set_piece_hashes(t, "./tmp1_web_seed", ec); if (ec) { fprintf(stderr, "error creating hashes for test torrent: %s\n" , ec.message().c_str()); TEST_CHECK(false); return 0; } std::vector<char> buf; bencode(std::back_inserter(buf), t.generate()); boost::intrusive_ptr<torrent_info> torrent_file(new torrent_info(&buf[0], buf.size(), ec)); // verify that the file hashes are correct for (int i = 0; i < torrent_file->num_files(); ++i) { sha1_hash h1 = torrent_file->file_at(i).filehash; sha1_hash h2 = file_hash(combine_path("./tmp1_web_seed" , torrent_file->file_at(i).path)); // fprintf(stderr, "%s: %s == %s\n" // , torrent_file->file_at(i).path.c_str() // , to_hex(h1.to_string()).c_str(), to_hex(h2.to_string()).c_str()); TEST_EQUAL(h1, h2); } for (int i = 0; i < 6; ++i) test_transfer(torrent_file, i, port, protocol, test_url_seed, chunked_encoding); if (test_url_seed) { torrent_file->rename_file(0, "./tmp2_web_seed/test_torrent_dir/renamed_test1"); test_transfer(torrent_file, 0, port, protocol, test_url_seed, chunked_encoding); } stop_web_server(); remove_all("./tmp1_web_seed", ec); return 0; } int test_main() { int ret = 0; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { #ifdef TORRENT_USE_OPENSSL run_suite("https", i, j); #endif run_suite("http", i, j); } } return ret; } <|endoftext|>
<commit_before>/* * IceWM * * Copyright (C) 1998-2003 Marko Macek & Nehal Mistry * * Changes: * * 2003/06/14 * * created gnome2 support from gnome.cc */ #include "config.h" #ifdef CONFIG_GNOME_MENUS #include "ylib.h" #include "default.h" #include "ypixbuf.h" #include "yapp.h" #include "sysdep.h" #include "base.h" #include <dirent.h> #include <string.h> #include <gnome.h> #include <libgnome/gnome-desktop-item.h> #include <libgnomevfs/gnome-vfs-init.h> #include "yarray.h" char const * ApplicationName = "icewm-menu-gnome2"; class GnomeMenu; class GnomeMenuItem { public: GnomeMenuItem() { title = 0; icon = 0; dentry = 0; submenu = 0; } const char *title; const char *icon; const char *dentry; GnomeMenu *submenu; }; class GnomeMenu { public: GnomeMenu() { } YObjectArray<GnomeMenuItem> items; bool isDuplicateName(const char *name); void addEntry(const char *fPath, const char *name, const int plen, const bool firstRun); void populateMenu(const char *fPath); }; void dumpMenu(GnomeMenu *menu) { for (int i = 0; i < menu->items.getCount(); i++) { GnomeMenuItem *item = menu->items.getItem(i); if (item->dentry && !item->submenu) { printf("prog \"%s\" %s icewm-menu-gnome2 --open \"%s\"\n", item->title, item->icon ? item->icon : "-", item->dentry); } else if (item->dentry && item->submenu) { printf("menuprog \"%s\" %s icewm-menu-gnome2 --list \"%s\"\n", item->title, item->icon ? item->icon : "-", (!strcmp(my_basename(item->dentry), ".directory") ? g_dirname(item->dentry) : item->dentry)); } } } bool GnomeMenu::isDuplicateName(const char *name) { for (int i = 0; i < items.getCount(); i++) { GnomeMenuItem *item = items.getItem(i); if (strcmp(name, item->title) == 0) return 1; } return 0; } void GnomeMenu::addEntry(const char *fPath, const char *name, const int plen, const bool firstRun) { const int nlen = (plen == 0 || fPath[plen - 1] != '/') ? plen + 1 + strlen(name) : plen + strlen(name); char *npath = new char[nlen + 1]; if (npath) { strcpy(npath, fPath); if (plen == 0 || npath[plen - 1] != '/') { npath[plen] = '/'; strcpy(npath + plen + 1, name); } else strcpy(npath + plen, name); GnomeMenuItem *item = new GnomeMenuItem(); item->title = name; GnomeDesktopItem *ditem = gnome_desktop_item_new_from_file(npath, (GnomeDesktopItemLoadFlags)0, NULL); struct stat sb; const char *type; bool isDir = (!stat(npath, &sb) && S_ISDIR(sb.st_mode)); type = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_TYPE); if (!isDir && type && strstr(type, "Directory")) { isDir = 1; } if (isDir) { GnomeMenu *submenu = new GnomeMenu(); item->title = g_path_get_basename(npath); item->icon = gnome_pixmap_file("gnome-folder.png"); item->submenu = submenu; char *epath = new char[nlen + sizeof("/.directory")]; strcpy(epath, npath); strcpy(epath + nlen, "/.directory"); if (stat(epath, &sb) == -1) { strcpy(epath, npath); } ditem = gnome_desktop_item_new_from_file(epath, (GnomeDesktopItemLoadFlags)0, NULL); if (ditem) { item->title = gnome_desktop_item_get_localestring(ditem, GNOME_DESKTOP_ITEM_NAME); //LXP FX item->icon = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON); } item->dentry = epath; } else { if (type && !strstr(type, "Directory")) { item->title = gnome_desktop_item_get_localestring(ditem, GNOME_DESKTOP_ITEM_NAME); if (gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON)) item->icon = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON); item->dentry = npath; } } if (firstRun || !isDuplicateName(item->title)) items.append(item); } } void GnomeMenu::populateMenu(const char *fPath) { struct stat sb; bool isDir = (!stat(fPath, &sb) && S_ISDIR(sb.st_mode)); const int plen = strlen(fPath); char tmp[256]; strcpy(tmp, fPath); strcat(tmp, "/.directory"); if (isDir && !stat(tmp, &sb)) { // looks like kde/gnome1 style char *opath = new char[plen + sizeof("/.order")]; if (opath) { strcpy(opath, fPath); strcpy(opath + plen, "/.order"); FILE * order(fopen(opath, "r")); if (order) { char oentry[100]; while (fgets(oentry, sizeof (oentry), order)) { const int oend = strlen(oentry) - 1; if (oend > 0 && oentry[oend] == '\n') oentry[oend] = '\0'; addEntry(fPath, oentry, plen, true); } fclose(order); } delete[] opath; } DIR *dir = opendir(fPath); if (dir != 0) { struct dirent *file; while ((file = readdir(dir)) != NULL) { if (*file->d_name != '.') addEntry(fPath, file->d_name, plen, false); } closedir(dir); } } else { // gnome2 style char *category = NULL; char dirname[256] = "a"; if (isDir) { strcpy(dirname, fPath); } else if (strstr(fPath, "Settings")) { strcpy(dirname, "/usr/share/control-center-2.0/capplets/"); } else if (strstr(fPath, "Advanced")) { strcpy(dirname, "/usr/share/control-center-2.0/capplets/"); } else { dirname[0] = '\0'; } if (isDir) { DIR *dir = opendir(dirname); if (dir != 0) { struct dirent *file; while ((file = readdir(dir)) != NULL) { if (!strcmp(dirname, fPath) && (strstr(file->d_name, "Accessibility") || strstr(file->d_name, "Advanced") || strstr(file->d_name, "Applications") || strstr(file->d_name, "Root") )) continue; if (*file->d_name != '.') addEntry(dirname, file->d_name, strlen(dirname), false); } closedir(dir); } } strcpy(dirname, "/usr/share/applications/"); if (isDir) { category = strdup("ion;Core"); } else if (strstr(fPath, "Applications")) { category = strdup("ion;Merg"); } else if (strstr(fPath, "Accessories")) { category = strdup("ion;Util"); } else if (strstr(fPath, "Advanced")) { category = strdup("ngs;Adva"); strcpy(dirname, "/usr/share/control-center-2.0/capplets/"); } else if (strstr(fPath, "Accessibility")) { category = strdup("ngs;Acce"); strcpy(dirname, "/usr/share/control-center-2.0/capplets/"); } else if (strstr(fPath, "Development")) { category = strdup("ion;Deve"); } else if (strstr(fPath, "Editors")) { category = strdup("ion;Text"); } else if (strstr(fPath, "Games")) { category = strdup("ion;Game"); } else if (strstr(fPath, "Graphics")) { category = strdup("ion;Grap"); } else if (strstr(fPath, "Internet")) { category = strdup("ion;Netw"); } else if (strstr(fPath, "Root")) { category = strdup("ion;Core"); } else if (strstr(fPath, "Multimedia")) { category = strdup("ion;Audi"); } else if (strstr(fPath, "Office")) { category = strdup("ion;Offi"); } else if (strstr(fPath, "Settings")) { category = strdup("ion;Sett"); strcpy(dirname, "/usr/share/control-center-2.0/capplets/"); } else if (strstr(fPath, "System")) { category = strdup("ion;Syst"); } else { category = strdup("xyz"); } if (!strlen(dirname)) strcpy(dirname, "/usr/share/applications/"); DIR* dir = opendir(dirname); if (dir != 0) { struct dirent *file; while ((file = readdir(dir)) != NULL) { char fullpath[256]; strcpy(fullpath, dirname); strcat(fullpath, file->d_name); GnomeDesktopItem *ditem = gnome_desktop_item_new_from_file(fullpath, (GnomeDesktopItemLoadFlags)0, NULL); const char *categories = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_CATEGORIES); if (categories && strstr(categories, category)) { if (*file->d_name != '.') { if (strstr(fPath, "Settings")) { if (!strstr(categories, "ngs;Adva") && !strstr(categories, "ngs;Acce")) addEntry(dirname, file->d_name, strlen(dirname), false); } else { addEntry(dirname, file->d_name, strlen(dirname), false); } } } } if (strstr(fPath, "Settings")) { addEntry("/usr/share/gnome/vfolders/", "Accessibility.directory", strlen("/usr/share/gnome/vfolders/"), false); addEntry("/usr/share/gnome/vfolders/", "Advanced.directory", strlen("/usr/share/gnome/vfolders/"), false); } closedir(dir); } } } int makeMenu(const char *base_directory) { GnomeMenu *menu = new GnomeMenu(); menu->populateMenu(base_directory); dumpMenu(menu); return 0; } int runFile(const char *dentry_path) { char arg[32]; int i; GnomeDesktopItem *ditem = gnome_desktop_item_new_from_file(dentry_path, (GnomeDesktopItemLoadFlags)0, NULL); if (ditem == NULL) { return 1; } else { // FIXME: leads to segfault for some reason, so using execlp instead // gnome_desktop_item_launch(ditem, NULL, 0, NULL); const char *app = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_EXEC); for (i = 0; app[i] && app[i] != ' '; ++i) { arg[i] = app[i]; } arg[i] = '\0'; execlp(arg, arg, NULL); } return 0; } int main(int argc, char **argv) { gnome_vfs_init(); for (char ** arg = argv + 1; arg < argv + argc; ++arg) { if (**arg == '-') { char *path = 0; if (IS_SWITCH("h", "help")) break; if (GetLongArgument(path, "open", arg, argv+argc)) return runFile(path); else if (GetLongArgument(path, "list", arg, argv+argc)) return makeMenu(path); } } msg("Usage: %s [ --open PATH | --list PATH ]", argv[0]); } #endif <commit_msg>Fix stupid crash of gnome menu when an invalid folder was specified<commit_after>/* * IceWM * * Copyright (C) 1998-2003 Marko Macek & Nehal Mistry * * Changes: * * 2003/06/14 * * created gnome2 support from gnome.cc */ #include "config.h" #ifdef CONFIG_GNOME_MENUS #include "ylib.h" #include "default.h" #include "ypixbuf.h" #include "yapp.h" #include "sysdep.h" #include "base.h" #include <dirent.h> #include <string.h> #include <gnome.h> #include <libgnome/gnome-desktop-item.h> #include <libgnomevfs/gnome-vfs-init.h> #include "yarray.h" char const * ApplicationName = "icewm-menu-gnome2"; class GnomeMenu; class GnomeMenuItem { public: GnomeMenuItem() { title = 0; icon = 0; dentry = 0; submenu = 0; } const char *title; const char *icon; const char *dentry; GnomeMenu *submenu; }; class GnomeMenu { public: GnomeMenu() { } YObjectArray<GnomeMenuItem> items; bool isDuplicateName(const char *name); void addEntry(const char *fPath, const char *name, const int plen, const bool firstRun); void populateMenu(const char *fPath); }; void dumpMenu(GnomeMenu *menu) { for (int i = 0; i < menu->items.getCount(); i++) { GnomeMenuItem *item = menu->items.getItem(i); if (item->dentry && !item->submenu) { printf("prog \"%s\" %s icewm-menu-gnome2 --open \"%s\"\n", item->title, item->icon ? item->icon : "-", item->dentry); } else if (item->dentry && item->submenu) { printf("menuprog \"%s\" %s icewm-menu-gnome2 --list \"%s\"\n", item->title, item->icon ? item->icon : "-", (!strcmp(my_basename(item->dentry), ".directory") ? g_dirname(item->dentry) : item->dentry)); } } } bool GnomeMenu::isDuplicateName(const char *name) { for (int i = 0; i < items.getCount(); i++) { GnomeMenuItem *item = items.getItem(i); if (strcmp(name, item->title) == 0) return 1; } return 0; } void GnomeMenu::addEntry(const char *fPath, const char *name, const int plen, const bool firstRun) { const int nlen = (plen == 0 || fPath[plen - 1] != '/') ? plen + 1 + strlen(name) : plen + strlen(name); char *npath = new char[nlen + 1]; if (npath) { strcpy(npath, fPath); if (plen == 0 || npath[plen - 1] != '/') { npath[plen] = '/'; strcpy(npath + plen + 1, name); } else strcpy(npath + plen, name); GnomeMenuItem *item = new GnomeMenuItem(); item->title = name; GnomeDesktopItem *ditem = gnome_desktop_item_new_from_file(npath, (GnomeDesktopItemLoadFlags)0, NULL); struct stat sb; const char *type; bool isDir = (!stat(npath, &sb) && S_ISDIR(sb.st_mode)); type = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_TYPE); if (!isDir && type && strstr(type, "Directory")) { isDir = 1; } if (isDir) { GnomeMenu *submenu = new GnomeMenu(); item->title = g_path_get_basename(npath); item->icon = gnome_pixmap_file("gnome-folder.png"); item->submenu = submenu; char *epath = new char[nlen + sizeof("/.directory")]; strcpy(epath, npath); strcpy(epath + nlen, "/.directory"); if (stat(epath, &sb) == -1) { strcpy(epath, npath); } ditem = gnome_desktop_item_new_from_file(epath, (GnomeDesktopItemLoadFlags)0, NULL); if (ditem) { item->title = gnome_desktop_item_get_localestring(ditem, GNOME_DESKTOP_ITEM_NAME); //LXP FX item->icon = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON); } item->dentry = epath; } else { if (type && !strstr(type, "Directory")) { item->title = gnome_desktop_item_get_localestring(ditem, GNOME_DESKTOP_ITEM_NAME); if (gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON)) item->icon = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON); item->dentry = npath; } } if (firstRun || !isDuplicateName(item->title)) items.append(item); } } void GnomeMenu::populateMenu(const char *fPath) { struct stat sb; bool isDir = (!stat(fPath, &sb) && S_ISDIR(sb.st_mode)); const int plen = strlen(fPath); char tmp[256]; strcpy(tmp, fPath); strcat(tmp, "/.directory"); if (isDir && !stat(tmp, &sb)) { // looks like kde/gnome1 style char *opath = new char[plen + sizeof("/.order")]; if (opath) { strcpy(opath, fPath); strcpy(opath + plen, "/.order"); FILE * order(fopen(opath, "r")); if (order) { char oentry[100]; while (fgets(oentry, sizeof (oentry), order)) { const int oend = strlen(oentry) - 1; if (oend > 0 && oentry[oend] == '\n') oentry[oend] = '\0'; addEntry(fPath, oentry, plen, true); } fclose(order); } delete[] opath; } DIR *dir = opendir(fPath); if (dir != 0) { struct dirent *file; while ((file = readdir(dir)) != NULL) { if (*file->d_name != '.') addEntry(fPath, file->d_name, plen, false); } closedir(dir); } } else { // gnome2 style char *category = NULL; char dirname[256] = "a"; if (isDir) { strcpy(dirname, fPath); } else if (strstr(fPath, "Settings")) { strcpy(dirname, "/usr/share/control-center-2.0/capplets/"); } else if (strstr(fPath, "Advanced")) { strcpy(dirname, "/usr/share/control-center-2.0/capplets/"); } else { dirname[0] = '\0'; } if (isDir) { DIR *dir = opendir(dirname); if (dir != 0) { struct dirent *file; while ((file = readdir(dir)) != NULL) { if (!strcmp(dirname, fPath) && (strstr(file->d_name, "Accessibility") || strstr(file->d_name, "Advanced") || strstr(file->d_name, "Applications") || strstr(file->d_name, "Root") )) continue; if (*file->d_name != '.') addEntry(dirname, file->d_name, strlen(dirname), false); } closedir(dir); } } strcpy(dirname, "/usr/share/applications/"); if (isDir) { category = strdup("ion;Core"); } else if (strstr(fPath, "Applications")) { category = strdup("ion;Merg"); } else if (strstr(fPath, "Accessories")) { category = strdup("ion;Util"); } else if (strstr(fPath, "Advanced")) { category = strdup("ngs;Adva"); strcpy(dirname, "/usr/share/control-center-2.0/capplets/"); } else if (strstr(fPath, "Accessibility")) { category = strdup("ngs;Acce"); strcpy(dirname, "/usr/share/control-center-2.0/capplets/"); } else if (strstr(fPath, "Development")) { category = strdup("ion;Deve"); } else if (strstr(fPath, "Editors")) { category = strdup("ion;Text"); } else if (strstr(fPath, "Games")) { category = strdup("ion;Game"); } else if (strstr(fPath, "Graphics")) { category = strdup("ion;Grap"); } else if (strstr(fPath, "Internet")) { category = strdup("ion;Netw"); } else if (strstr(fPath, "Root")) { category = strdup("ion;Core"); } else if (strstr(fPath, "Multimedia")) { category = strdup("ion;Audi"); } else if (strstr(fPath, "Office")) { category = strdup("ion;Offi"); } else if (strstr(fPath, "Settings")) { category = strdup("ion;Sett"); strcpy(dirname, "/usr/share/control-center-2.0/capplets/"); } else if (strstr(fPath, "System")) { category = strdup("ion;Syst"); } else { category = strdup("xyz"); } if (!strlen(dirname)) strcpy(dirname, "/usr/share/applications/"); DIR* dir = opendir(dirname); if (dir != 0) { struct dirent *file; while ((file = readdir(dir)) != NULL) { char fullpath[256]; strcpy(fullpath, dirname); strcat(fullpath, file->d_name); GnomeDesktopItem *ditem = gnome_desktop_item_new_from_file(fullpath, (GnomeDesktopItemLoadFlags)0, NULL); const char *categories = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_CATEGORIES); if (categories && strstr(categories, category)) { if (*file->d_name != '.') { if (strstr(fPath, "Settings")) { if (!strstr(categories, "ngs;Adva") && !strstr(categories, "ngs;Acce")) addEntry(dirname, file->d_name, strlen(dirname), false); } else { addEntry(dirname, file->d_name, strlen(dirname), false); } } } } if (strstr(fPath, "Settings")) { addEntry("/usr/share/gnome/vfolders/", "Accessibility.directory", strlen("/usr/share/gnome/vfolders/"), false); addEntry("/usr/share/gnome/vfolders/", "Advanced.directory", strlen("/usr/share/gnome/vfolders/"), false); } closedir(dir); } } } int makeMenu(const char *base_directory) { GnomeMenu *menu = new GnomeMenu(); menu->populateMenu(base_directory); dumpMenu(menu); return 0; } int runFile(const char *dentry_path) { char arg[32]; int i; GnomeDesktopItem *ditem = gnome_desktop_item_new_from_file(dentry_path, (GnomeDesktopItemLoadFlags)0, NULL); if (ditem == NULL) { return 1; } else { // FIXME: leads to segfault for some reason, so using execlp instead // gnome_desktop_item_launch(ditem, NULL, 0, NULL); const char *app = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_EXEC); if(!app) return 1; for (i = 0; app[i] && app[i] != ' '; ++i) { arg[i] = app[i]; } arg[i] = '\0'; execlp(arg, arg, NULL); } return 0; } int main(int argc, char **argv) { gnome_vfs_init(); for (char ** arg = argv + 1; arg < argv + argc; ++arg) { if (**arg == '-') { char *path = 0; if (IS_SWITCH("h", "help")) break; if (GetLongArgument(path, "open", arg, argv+argc)) return runFile(path); else if (GetLongArgument(path, "list", arg, argv+argc)) return makeMenu(path); } } msg("Usage: %s [ --open PATH | --list PATH ]", argv[0]); } #endif <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <string> #include <vector> #include <cstdio> #include <cstring> #include <algorithm> #include <csignal> #include <misc/size.hpp> #include <signals.h> class Command { private: std::vector<std::string> args; public: Command(const char *cmdName) : args{cmdName} {} ~Command() = default; Command &addArg(const char *arg) { this->args.push_back(arg); return *this; } std::string operator()() const; }; static bool isSpace(char ch) { return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; } std::string Command::operator()() const { std::string cmd = this->args[0]; for(unsigned int i = 1; i < this->args.size(); i++) { cmd += " "; cmd += this->args[i]; } FILE *fp = popen(cmd.c_str(), "r"); std::string out; char buf[256]; for(int readSize; (readSize = fread(buf, sizeof(char), ydsh::arraySize(buf), fp)) > 0;) { out.append(buf, readSize); } pclose(fp); // remove last newline while(!out.empty() && isSpace(out.back())) { out.pop_back(); } return out; } static std::vector<std::string> split(const std::string &str) { std::vector<std::string> bufs; std::string buf; for(auto &ch : str) { if(ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') { bufs.push_back(std::move(buf)); buf = ""; } else { buf += ch; } } if(!buf.empty()) { bufs.push_back(std::move(buf)); } return bufs; } static void toUpperCase(std::string &str) { for(auto &ch : str) { if(ch >= 'a' && ch <= 'z') { ch -= static_cast<int>('a') - static_cast<int>('A'); // convert to upper character } } } static bool startsWith(const char *s1, const char *s2) { return s1 != nullptr && s2 != nullptr && strstr(s1, s2) == s1; } static bool exclude(const std::string &str) { const char *list[] = { "RT", "UNUSED", }; for(auto &e : list) { if(startsWith(str.c_str(), e)) { return true; } } return false; } static std::vector<std::string> toSignalList(const std::string &str) { auto values = split(str); for(auto iter = values.begin(); iter != values.end();) { toUpperCase(*iter); auto &e = *iter; if(e.empty() || !std::isalpha(e[0]) || exclude(e)) { iter = values.erase(iter); continue; } ++iter; } std::sort(values.begin(), values.end()); return values; } static std::vector<std::string> toList(const ydsh::SignalPair *pairs) { std::vector<std::string> values; for(; pairs->name; pairs++) { values.push_back(std::string(pairs->name)); } std::sort(values.begin(), values.end()); return values; } TEST(Signal, all) { std::string killPath = Command("which").addArg("kill")(); ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(killPath.size() > 0)); std::string killOut = Command(killPath.c_str()).addArg("-l")(); ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(killOut.size() > 0)); auto expected = toSignalList(killOut); auto actual = toList(ydsh::getSignalList()); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(expected.size(), actual.size())); unsigned int size = expected.size(); for(unsigned int i = 0; i < size; i++) { ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(expected[i], actual[i])); } } TEST(Signal, base) { using namespace ydsh; ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(SIGQUIT, getSignalNum("quit"))); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(SIGQUIT, getSignalNum("Sigquit"))); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(SIGTSTP, getSignalNum("tStP"))); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(SIGTSTP, getSignalNum("SigTStp"))); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(-1, getSignalNum("HOGED"))); ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("USR1", getSignalName(SIGUSR1))); ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("SEGV", getSignalName(SIGSEGV))); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(nullptr, getSignalName(-12))); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>fix signal api test case. not test non-standard signal<commit_after>#include <gtest/gtest.h> #include <string> #include <vector> #include <cstdio> #include <cstring> #include <algorithm> #include <csignal> #include <misc/size.hpp> #include <signals.h> class Command { private: std::vector<std::string> args; public: Command(const char *cmdName) : args{cmdName} {} ~Command() = default; Command &addArg(const char *arg) { this->args.push_back(arg); return *this; } std::string operator()() const; }; static bool isSpace(char ch) { return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; } std::string Command::operator()() const { std::string cmd = this->args[0]; for(unsigned int i = 1; i < this->args.size(); i++) { cmd += " "; cmd += this->args[i]; } FILE *fp = popen(cmd.c_str(), "r"); std::string out; char buf[256]; for(int readSize; (readSize = fread(buf, sizeof(char), ydsh::arraySize(buf), fp)) > 0;) { out.append(buf, readSize); } pclose(fp); // remove last newline while(!out.empty() && isSpace(out.back())) { out.pop_back(); } return out; } static std::vector<std::string> split(const std::string &str) { std::vector<std::string> bufs; std::string buf; for(auto &ch : str) { if(ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') { bufs.push_back(std::move(buf)); buf = ""; } else { buf += ch; } } if(!buf.empty()) { bufs.push_back(std::move(buf)); } return bufs; } static void toUpperCase(std::string &str) { for(auto &ch : str) { if(ch >= 'a' && ch <= 'z') { ch -= static_cast<int>('a') - static_cast<int>('A'); // convert to upper character } } } static bool startsWith(const char *s1, const char *s2) { return s1 != nullptr && s2 != nullptr && strstr(s1, s2) == s1; } static bool excludeRT(const std::string &str) { return startsWith(str.c_str(), "RT"); } static void trim(std::string &str) { if(startsWith(str.c_str(), "SIG")) { str = str.c_str() + 3; } } /** * exclude other signal (non-standard signal) and real time signal * */ struct SigFilter { bool operator()(const std::string &str) const { const char *v[] = { "IOT", "EMT", "STKFLT", "IO","CLD", "PWR", "INFO", "LOST", "WINCH", "UNUSED" }; for(auto &e : v) { if(str == e) { return true; } } return false; } }; static std::vector<std::string> toSignalList(const std::string &str) { auto values = split(str); for(auto iter = values.begin(); iter != values.end();) { toUpperCase(*iter); trim(*iter); auto &e = *iter; if(e.empty() || !std::isalpha(e[0]) || excludeRT(e)) { iter = values.erase(iter); continue; } ++iter; } std::sort(values.begin(), values.end()); values.erase(std::remove_if(values.begin(), values.end(), SigFilter()), values.end()); return values; } static std::vector<std::string> toList(const ydsh::SignalPair *pairs) { std::vector<std::string> values; for(; pairs->name; pairs++) { values.push_back(std::string(pairs->name)); } std::sort(values.begin(), values.end()); values.erase(std::remove_if(values.begin(), values.end(), SigFilter()), values.end()); return values; } TEST(Signal, all) { std::string killPath = Command("which").addArg("kill")(); ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(killPath.size() > 0)); std::string killOut = Command(killPath.c_str()).addArg("-l")(); ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(killOut.size() > 0)); auto expected = toSignalList(killOut); auto actual = toList(ydsh::getSignalList()); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(expected.size(), actual.size())); unsigned int size = expected.size(); for(unsigned int i = 0; i < size; i++) { ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(expected[i], actual[i])); } } TEST(Signal, base) { using namespace ydsh; ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(SIGQUIT, getSignalNum("quit"))); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(SIGQUIT, getSignalNum("Sigquit"))); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(SIGTSTP, getSignalNum("tStP"))); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(SIGTSTP, getSignalNum("SigTStp"))); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(-1, getSignalNum("HOGED"))); ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("USR1", getSignalName(SIGUSR1))); ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("SEGV", getSignalName(SIGSEGV))); ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(nullptr, getSignalName(-12))); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#undef NDEBUG //because we are using assert to check actual operations that cannot be skipped in release mode testing #include <cassert> #include <exodus/program.h> programinit() function main() { TRACE(osgetenv("PATH")) TRACE(osgetenv()) TRACE(oslist()) assert(osshellread("./testcommandline '(ab)'") eq "testcommandline (ab)\ntestcommandline\nab\n"); assert(osshellread("./testcommandline '{ab}'") eq "testcommandline {ab}\ntestcommandline\nab\n"); assert(osshellread("./testcommandline a b c '(ab)'") eq "testcommandline a b c (ab)\ntestcommandline^a^b^c\nab\n"); assert(osshellread("./testcommandline a b c '{ab}'") eq "testcommandline a b c {ab}\ntestcommandline^a^b^c\nab\n"); assert(osshellread("./testcommandline a b c '(a b)'").outputl() eq "testcommandline a b c (a b)\ntestcommandline^a^b^c\na b\n"); assert(osshellread("./testcommandline a b c '{a b}'").outputl() eq "testcommandline a b c {a b}\ntestcommandline^a^b^c\na b\n"); assert(osshellread("./testcommandline a b c '(' a or b ')'").outputl() eq "testcommandline a b c ( a or b )\ntestcommandline^a^b^c^(^a^or^b^)\n\n"); // Syntax error // assert(osshellread("./testcommandline a b c (a b)").outputl() eq "testcommandline a b c (a b)\ntestcommandline^a^b^c^(a^b)\n\n"); // assert(osshellread("./testcommandline a b c {a b}").outputl() eq "testcommandline a b c {a b}\ntestcommandline^a^b^c^{a^b}\n\n"); assert(osshellread("./testcommandline '(' a b ')'") eq "testcommandline ( a b )\ntestcommandline^(^a^b^)\n\n"); perform("testcommandlib a b c (xyz)"); TRACE(USER1) // TODO COMMAND should be parsed in libexodus (exoprog.cpp) in FM separated parts as is done for COMMAND from the command line //assert(USER1 eq "testcommandlib a b c (xyz)\ntestcommandlib^a^b^c\nxyz\n"); assert(USER1 eq "testcommandlib a b c (xyz)\ntestcommandlib a b c\nxyz\n"); printl(elapsedtimetext()); printl("Test passed"); return 0; } programexit() <commit_msg>GITHUB test build calling other test programs<commit_after>#undef NDEBUG //because we are using assert to check actual operations that cannot be skipped in release mode testing #include <cassert> #include <exodus/program.h> programinit() function main() { TRACE(osgetenv("PATH")) TRACE(osgetenv()) TRACE(oslist()) TRACE(EXECPATH) var execdir = EXECPATH.field(OSSLASH, 1, fcount(EXECPATH, OSSLASH) - 1); assert(osshellread(execdir ^ "/testcommandline '(ab)'") eq "testcommandline (ab)\ntestcommandline\nab\n"); assert(osshellread(execdir ^ "/testcommandline '{ab}'") eq "testcommandline {ab}\ntestcommandline\nab\n"); assert(osshellread(execdir ^ "/testcommandline a b c '(ab)'") eq "testcommandline a b c (ab)\ntestcommandline^a^b^c\nab\n"); assert(osshellread(execdir ^ "/testcommandline a b c '{ab}'") eq "testcommandline a b c {ab}\ntestcommandline^a^b^c\nab\n"); assert(osshellread(execdir ^ "/testcommandline a b c '(a b)'").outputl() eq "testcommandline a b c (a b)\ntestcommandline^a^b^c\na b\n"); assert(osshellread(execdir ^ "/testcommandline a b c '{a b}'").outputl() eq "testcommandline a b c {a b}\ntestcommandline^a^b^c\na b\n"); assert(osshellread(execdir ^ "/testcommandline a b c '(' a or b ')'").outputl() eq "testcommandline a b c ( a or b )\ntestcommandline^a^b^c^(^a^or^b^)\n\n"); // Syntax error // assert(osshellread(execdir ^ "/testcommandline a b c (a b)").outputl() eq "testcommandline a b c (a b)\ntestcommandline^a^b^c^(a^b)\n\n"); // assert(osshellread(execdir ^ "/testcommandline a b c {a b}").outputl() eq "testcommandline a b c {a b}\ntestcommandline^a^b^c^{a^b}\n\n"); assert(osshellread(execdir ^ "/testcommandline '(' a b ')'") eq "testcommandline ( a b )\ntestcommandline^(^a^b^)\n\n"); if (libinfo("testcommandlib")) { perform("testcommandlib a b c (xyz)"); TRACE(USER1) // TODO COMMAND should be parsed in libexodus (exoprog.cpp) in FM separated parts as is done for COMMAND from the command line //assert(USER1 eq "testcommandlib a b c (xyz)\ntestcommandlib^a^b^c\nxyz\n"); assert(USER1 eq "testcommandlib a b c (xyz)\ntestcommandlib a b c\nxyz\n"); } printl(elapsedtimetext()); printl("Test passed"); return 0; } programexit() <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The Backplane Incorporated, * Vinay Hiremath * * 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 <string> #include <vector> #include "include/grunt.h" std::string Grunt::makeGrepQuery( std::string query, std::string path, std::vector<std::string> extensions, unsigned int max_results ) { std::string resultQuery = std::string("grep"); // grep flags resultQuery += std::string(" -ir"); resultQuery += std::string(" ") + query; resultQuery += std::string(" ") + path; return resultQuery; } <commit_msg>Extensions in Query for Grunt<commit_after>/* * Copyright (c) 2012 The Backplane Incorporated, * Vinay Hiremath * * 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 <string> #include <vector> #include "include/grunt.h" std::string Grunt::makeGrepQuery( std::string query, std::string path, std::vector<std::string> extensions, unsigned int max_results ) { std::string resultQuery = std::string("grep"); // grep flags // TODO: make them passable from the command line resultQuery += std::string(" -ir"); std::string extensionsQuery(""); for (unsigned int i = 0; i < extensions.size(); i++) { if (extensions[i].compare("*")) { extensionsQuery += std::string(" --include *."); extensionsQuery += extensions[i]; } else { extensionsQuery = std::string(""); break; } } resultQuery += extensionsQuery; resultQuery += std::string(" ") + query; resultQuery += std::string(" ") + path; return resultQuery; } <|endoftext|>
<commit_before>#include"all_defines.hpp" #include"objects.hpp" #include"heaps.hpp" #include"types.hpp" #include<cstdlib> #include<stdint.h> /*----------------------------------------------------------------------------- Semispaces -----------------------------------------------------------------------------*/ Semispace::Semispace(size_t nsz) : max(nsz) { mem = std::malloc(nsz); if(!mem) throw std::bad_alloc(); allocpt = mem; // check alignment intptr_t tmp = reinterpret_cast<intptr_t>(allocpt); if(tmp & Object::tag_mask) { char* callocpt = (char*)allocpt; callocpt += Object::alignment - (tmp & Object::tag_mask); allocpt = callocpt; } allocstart = allocpt; char* cmem = (char*)mem; char* clifoallocpt = cmem + nsz; // adjust for alignment tmp = reinterpret_cast<intptr_t>(lifoallocpt); clifoallocpt -= (tmp & Object::tag_mask); lifoallocpt = clifoallocpt; } Semispace::~Semispace() { Generic* gp; size_t step; char* mvpt; char* endpt; /*TODO: consider refactoring*/ /*----Delete normally-allocated memory----*/ mvpt = (char*) allocstart; endpt = (char*) allocpt; while(mvpt < endpt) { gp = (Generic*)(void*) mvpt; step = gp->real_size(); gp->~Generic(); mvpt += step; } /*----Delete lifo-allocated memory----*/ mvpt = (char*) lifoallocpt; endpt = (char*) lifoallocstart; while(mvpt < endpt) { gp = (Generic*)(void*) mvpt; step = gp->real_size(); gp->~Generic(); mvpt += step; } } /* sz must be computed using the exact same computation used in real_size() of the object to be allocated. This includes alignment. */ void* Semispace::alloc(size_t sz) { prev_alloc = sz; void* tmp = allocpt; char* callocpt = (char*) allocpt; callocpt += sz; allocpt = callocpt; return tmp; } /*should be used only for most recent allocation (i.e. should be used for freeing memory when the constructor throws.) */ void Semispace::dealloc(void* pt) { #ifdef DEBUG char* callocpt = allocpt; callocpt -= prev_alloc; if(callocpt != pt) throw_DeallocError(pt); #endif allocpt = pt; } void* Semispace::lifo_alloc(size_t sz) { prevalloc = sz; char* clifoallocpt = lifoallocpt; clifoallocpt -= sz; lifoallocpt = clifoallocpt; return lifoallocpt; } void Semispace::lifo_dealloc(void* pt) { /*if we can't deallocate, just ignore*/ if(pt != lifoallocpt) return; size_t sz = ((Generic*) pt)->real_size(); ((Generic*) pt)->~Generic(); char* clifoallocpt = pt; clifoallocpt += sz; lifoallocpt = clifoallocpt; } /*This function should be used only when the constructor for the object fails. It does *not* properly destroy the object. */ void Semispace::lifo_dealloc_abort(void* pt) { #ifdef DEBUG if(pt != lifoallocpt) throw_DeallocError(pt); #endif char* clifoallocpt = lifoallocpt; clifoallocpt += prev_alloc; lifoallocpt = clifoallocpt; } /*TODO*/ void Semispace::clone(boost::scoped_ptr<Semispace>& sp, Generic*& g); /*----------------------------------------------------------------------------- Heaps -----------------------------------------------------------------------------*/ /*copy and modify GC class*/ class GCTraverser : public GenericTraverser { Semispace* nsp; public: explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { } void traverse(Object::ref& r) { if(is_a<Generic*>(r)) { Generic* gp = as_a<Generic*>(r); BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp); if(bp) { //broken heart r = Object::to_ref(bp->to); } else { //unbroken Generic* ngp = gp->clone(nsp); gp->break_heart(ngp); r = Object::to_ref(ngp); } } else return; } }; static void cheney_collection(Semispace* nsp) { GCTraverser gc(nsp); /*step 1: initial traverse*/ scan_root_object(gc); /*step 2: non-root traverse*/ /*notice that we traverse the new semispace this is a two-pointer Cheney collector, with mvpt being one pointer and nsp->allocpt the other one */ char* mvpt = nsp->allocstart; while(mvpt < ((char*) nsp->allocpt)) { Generic* gp = (Generic*)(void*) mvpt; size_t obsz = gp->real_size(); gp->traverse_references(gc); mvpt += obsz; } } void Heap::GC(size_t insurance) { /*Determine the sizes of all semispaces*/ size_t total = main->used() + insurance + (other_spaces) ? other_spaces->used_total() : /*otherwise*/ 0 ; if(tight) total *= 2; /*get a new Semispace*/ boost::scoped_ptr<Semispace> nsp(new Semispace(total)); /*traverse*/ cheney_collection(&*nsp); /*replace*/ main.swap(nsp); nsp.reset(); other_spaces.reset(); /*determine if resizing is appropriate*/ if(main->used() + insurance <= total / 4) { /*semispace a bit large... make it smaller*/ nsp.reset(new Semispace(total / 2)); cheney_collection(&*nsp); main.swap(nsp); nsp.reset(); } else if(main->used() + insurance >= (total / 4) * 3) { tight = 1; } } <commit_msg>src/heaps.cpp: Corrected spelling of prev_alloc<commit_after>#include"all_defines.hpp" #include"objects.hpp" #include"heaps.hpp" #include"types.hpp" #include<cstdlib> #include<stdint.h> /*----------------------------------------------------------------------------- Semispaces -----------------------------------------------------------------------------*/ Semispace::Semispace(size_t nsz) : max(nsz) { mem = std::malloc(nsz); if(!mem) throw std::bad_alloc(); allocpt = mem; // check alignment intptr_t tmp = reinterpret_cast<intptr_t>(allocpt); if(tmp & Object::tag_mask) { char* callocpt = (char*)allocpt; callocpt += Object::alignment - (tmp & Object::tag_mask); allocpt = callocpt; } allocstart = allocpt; char* cmem = (char*)mem; char* clifoallocpt = cmem + nsz; // adjust for alignment tmp = reinterpret_cast<intptr_t>(lifoallocpt); clifoallocpt -= (tmp & Object::tag_mask); lifoallocpt = clifoallocpt; } Semispace::~Semispace() { Generic* gp; size_t step; char* mvpt; char* endpt; /*TODO: consider refactoring*/ /*----Delete normally-allocated memory----*/ mvpt = (char*) allocstart; endpt = (char*) allocpt; while(mvpt < endpt) { gp = (Generic*)(void*) mvpt; step = gp->real_size(); gp->~Generic(); mvpt += step; } /*----Delete lifo-allocated memory----*/ mvpt = (char*) lifoallocpt; endpt = (char*) lifoallocstart; while(mvpt < endpt) { gp = (Generic*)(void*) mvpt; step = gp->real_size(); gp->~Generic(); mvpt += step; } } /* sz must be computed using the exact same computation used in real_size() of the object to be allocated. This includes alignment. */ void* Semispace::alloc(size_t sz) { prev_alloc = sz; void* tmp = allocpt; char* callocpt = (char*) allocpt; callocpt += sz; allocpt = callocpt; return tmp; } /*should be used only for most recent allocation (i.e. should be used for freeing memory when the constructor throws.) */ void Semispace::dealloc(void* pt) { #ifdef DEBUG char* callocpt = allocpt; callocpt -= prev_alloc; if(callocpt != pt) throw_DeallocError(pt); #endif allocpt = pt; } void* Semispace::lifo_alloc(size_t sz) { prev_alloc = sz; char* clifoallocpt = lifoallocpt; clifoallocpt -= sz; lifoallocpt = clifoallocpt; return lifoallocpt; } void Semispace::lifo_dealloc(void* pt) { /*if we can't deallocate, just ignore*/ if(pt != lifoallocpt) return; size_t sz = ((Generic*) pt)->real_size(); ((Generic*) pt)->~Generic(); char* clifoallocpt = pt; clifoallocpt += sz; lifoallocpt = clifoallocpt; } /*This function should be used only when the constructor for the object fails. It does *not* properly destroy the object. */ void Semispace::lifo_dealloc_abort(void* pt) { #ifdef DEBUG if(pt != lifoallocpt) throw_DeallocError(pt); #endif char* clifoallocpt = lifoallocpt; clifoallocpt += prev_alloc; lifoallocpt = clifoallocpt; } /*TODO*/ void Semispace::clone(boost::scoped_ptr<Semispace>& sp, Generic*& g); /*----------------------------------------------------------------------------- Heaps -----------------------------------------------------------------------------*/ /*copy and modify GC class*/ class GCTraverser : public GenericTraverser { Semispace* nsp; public: explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { } void traverse(Object::ref& r) { if(is_a<Generic*>(r)) { Generic* gp = as_a<Generic*>(r); BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp); if(bp) { //broken heart r = Object::to_ref(bp->to); } else { //unbroken Generic* ngp = gp->clone(nsp); gp->break_heart(ngp); r = Object::to_ref(ngp); } } else return; } }; static void cheney_collection(Semispace* nsp) { GCTraverser gc(nsp); /*step 1: initial traverse*/ scan_root_object(gc); /*step 2: non-root traverse*/ /*notice that we traverse the new semispace this is a two-pointer Cheney collector, with mvpt being one pointer and nsp->allocpt the other one */ char* mvpt = nsp->allocstart; while(mvpt < ((char*) nsp->allocpt)) { Generic* gp = (Generic*)(void*) mvpt; size_t obsz = gp->real_size(); gp->traverse_references(gc); mvpt += obsz; } } void Heap::GC(size_t insurance) { /*Determine the sizes of all semispaces*/ size_t total = main->used() + insurance + (other_spaces) ? other_spaces->used_total() : /*otherwise*/ 0 ; if(tight) total *= 2; /*get a new Semispace*/ boost::scoped_ptr<Semispace> nsp(new Semispace(total)); /*traverse*/ cheney_collection(&*nsp); /*replace*/ main.swap(nsp); nsp.reset(); other_spaces.reset(); /*determine if resizing is appropriate*/ if(main->used() + insurance <= total / 4) { /*semispace a bit large... make it smaller*/ nsp.reset(new Semispace(total / 2)); cheney_collection(&*nsp); main.swap(nsp); nsp.reset(); } else if(main->used() + insurance >= (total / 4) * 3) { tight = 1; } } <|endoftext|>
<commit_before>#include"all_defines.hpp" #include"objects.hpp" #include"heaps.hpp" #include"types.hpp" #include<cstdlib> #include<stdint.h> /*----------------------------------------------------------------------------- Semispaces -----------------------------------------------------------------------------*/ Semispace::Semispace(size_t nsz) : max(nsz) { mem = std::malloc(nsz); if(!mem) throw std::bad_alloc(); allocpt = mem; // check alignment intptr_t tmp = reinterpret_cast<intptr_t>(allocpt); if(tmp & Object::tag_mask) { char* callocpt = allocpt; callocpt += Object::alignment - (tmp & Object::tag_mask); allocpt = callocpt; } char* cmem = mem; char* clifoallocpt = cmem + nsz; // adjust for alignment tmp = reinterpret_cast<intptr_t>(lifoallocpt); clifoallocpt -= (tmp & Object::tag_mask); lifoallocpt = clifoallocpt; } Semispace::~Semispace() { Generic* gp; size_t step; char* mvpt; char* endpt; /*----Delete normally-allocated memory----*/ mvpt = mem; intptr_t tmp = reinterpret_cast<intptr_t>(mem); if(tmp & Object::tag_mask) { char* cmem = mem; cmem += Object::alignment - (tmp & Object::tag_mask); mvpt = cmem; } endpt = allocpt; while(mvpt < allocpt) { gp = (Generic*)(void*) mvpt; step = gp->real_size(); gp->~Generic(); mvpt += step; } /*----Delete lifo-allocated memory----*/ mvpt = lifoallocpt; endpt = mem; endpt += sz; intptr_t tmp = reinterpret_cast<intptr_t>(endpt); endpt -= (tmp & Object::tag_mask); while(mvpt < allocpt) { gp = (Generic*)(void*) mvpt; step = gp->real_size(); gp->~Generic(); mvpt += step; } } <commit_msg>src/heaps.cpp: Added alloc()/dealloc() implementation<commit_after>#include"all_defines.hpp" #include"objects.hpp" #include"heaps.hpp" #include"types.hpp" #include<cstdlib> #include<stdint.h> /*----------------------------------------------------------------------------- Semispaces -----------------------------------------------------------------------------*/ Semispace::Semispace(size_t nsz) : max(nsz) { mem = std::malloc(nsz); if(!mem) throw std::bad_alloc(); allocpt = mem; // check alignment intptr_t tmp = reinterpret_cast<intptr_t>(allocpt); if(tmp & Object::tag_mask) { char* callocpt = allocpt; callocpt += Object::alignment - (tmp & Object::tag_mask); allocpt = callocpt; } char* cmem = mem; char* clifoallocpt = cmem + nsz; // adjust for alignment tmp = reinterpret_cast<intptr_t>(lifoallocpt); clifoallocpt -= (tmp & Object::tag_mask); lifoallocpt = clifoallocpt; } Semispace::~Semispace() { Generic* gp; size_t step; char* mvpt; char* endpt; /*----Delete normally-allocated memory----*/ mvpt = mem; intptr_t tmp = reinterpret_cast<intptr_t>(mem); if(tmp & Object::tag_mask) { char* cmem = mem; cmem += Object::alignment - (tmp & Object::tag_mask); mvpt = cmem; } endpt = allocpt; while(mvpt < allocpt) { gp = (Generic*)(void*) mvpt; step = gp->real_size(); gp->~Generic(); mvpt += step; } /*----Delete lifo-allocated memory----*/ mvpt = lifoallocpt; endpt = mem; endpt += sz; intptr_t tmp = reinterpret_cast<intptr_t>(endpt); endpt -= (tmp & Object::tag_mask); while(mvpt < allocpt) { gp = (Generic*)(void*) mvpt; step = gp->real_size(); gp->~Generic(); mvpt += step; } } /* sz must be computed using the exact same computation used in real_size() of the object to be allocated. */ void* Semispace::alloc(size_t sz) { prev_alloc = sz; void* tmp = allocpt; char* callocpt = allocpt; callocpt += sz; allocpt = callocpt; return tmp; } /*should be used only for most recent allocation*/ void Semispace::dealloc(void* pt) { #ifdef DEBUG char* callocpt = allocpt; callocpt -= prev_alloc; if(callocpt != pt) throw_DeallocError(pt); #endif allocpt = pt; } <|endoftext|>
<commit_before>/******************************************************************************* Copyright (c) 2014, Jan Koester jan.koester@gmx.net All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include <cstring> #include <cstdlib> #include "os/os.h" #include "utils.h" #include "httpd.h" #define KTKEY 0 #define KTSKEY 1 libhttppp::HTTPDCmd::HTTPDCmd() { _Key = NULL; _SKey = '\0'; _Value = NULL; _Help = NULL; _Found = false; _Required = false; _nextHTTPDCmd = NULL; } const char *libhttppp::HTTPDCmd::getKey() { return _Key; } const char libhttppp::HTTPDCmd::getShortkey() { return _SKey; } const char *libhttppp::HTTPDCmd::getValue() { return _Value; } size_t libhttppp::HTTPDCmd::getValueSize_t() { return atoi(_Value); } int libhttppp::HTTPDCmd::getValueInt() { return atoi(_Value); } const char *libhttppp::HTTPDCmd::getHelp() { return _Help; } bool libhttppp::HTTPDCmd::getFound() { return _Found; } bool libhttppp::HTTPDCmd::getRequired() { return _Required; } libhttppp::HTTPDCmd *libhttppp::HTTPDCmd::nextHTTPDCmd() { return _nextHTTPDCmd; } libhttppp::HTTPDCmd::~HTTPDCmd() { delete[] _Key; delete[] _Value; delete[] _Help; delete _nextHTTPDCmd; } libhttppp::HTTPDCmdController::HTTPDCmdController() { _firstHTTPDCmd = NULL; _lastHTTPDCmd = NULL; } void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey,bool required, const char *defaultvalue, const char *help) { if (!key || !skey || !help) { _httpexception[HTTPException::Critical] << "cmd parser key,skey or help not set!"; throw _httpexception; } /*if key exist overwriting options*/ for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd=curhttpdcmd->nextHTTPDCmd()) { if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) { /*set new shortkey*/ curhttpdcmd->_SKey = skey; /*set reqirement flag*/ curhttpdcmd->_Required = required; /*set new value*/ delete[] curhttpdcmd->_Value; curhttpdcmd->_Value = new char[getlen(defaultvalue)+1]; scopy(defaultvalue, defaultvalue+getlen(defaultvalue),curhttpdcmd->_Value); curhttpdcmd->_Value[getlen(defaultvalue)] = '\0'; /*set new help*/ delete[] curhttpdcmd->_Help; curhttpdcmd->_Help = new char[getlen(help) + 1]; scopy(help, help + getlen(help), curhttpdcmd->_Help); curhttpdcmd->_Help[getlen(help)] = '\0'; return; } } /*create new key value store*/ if (!_firstHTTPDCmd) { _firstHTTPDCmd = new HTTPDCmd; _lastHTTPDCmd = _firstHTTPDCmd; } else { _lastHTTPDCmd->_nextHTTPDCmd = new HTTPDCmd; _lastHTTPDCmd = _lastHTTPDCmd->_nextHTTPDCmd; } /*set new key*/ _lastHTTPDCmd->_Key = new char[getlen(key) + 1]; scopy(key,key+getlen(key),_lastHTTPDCmd->_Key); _lastHTTPDCmd->_Key[getlen(key)] = '\0'; /*set new shortkey*/ _lastHTTPDCmd->_SKey = skey; /*set reqirement flag*/ _lastHTTPDCmd->_Required = required; /*set new value*/ if (defaultvalue) { _lastHTTPDCmd->_Value = new char[getlen(defaultvalue) + 1]; scopy(defaultvalue, defaultvalue + getlen(defaultvalue), _lastHTTPDCmd->_Value); _lastHTTPDCmd->_Value[getlen(defaultvalue)] = '\0'; } /*set new help*/ _lastHTTPDCmd->_Help = new char[getlen(help) + 1]; scopy(help, help + getlen(help), _lastHTTPDCmd->_Help); _lastHTTPDCmd->_Help[getlen(help)] = '\0'; } void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, size_t defaultvalue, const char *help) { char buf[sizeof(size_t)]; itoa(defaultvalue,buf); registerCmd(key,skey,required,buf,help); } void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, int defaultvalue, const char *help) { char buf[sizeof(size_t)]; itoa(defaultvalue,buf); registerCmd(key, skey, required, buf, help); } void libhttppp::HTTPDCmdController::parseCmd(int argc, char** argv){ for (int args = 1; args < argc; args++) { int keytype = -1; if (argv[args][0]=='-' && argv[args][1] == '-') { keytype = KTKEY; }else if (argv[args][0] == '-'){ keytype = KTSKEY; }else { break; } size_t kendpos = getlen(argv[args]); for (size_t cmdpos = 0; cmdpos < getlen(argv[args])+1; cmdpos++) { switch (argv[args][cmdpos]) { case '=': { kendpos = cmdpos; }; } } char *key = NULL; char skey = '0'; if (keytype == KTKEY) { key = new char[kendpos-1]; scopy(argv[args] +2, argv[args] +kendpos, key); key[kendpos - 2] = '\0'; } else if (keytype == KTSKEY){ skey = argv[args][1]; } for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) { if (keytype == KTKEY) { if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) { curhttpdcmd->_Found = true; int valuesize = (getlen(argv[args]) - (kendpos+1)); if (valuesize > 0) { delete[] curhttpdcmd->_Value; curhttpdcmd->_Value = new char[valuesize+1]; scopy(argv[args]+(kendpos+1), argv[args] + getlen(argv[args]),curhttpdcmd->_Value); curhttpdcmd->_Value[valuesize] = '\0'; } } } else if (keytype == KTSKEY) { if (curhttpdcmd->getShortkey()== skey) { curhttpdcmd->_Found = true; int valuesize = (getlen(argv[args]) - (kendpos + 1)); if (valuesize > 0) { delete[] curhttpdcmd->_Value; curhttpdcmd->_Value = new char[valuesize + 1]; scopy(argv[args] + (kendpos + 1), argv[args] + getlen(argv[args]), curhttpdcmd->_Value); curhttpdcmd->_Value[valuesize] = '\0'; } } } } delete[] key; } } bool libhttppp::HTTPDCmdController::checkRequired() { for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) { if (curhttpdcmd->getRequired() && !curhttpdcmd->_Found) { return false; } } return true; } void libhttppp::HTTPDCmdController::printHelp() { for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) { Console con; con << "--" << curhttpdcmd->getKey() << "-" << curhttpdcmd->getShortkey() << curhttpdcmd->getHelp() << Console::endl; } } libhttppp::HTTPDCmd *libhttppp::HTTPDCmdController::getHTTPDCmdbyKey(const char *key) { for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) { if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) { return curhttpdcmd; } } return NULL; } libhttppp::HTTPDCmdController::~HTTPDCmdController() { delete _firstHTTPDCmd; _lastHTTPDCmd = NULL; } libhttppp::HttpD::HttpD(int argc, char** argv){ CmdController= new HTTPDCmdController; /*Register Parameters*/ CmdController->registerCmd("help", 'h', false, (const char*) NULL, "Helpmenu"); CmdController->registerCmd("httpaddr",'a', true,(const char*) NULL,"Address to listen"); CmdController->registerCmd("httpport", 'p', false, 8080, "Port to listen"); CmdController->registerCmd("maxconnections", 'm',false, MAXDEFAULTCONN, "Max connections that can connect"); CmdController->registerCmd("httpscert", 'c',false,(const char*) NULL, "HTTPS Certfile"); CmdController->registerCmd("httpskey", 'k',false, (const char*) NULL, "HTTPS Keyfile"); /*Parse Parameters*/ CmdController->parseCmd(argc,argv); if (!CmdController->checkRequired()) { CmdController->printHelp(); _httpexception[HTTPException::Critical] << "cmd parser not enough arguments given"; throw _httpexception; } if (CmdController->getHTTPDCmdbyKey("help") && CmdController->getHTTPDCmdbyKey("help")->getFound()) { CmdController->printHelp(); return; } /*get port from console paramter*/ int port = 0; bool portset=false; if(CmdController->getHTTPDCmdbyKey("httpport")){ port = CmdController->getHTTPDCmdbyKey("httpport")->getValueInt(); portset = CmdController->getHTTPDCmdbyKey("httpport")->getFound(); } /*get httpaddress from console paramter*/ const char *httpaddr = NULL; if (CmdController->getHTTPDCmdbyKey("httpaddr")) httpaddr = CmdController->getHTTPDCmdbyKey("httpaddr")->getValue(); /*get max connections from console paramter*/ int maxconnections = 0; if (CmdController->getHTTPDCmdbyKey("maxconnections")) maxconnections = CmdController->getHTTPDCmdbyKey("maxconnections")->getValueInt(); /*get httpaddress from console paramter*/ const char *sslcertpath = NULL; if (CmdController->getHTTPDCmdbyKey("httpscert")) sslcertpath = CmdController->getHTTPDCmdbyKey("httpscert")->getValue(); /*get httpaddress from console paramter*/ const char *sslkeypath = NULL; if (CmdController->getHTTPDCmdbyKey("httpskey")) sslkeypath = CmdController->getHTTPDCmdbyKey("httpskey")->getValue(); try { #ifndef Windows if (portset == true) _ServerSocket = new ServerSocket(httpaddr, port, maxconnections); else _ServerSocket = new ServerSocket(httpaddr, maxconnections); #else _ServerSocket = new ServerSocket(httpaddr, port, maxconnections); #endif if (!_ServerSocket) { throw _httpexception; } if (sslcertpath && sslkeypath) { _ServerSocket->createContext(); _ServerSocket->loadCertfile(sslcertpath); _ServerSocket->loadKeyfile(sslkeypath); } }catch (HTTPException &e) { } } libhttppp::ServerSocket *libhttppp::HttpD::getServerSocket(){ return _ServerSocket; } libhttppp::HttpD::~HttpD(){ delete _ServerSocket; delete CmdController; } <commit_msg>fixed 32bit fail in cmd parser<commit_after>/******************************************************************************* Copyright (c) 2014, Jan Koester jan.koester@gmx.net All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include <cstring> #include <cstdlib> #include "os/os.h" #include "utils.h" #include "httpd.h" #define KTKEY 0 #define KTSKEY 1 libhttppp::HTTPDCmd::HTTPDCmd() { _Key = NULL; _SKey = '\0'; _Value = NULL; _Help = NULL; _Found = false; _Required = false; _nextHTTPDCmd = NULL; } const char *libhttppp::HTTPDCmd::getKey() { return _Key; } const char libhttppp::HTTPDCmd::getShortkey() { return _SKey; } const char *libhttppp::HTTPDCmd::getValue() { return _Value; } size_t libhttppp::HTTPDCmd::getValueSize_t() { return atoi(_Value); } int libhttppp::HTTPDCmd::getValueInt() { return atoi(_Value); } const char *libhttppp::HTTPDCmd::getHelp() { return _Help; } bool libhttppp::HTTPDCmd::getFound() { return _Found; } bool libhttppp::HTTPDCmd::getRequired() { return _Required; } libhttppp::HTTPDCmd *libhttppp::HTTPDCmd::nextHTTPDCmd() { return _nextHTTPDCmd; } libhttppp::HTTPDCmd::~HTTPDCmd() { delete[] _Key; delete[] _Value; delete[] _Help; delete _nextHTTPDCmd; } libhttppp::HTTPDCmdController::HTTPDCmdController() { _firstHTTPDCmd = NULL; _lastHTTPDCmd = NULL; } void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey,bool required, const char *defaultvalue, const char *help) { if (!key || !skey || !help) { _httpexception[HTTPException::Critical] << "cmd parser key,skey or help not set!"; throw _httpexception; } /*if key exist overwriting options*/ for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd=curhttpdcmd->nextHTTPDCmd()) { if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) { /*set new shortkey*/ curhttpdcmd->_SKey = skey; /*set reqirement flag*/ curhttpdcmd->_Required = required; /*set new value*/ delete[] curhttpdcmd->_Value; curhttpdcmd->_Value = new char[getlen(defaultvalue)+1]; scopy(defaultvalue, defaultvalue+getlen(defaultvalue),curhttpdcmd->_Value); curhttpdcmd->_Value[getlen(defaultvalue)] = '\0'; /*set new help*/ delete[] curhttpdcmd->_Help; curhttpdcmd->_Help = new char[getlen(help) + 1]; scopy(help, help + getlen(help), curhttpdcmd->_Help); curhttpdcmd->_Help[getlen(help)] = '\0'; return; } } /*create new key value store*/ if (!_firstHTTPDCmd) { _firstHTTPDCmd = new HTTPDCmd; _lastHTTPDCmd = _firstHTTPDCmd; } else { _lastHTTPDCmd->_nextHTTPDCmd = new HTTPDCmd; _lastHTTPDCmd = _lastHTTPDCmd->_nextHTTPDCmd; } /*set new key*/ _lastHTTPDCmd->_Key = new char[getlen(key) + 1]; scopy(key,key+getlen(key),_lastHTTPDCmd->_Key); _lastHTTPDCmd->_Key[getlen(key)] = '\0'; /*set new shortkey*/ _lastHTTPDCmd->_SKey = skey; /*set reqirement flag*/ _lastHTTPDCmd->_Required = required; /*set new value*/ if (defaultvalue) { _lastHTTPDCmd->_Value = new char[getlen(defaultvalue) + 1]; scopy(defaultvalue, defaultvalue + getlen(defaultvalue), _lastHTTPDCmd->_Value); _lastHTTPDCmd->_Value[getlen(defaultvalue)] = '\0'; } /*set new help*/ _lastHTTPDCmd->_Help = new char[getlen(help) + 1]; scopy(help, help + getlen(help), _lastHTTPDCmd->_Help); _lastHTTPDCmd->_Help[getlen(help)] = '\0'; } void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, size_t defaultvalue, const char *help) { char buf[255]; itoa(defaultvalue,buf); registerCmd(key,skey,required,buf,help); } void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, int defaultvalue, const char *help) { char buf[255]; itoa(defaultvalue,buf); registerCmd(key, skey, required, buf, help); } void libhttppp::HTTPDCmdController::parseCmd(int argc, char** argv){ for (int args = 1; args < argc; args++) { int keytype = -1; if (argv[args][0]=='-' && argv[args][1] == '-') { keytype = KTKEY; }else if (argv[args][0] == '-'){ keytype = KTSKEY; }else { break; } size_t kendpos = getlen(argv[args]); for (size_t cmdpos = 0; cmdpos < getlen(argv[args])+1; cmdpos++) { switch (argv[args][cmdpos]) { case '=': { kendpos = cmdpos; }; } } char *key = NULL; char skey = '0'; if (keytype == KTKEY) { key = new char[kendpos-1]; scopy(argv[args] +2, argv[args] +kendpos, key); key[kendpos - 2] = '\0'; } else if (keytype == KTSKEY){ skey = argv[args][1]; } for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) { if (keytype == KTKEY) { if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) { curhttpdcmd->_Found = true; int valuesize = (getlen(argv[args]) - (kendpos+1)); if (valuesize > 0) { delete[] curhttpdcmd->_Value; curhttpdcmd->_Value = new char[valuesize+1]; scopy(argv[args]+(kendpos+1), argv[args] + getlen(argv[args]),curhttpdcmd->_Value); curhttpdcmd->_Value[valuesize] = '\0'; } } } else if (keytype == KTSKEY) { if (curhttpdcmd->getShortkey()== skey) { curhttpdcmd->_Found = true; int valuesize = (getlen(argv[args]) - (kendpos + 1)); if (valuesize > 0) { delete[] curhttpdcmd->_Value; curhttpdcmd->_Value = new char[valuesize + 1]; scopy(argv[args] + (kendpos + 1), argv[args] + getlen(argv[args]), curhttpdcmd->_Value); curhttpdcmd->_Value[valuesize] = '\0'; } } } } delete[] key; } } bool libhttppp::HTTPDCmdController::checkRequired() { for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) { if (curhttpdcmd->getRequired() && !curhttpdcmd->_Found) { return false; } } return true; } void libhttppp::HTTPDCmdController::printHelp() { for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) { Console con; con << "--" << curhttpdcmd->getKey() << "-" << curhttpdcmd->getShortkey() << curhttpdcmd->getHelp() << Console::endl; } } libhttppp::HTTPDCmd *libhttppp::HTTPDCmdController::getHTTPDCmdbyKey(const char *key) { for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) { if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) { return curhttpdcmd; } } return NULL; } libhttppp::HTTPDCmdController::~HTTPDCmdController() { delete _firstHTTPDCmd; _lastHTTPDCmd = NULL; } libhttppp::HttpD::HttpD(int argc, char** argv){ CmdController= new HTTPDCmdController; /*Register Parameters*/ CmdController->registerCmd("help", 'h', false, (const char*) NULL, "Helpmenu"); CmdController->registerCmd("httpaddr",'a', true,(const char*) NULL,"Address to listen"); CmdController->registerCmd("httpport", 'p', false, 8080, "Port to listen"); CmdController->registerCmd("maxconnections", 'm',false, MAXDEFAULTCONN, "Max connections that can connect"); CmdController->registerCmd("httpscert", 'c',false,(const char*) NULL, "HTTPS Certfile"); CmdController->registerCmd("httpskey", 'k',false, (const char*) NULL, "HTTPS Keyfile"); /*Parse Parameters*/ CmdController->parseCmd(argc,argv); if (!CmdController->checkRequired()) { CmdController->printHelp(); _httpexception[HTTPException::Critical] << "cmd parser not enough arguments given"; throw _httpexception; } if (CmdController->getHTTPDCmdbyKey("help") && CmdController->getHTTPDCmdbyKey("help")->getFound()) { CmdController->printHelp(); return; } /*get port from console paramter*/ int port = 0; bool portset=false; if(CmdController->getHTTPDCmdbyKey("httpport")){ port = CmdController->getHTTPDCmdbyKey("httpport")->getValueInt(); portset = CmdController->getHTTPDCmdbyKey("httpport")->getFound(); } /*get httpaddress from console paramter*/ const char *httpaddr = NULL; if (CmdController->getHTTPDCmdbyKey("httpaddr")) httpaddr = CmdController->getHTTPDCmdbyKey("httpaddr")->getValue(); /*get max connections from console paramter*/ int maxconnections = 0; if (CmdController->getHTTPDCmdbyKey("maxconnections")) maxconnections = CmdController->getHTTPDCmdbyKey("maxconnections")->getValueInt(); /*get httpaddress from console paramter*/ const char *sslcertpath = NULL; if (CmdController->getHTTPDCmdbyKey("httpscert")) sslcertpath = CmdController->getHTTPDCmdbyKey("httpscert")->getValue(); /*get httpaddress from console paramter*/ const char *sslkeypath = NULL; if (CmdController->getHTTPDCmdbyKey("httpskey")) sslkeypath = CmdController->getHTTPDCmdbyKey("httpskey")->getValue(); try { #ifndef Windows if (portset == true) _ServerSocket = new ServerSocket(httpaddr, port, maxconnections); else _ServerSocket = new ServerSocket(httpaddr, maxconnections); #else _ServerSocket = new ServerSocket(httpaddr, port, maxconnections); #endif if (!_ServerSocket) { throw _httpexception; } if (sslcertpath && sslkeypath) { _ServerSocket->createContext(); _ServerSocket->loadCertfile(sslcertpath); _ServerSocket->loadKeyfile(sslkeypath); } }catch (HTTPException &e) { } } libhttppp::ServerSocket *libhttppp::HttpD::getServerSocket(){ return _ServerSocket; } libhttppp::HttpD::~HttpD(){ delete _ServerSocket; delete CmdController; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com) * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided * with the distribution. * * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <boost/test/unit_test.hpp> #include <boost/cstdint.hpp> #include <boost/property_tree/xml_parser.hpp> #include <pdal/PointBuffer.hpp> #include <pdal/drivers/las/Reader.hpp> #include <pdal/PDALUtils.hpp> #include "Support.hpp" using namespace pdal; BOOST_AUTO_TEST_SUITE(PointBufferTest) PointBuffer* makeTestBuffer(PointContext ctx) { ctx.registerDim(Dimension::Id::Classification); ctx.registerDim(Dimension::Id::X); ctx.registerDim(Dimension::Id::Y); PointBuffer* data = new PointBuffer(ctx); // write the data into the buffer for (uint32_t i = 0; i < 17; i++) { const uint8_t x = (uint8_t)(i + 1); const int32_t y = i * 10; const double z = i * 100; data->setField(Dimension::Id::Classification, i, x); data->setField(Dimension::Id::X, i, y); data->setField(Dimension::Id::Y, i, z); } BOOST_CHECK(data->size() == 17); return data; } static void verifyTestBuffer(const PointBuffer& data) { // read the data back out for (int i = 0; i < 17; i++) { const uint8_t x = data.getFieldAs<uint8_t>( Dimension::Id::Classification, i); const int32_t y = data.getFieldAs<uint32_t>(Dimension::Id::X, i); const double z = data.getFieldAs<double>(Dimension::Id::Y, i); BOOST_CHECK_EQUAL(x, i + 1); BOOST_CHECK_EQUAL(y, i * 10); BOOST_CHECK(Utils::compare_approx(z, static_cast<double>(i) * 100.0, (std::numeric_limits<double>::min)())); } } BOOST_AUTO_TEST_CASE(test_get_set) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); verifyTestBuffer(*data); delete data; } BOOST_AUTO_TEST_CASE(test_getFieldAs_uint8) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); // read the data back out for (int i = 0; i < 3; i++) { uint8_t x = data->getFieldAs<uint8_t>(Dimension::Id::Classification, i); uint8_t y = data->getFieldAs<uint8_t>(Dimension::Id::X, i); uint8_t z = data->getFieldAs<uint8_t>(Dimension::Id::Y, i); BOOST_CHECK_EQUAL(x, i + 1); BOOST_CHECK_EQUAL(y, i * 10); BOOST_CHECK_EQUAL(z, i * 100); } // read the data back out for (int i = 3; i < 17; i++) { uint8_t x = data->getFieldAs<uint8_t>(Dimension::Id::Classification, i); uint8_t y = data->getFieldAs<uint8_t>(Dimension::Id::X, i); BOOST_CHECK_THROW(data->getFieldAs<uint8_t>(Dimension::Id::Y, i), pdal_error); BOOST_CHECK(x == i + 1); BOOST_CHECK(y == i * 10); } delete data; } BOOST_AUTO_TEST_CASE(test_getFieldAs_int32) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); // read the data back out for (int i = 0; i < 17; i++) { int32_t x = data->getFieldAs<int32_t>(Dimension::Id::Classification, i); int32_t y = data->getFieldAs<int32_t>(Dimension::Id::X, i); int32_t z = data->getFieldAs<int32_t>(Dimension::Id::Y, i); BOOST_CHECK_EQUAL(x, i + 1); BOOST_CHECK_EQUAL(y, i * 10); BOOST_CHECK_EQUAL(z, i * 100); } delete data; } BOOST_AUTO_TEST_CASE(test_getFieldAs_float) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); // read the data back out for (int i = 0; i < 17; i++) { float x = data->getFieldAs<float>(Dimension::Id::Classification, i); float y = data->getFieldAs<float>(Dimension::Id::X, i); float z = data->getFieldAs<float>(Dimension::Id::Y, i); BOOST_CHECK_CLOSE(x, i + 1.0f, std::numeric_limits<float>::min()); BOOST_CHECK_CLOSE(y, i * 10.0f, std::numeric_limits<float>::min()); BOOST_CHECK_CLOSE(z, i * 100.0f, std::numeric_limits<float>::min()); } delete data; } BOOST_AUTO_TEST_CASE(test_copy) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); PointBuffer d2(*data); // read the data back out { BOOST_CHECK_EQUAL( d2.getFieldAs<uint8_t>(Dimension::Id::Classification, 0), data->getFieldAs<uint8_t>(Dimension::Id::Classification, 0)); BOOST_CHECK_EQUAL(d2.getFieldAs<int32_t>(Dimension::Id::X, 0), data->getFieldAs<int32_t>(Dimension::Id::X, 0)); BOOST_CHECK_EQUAL(d2.getFieldAs<double>(Dimension::Id::Y, 0), data->getFieldAs<double>(Dimension::Id::Y, 0)); } for (int i = 1; i < 17; i++) { uint8_t x = d2.getFieldAs<uint8_t>(Dimension::Id::Classification, i); int32_t y = d2.getFieldAs<int32_t>(Dimension::Id::X, i); double z = d2.getFieldAs<double>(Dimension::Id::Y, i); BOOST_CHECK_EQUAL(x, i + 1); BOOST_CHECK_EQUAL(y, i * 10); BOOST_CHECK(Utils::compare_approx(z, i * 100.0, (std::numeric_limits<double>::min)())); } BOOST_CHECK_EQUAL(data->size(), d2.size()); delete data; } BOOST_AUTO_TEST_CASE(test_copy_constructor) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); PointBuffer d2(*data); verifyTestBuffer(d2); delete data; } BOOST_AUTO_TEST_CASE(test_assignment_constructor) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); PointBuffer d2 = *data; verifyTestBuffer(d2); delete data; } BOOST_AUTO_TEST_CASE(PointBufferTest_ptree) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); std::stringstream ss1(std::stringstream::in | std::stringstream::out); boost::property_tree::ptree tree = pdal::utils::toPTree(*data); delete data; boost::property_tree::write_xml(ss1, tree); std::string out1 = ss1.str(); std::string xml_header = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; std::string ref = xml_header + "<0><X>0</X><Y>0</Y><Classification>1</Classification></0><1><X>10</X><Y>100</Y><Classification>2</Classification></1>"; BOOST_CHECK_EQUAL(ref, out1.substr(0, ref.length())); } BOOST_AUTO_TEST_CASE(bigfile) { PointContext ctx; point_count_t NUM_PTS = 1000000; ctx.registerDim(Dimension::Id::X); ctx.registerDim(Dimension::Id::Y); ctx.registerDim(Dimension::Id::Z); PointBuffer buf(ctx); for (PointId id = 0; id < NUM_PTS; ++id) { buf.setField(Dimension::Id::X, id, id); buf.setField(Dimension::Id::Y, id, 2 * id); buf.setField(Dimension::Id::Z, id, -(int)id); } for (PointId id = 0; id < NUM_PTS; ++id) { BOOST_CHECK_EQUAL( buf.getFieldAs<PointId>(Dimension::Id::X, id), id); BOOST_CHECK_EQUAL( buf.getFieldAs<PointId>(Dimension::Id::Y, id), id * 2); BOOST_CHECK_EQUAL( buf.getFieldAs<int>(Dimension::Id::Z, id), -(int)id); } // Test some random access. PointId ids[NUM_PTS]; for (PointId idx = 0; idx < NUM_PTS; ++idx) ids[idx] = idx; // Do a bunch of random swaps. for (PointId idx = 0; idx < NUM_PTS; ++idx) std::swap(ids[idx], ids[random() % NUM_PTS]); for (PointId idx = 0; idx < NUM_PTS; ++idx) { PointId id = ids[idx]; buf.setField(Dimension::Id::X, id, idx); buf.setField(Dimension::Id::Y, id, 2 * idx); buf.setField(Dimension::Id::Z, id, -(int)idx); } for (PointId idx = 0; idx < NUM_PTS; ++idx) { PointId id = ids[idx]; BOOST_CHECK_EQUAL( buf.getFieldAs<PointId>(Dimension::Id::X, id), idx); BOOST_CHECK_EQUAL( buf.getFieldAs<PointId>(Dimension::Id::Y, id), idx * 2); BOOST_CHECK_EQUAL( buf.getFieldAs<int>(Dimension::Id::Z, id), -(int)idx); } } //ABELL - Move to KdIndex /** BOOST_AUTO_TEST_CASE(test_indexed) { drivers::las::Reader reader(Support::datapath("1.2-with-color.las")); BOOST_CHECK(reader.getDescription() == "Las Reader"); reader.prepare(); const Schema& schema = reader.getSchema(); boost::uint32_t capacity(1000); PointBuffer data(schema, capacity); StageSequentialIterator* iter = reader.createSequentialIterator(data); { uint32_t numRead = iter->read(data); BOOST_CHECK_EQUAL(numRead, capacity); } BOOST_CHECK_EQUAL(data.getCapacity(), capacity); BOOST_CHECK_EQUAL(data.getSchema(), schema); IndexedPointBuffer idata(data); BOOST_CHECK_EQUAL(idata.getCapacity(), capacity); BOOST_CHECK_EQUAL(idata.getSchema(), schema); idata.build(); unsigned k = 8; // If the query distance is 0, just return the k nearest neighbors std::vector<size_t> ids = idata.neighbors(636199, 849238, 428.05, 0.0, k); BOOST_CHECK_EQUAL(ids.size(), k); BOOST_CHECK_EQUAL(ids[0], 8u); BOOST_CHECK_EQUAL(ids[1], 7u); BOOST_CHECK_EQUAL(ids[2], 9u); BOOST_CHECK_EQUAL(ids[3], 42u); BOOST_CHECK_EQUAL(ids[4], 40u); std::vector<size_t> dist_ids = idata.neighbors(636199, 849238, 428.05, 100.0, 3); BOOST_CHECK_EQUAL(dist_ids.size(), 3u); BOOST_CHECK_EQUAL(dist_ids[0], 8u); std::vector<size_t> nids = idata.neighbors(636199, 849238, 428.05, 0.0, k); BOOST_CHECK_EQUAL(nids.size(), k); BOOST_CHECK_EQUAL(nids[0], 8u); BOOST_CHECK_EQUAL(nids[1], 7u); BOOST_CHECK_EQUAL(nids[2], 9u); BOOST_CHECK_EQUAL(nids[3], 42u); BOOST_CHECK_EQUAL(nids[4], 40u); std::vector<size_t> rids = idata.radius(637012.24, 849028.31, 431.66, 100000); BOOST_CHECK_EQUAL(rids.size(), 11u); delete iter; } **/ BOOST_AUTO_TEST_SUITE_END() <commit_msg>addressing multiple windows issues<commit_after>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com) * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided * with the distribution. * * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <random> #include <boost/test/unit_test.hpp> #include <boost/cstdint.hpp> #include <boost/property_tree/xml_parser.hpp> #include <pdal/PointBuffer.hpp> #include <pdal/drivers/las/Reader.hpp> #include <pdal/PDALUtils.hpp> #include "Support.hpp" using namespace pdal; BOOST_AUTO_TEST_SUITE(PointBufferTest) PointBuffer* makeTestBuffer(PointContext ctx) { ctx.registerDim(Dimension::Id::Classification); ctx.registerDim(Dimension::Id::X); ctx.registerDim(Dimension::Id::Y); PointBuffer* data = new PointBuffer(ctx); // write the data into the buffer for (uint32_t i = 0; i < 17; i++) { const uint8_t x = (uint8_t)(i + 1); const int32_t y = i * 10; const double z = i * 100; data->setField(Dimension::Id::Classification, i, x); data->setField(Dimension::Id::X, i, y); data->setField(Dimension::Id::Y, i, z); } BOOST_CHECK(data->size() == 17); return data; } static void verifyTestBuffer(const PointBuffer& data) { // read the data back out for (int i = 0; i < 17; i++) { const uint8_t x = data.getFieldAs<uint8_t>( Dimension::Id::Classification, i); const int32_t y = data.getFieldAs<uint32_t>(Dimension::Id::X, i); const double z = data.getFieldAs<double>(Dimension::Id::Y, i); BOOST_CHECK_EQUAL(x, i + 1); BOOST_CHECK_EQUAL(y, i * 10); BOOST_CHECK(Utils::compare_approx(z, static_cast<double>(i) * 100.0, (std::numeric_limits<double>::min)())); } } BOOST_AUTO_TEST_CASE(test_get_set) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); verifyTestBuffer(*data); delete data; } BOOST_AUTO_TEST_CASE(test_getFieldAs_uint8) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); // read the data back out for (int i = 0; i < 3; i++) { uint8_t x = data->getFieldAs<uint8_t>(Dimension::Id::Classification, i); uint8_t y = data->getFieldAs<uint8_t>(Dimension::Id::X, i); uint8_t z = data->getFieldAs<uint8_t>(Dimension::Id::Y, i); BOOST_CHECK_EQUAL(x, i + 1); BOOST_CHECK_EQUAL(y, i * 10); BOOST_CHECK_EQUAL(z, i * 100); } // read the data back out for (int i = 3; i < 17; i++) { uint8_t x = data->getFieldAs<uint8_t>(Dimension::Id::Classification, i); uint8_t y = data->getFieldAs<uint8_t>(Dimension::Id::X, i); BOOST_CHECK_THROW(data->getFieldAs<uint8_t>(Dimension::Id::Y, i), pdal_error); BOOST_CHECK(x == i + 1); BOOST_CHECK(y == i * 10); } delete data; } BOOST_AUTO_TEST_CASE(test_getFieldAs_int32) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); // read the data back out for (int i = 0; i < 17; i++) { int32_t x = data->getFieldAs<int32_t>(Dimension::Id::Classification, i); int32_t y = data->getFieldAs<int32_t>(Dimension::Id::X, i); int32_t z = data->getFieldAs<int32_t>(Dimension::Id::Y, i); BOOST_CHECK_EQUAL(x, i + 1); BOOST_CHECK_EQUAL(y, i * 10); BOOST_CHECK_EQUAL(z, i * 100); } delete data; } BOOST_AUTO_TEST_CASE(test_getFieldAs_float) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); // read the data back out for (int i = 0; i < 17; i++) { float x = data->getFieldAs<float>(Dimension::Id::Classification, i); float y = data->getFieldAs<float>(Dimension::Id::X, i); float z = data->getFieldAs<float>(Dimension::Id::Y, i); BOOST_CHECK_CLOSE(x, i + 1.0f, std::numeric_limits<float>::min()); BOOST_CHECK_CLOSE(y, i * 10.0f, std::numeric_limits<float>::min()); BOOST_CHECK_CLOSE(z, i * 100.0f, std::numeric_limits<float>::min()); } delete data; } BOOST_AUTO_TEST_CASE(test_copy) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); PointBuffer d2(*data); // read the data back out { BOOST_CHECK_EQUAL( d2.getFieldAs<uint8_t>(Dimension::Id::Classification, 0), data->getFieldAs<uint8_t>(Dimension::Id::Classification, 0)); BOOST_CHECK_EQUAL(d2.getFieldAs<int32_t>(Dimension::Id::X, 0), data->getFieldAs<int32_t>(Dimension::Id::X, 0)); BOOST_CHECK_EQUAL(d2.getFieldAs<double>(Dimension::Id::Y, 0), data->getFieldAs<double>(Dimension::Id::Y, 0)); } for (int i = 1; i < 17; i++) { uint8_t x = d2.getFieldAs<uint8_t>(Dimension::Id::Classification, i); int32_t y = d2.getFieldAs<int32_t>(Dimension::Id::X, i); double z = d2.getFieldAs<double>(Dimension::Id::Y, i); BOOST_CHECK_EQUAL(x, i + 1); BOOST_CHECK_EQUAL(y, i * 10); BOOST_CHECK(Utils::compare_approx(z, i * 100.0, (std::numeric_limits<double>::min)())); } BOOST_CHECK_EQUAL(data->size(), d2.size()); delete data; } BOOST_AUTO_TEST_CASE(test_copy_constructor) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); PointBuffer d2(*data); verifyTestBuffer(d2); delete data; } BOOST_AUTO_TEST_CASE(test_assignment_constructor) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); PointBuffer d2 = *data; verifyTestBuffer(d2); delete data; } BOOST_AUTO_TEST_CASE(PointBufferTest_ptree) { PointContext ctx; PointBuffer* data = makeTestBuffer(ctx); std::stringstream ss1(std::stringstream::in | std::stringstream::out); boost::property_tree::ptree tree = pdal::utils::toPTree(*data); delete data; boost::property_tree::write_xml(ss1, tree); std::string out1 = ss1.str(); std::string xml_header = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; std::string ref = xml_header + "<0><X>0</X><Y>0</Y><Classification>1</Classification></0><1><X>10</X><Y>100</Y><Classification>2</Classification></1>"; BOOST_CHECK_EQUAL(ref, out1.substr(0, ref.length())); } BOOST_AUTO_TEST_CASE(bigfile) { PointContext ctx; point_count_t NUM_PTS = 1000000; ctx.registerDim(Dimension::Id::X); ctx.registerDim(Dimension::Id::Y); ctx.registerDim(Dimension::Id::Z); PointBuffer buf(ctx); for (PointId id = 0; id < NUM_PTS; ++id) { buf.setField(Dimension::Id::X, id, id); buf.setField(Dimension::Id::Y, id, 2 * id); buf.setField(Dimension::Id::Z, id, -(int)id); } for (PointId id = 0; id < NUM_PTS; ++id) { BOOST_CHECK_EQUAL( buf.getFieldAs<PointId>(Dimension::Id::X, id), id); BOOST_CHECK_EQUAL( buf.getFieldAs<PointId>(Dimension::Id::Y, id), id * 2); BOOST_CHECK_EQUAL( buf.getFieldAs<int>(Dimension::Id::Z, id), -(int)id); } // Test some random access. std::unique_ptr<PointId[]> ids(new PointId[NUM_PTS]); for (PointId idx = 0; idx < NUM_PTS; ++idx) ids[idx] = idx; // Do a bunch of random swaps. std::default_random_engine generator; std::uniform_int_distribution<PointId> distribution(0, NUM_PTS-1); for (PointId idx = 0; idx < NUM_PTS; ++idx) { PointId y = distribution(generator); PointId temp = std::move(ids[idx]); ids[idx] = std::move(ids[y]); ids[y] = std::move(temp); } for (PointId idx = 0; idx < NUM_PTS; ++idx) { PointId id = ids[idx]; buf.setField(Dimension::Id::X, id, idx); buf.setField(Dimension::Id::Y, id, 2 * idx); buf.setField(Dimension::Id::Z, id, -(int)idx); } for (PointId idx = 0; idx < NUM_PTS; ++idx) { PointId id = ids[idx]; BOOST_CHECK_EQUAL( buf.getFieldAs<PointId>(Dimension::Id::X, id), idx); BOOST_CHECK_EQUAL( buf.getFieldAs<PointId>(Dimension::Id::Y, id), idx * 2); BOOST_CHECK_EQUAL( buf.getFieldAs<int>(Dimension::Id::Z, id), -(int)idx); } } //ABELL - Move to KdIndex /** BOOST_AUTO_TEST_CASE(test_indexed) { drivers::las::Reader reader(Support::datapath("1.2-with-color.las")); BOOST_CHECK(reader.getDescription() == "Las Reader"); reader.prepare(); const Schema& schema = reader.getSchema(); boost::uint32_t capacity(1000); PointBuffer data(schema, capacity); StageSequentialIterator* iter = reader.createSequentialIterator(data); { uint32_t numRead = iter->read(data); BOOST_CHECK_EQUAL(numRead, capacity); } BOOST_CHECK_EQUAL(data.getCapacity(), capacity); BOOST_CHECK_EQUAL(data.getSchema(), schema); IndexedPointBuffer idata(data); BOOST_CHECK_EQUAL(idata.getCapacity(), capacity); BOOST_CHECK_EQUAL(idata.getSchema(), schema); idata.build(); unsigned k = 8; // If the query distance is 0, just return the k nearest neighbors std::vector<size_t> ids = idata.neighbors(636199, 849238, 428.05, 0.0, k); BOOST_CHECK_EQUAL(ids.size(), k); BOOST_CHECK_EQUAL(ids[0], 8u); BOOST_CHECK_EQUAL(ids[1], 7u); BOOST_CHECK_EQUAL(ids[2], 9u); BOOST_CHECK_EQUAL(ids[3], 42u); BOOST_CHECK_EQUAL(ids[4], 40u); std::vector<size_t> dist_ids = idata.neighbors(636199, 849238, 428.05, 100.0, 3); BOOST_CHECK_EQUAL(dist_ids.size(), 3u); BOOST_CHECK_EQUAL(dist_ids[0], 8u); std::vector<size_t> nids = idata.neighbors(636199, 849238, 428.05, 0.0, k); BOOST_CHECK_EQUAL(nids.size(), k); BOOST_CHECK_EQUAL(nids[0], 8u); BOOST_CHECK_EQUAL(nids[1], 7u); BOOST_CHECK_EQUAL(nids[2], 9u); BOOST_CHECK_EQUAL(nids[3], 42u); BOOST_CHECK_EQUAL(nids[4], 40u); std::vector<size_t> rids = idata.radius(637012.24, 849028.31, 431.66, 100000); BOOST_CHECK_EQUAL(rids.size(), 11u); delete iter; } **/ BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "comparator.hpp" using namespace std; using namespace OLC; TEST_CASE("comparator methods", "[comparator]") { vector<Nucleotide> first; first.push_back(Nucleotide(NucleotideLetter(0x03))); first.push_back(Nucleotide(NucleotideLetter(0x01))); first.push_back(Nucleotide(NucleotideLetter(0x01))); first.push_back(Nucleotide(NucleotideLetter(0x02))); first.push_back(Nucleotide(NucleotideLetter(0x04))); first.push_back(Nucleotide(NucleotideLetter(0x03))); vector<Nucleotide> second; second.push_back(Nucleotide(NucleotideLetter(0x04))); second.push_back(Nucleotide(NucleotideLetter(0x01))); second.push_back(Nucleotide(NucleotideLetter(0x02))); second.push_back(Nucleotide(NucleotideLetter(0x04))); second.push_back(Nucleotide(NucleotideLetter(0x02))); second.push_back(Nucleotide(NucleotideLetter(0x01))); const Overlap overlap = OLC::compare(first, second); const uint32_t overlapFirstEnd = overlap.getEndFirst(); const uint32_t overlapSecondEnd = overlap.getEndSecond(); const uint32_t overlapFirstStart = overlap.getStartFirst(); const uint32_t overlapSecondStart = overlap.getStartSecond(); const int overlapLength = overlapFirstEnd - overlapFirstStart + 1; SECTION("check overlap length") { REQUIRE(overlapLength == 3); } SECTION("check overlap values") { REQUIRE(first[overlapFirstStart].getValue() == 1); REQUIRE(first[overlapFirstStart + 1].getValue() == 2); //REQUIRE(first[overlapFirstStart + 2].getValue() == 4); REQUIRE(second[overlapSecondStart].getValue() == 1); REQUIRE(second[overlapSecondStart + 1].getValue() == 2); //REQUIRE(second[overlapSecondStart + 2].getValue() == 4); } } <commit_msg>comparator: fix the test for real this time<commit_after>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "comparator.hpp" using namespace std; using namespace OLC; TEST_CASE("comparator methods", "[comparator]") { vector<Nucleotide> first; first.push_back(Nucleotide(NucleotideLetter(0x03))); first.push_back(Nucleotide(NucleotideLetter(0x01))); first.push_back(Nucleotide(NucleotideLetter(0x01))); first.push_back(Nucleotide(NucleotideLetter(0x02))); first.push_back(Nucleotide(NucleotideLetter(0x00))); first.push_back(Nucleotide(NucleotideLetter(0x03))); vector<Nucleotide> second; second.push_back(Nucleotide(NucleotideLetter(0x00))); second.push_back(Nucleotide(NucleotideLetter(0x01))); second.push_back(Nucleotide(NucleotideLetter(0x02))); second.push_back(Nucleotide(NucleotideLetter(0x00))); second.push_back(Nucleotide(NucleotideLetter(0x02))); second.push_back(Nucleotide(NucleotideLetter(0x01))); const Overlap overlap = compare(first, second); const uint32_t overlapFirstEnd = overlap.getEndFirst(); const uint32_t overlapSecondEnd = overlap.getEndSecond(); const uint32_t overlapFirstStart = overlap.getStartFirst(); const uint32_t overlapSecondStart = overlap.getStartSecond(); const int overlapLength = overlapFirstEnd - overlapFirstStart + 1; SECTION("check overlap length") { REQUIRE(overlapLength == 3); } SECTION("check overlap values") { REQUIRE(first[overlapFirstStart].getValue() == 1); REQUIRE(first[overlapFirstStart + 1].getValue() == 2); REQUIRE(first[overlapFirstStart + 2].getValue() == 0); REQUIRE(second[overlapSecondStart].getValue() == 1); REQUIRE(second[overlapSecondStart + 1].getValue() == 2); REQUIRE(second[overlapSecondStart + 2].getValue() == 0); } } <|endoftext|>
<commit_before>#include "lexer.hpp" #include <cctype> #include <algorithm> #include <iterator> #include <vector> namespace klang { namespace { using const_iterator = std::string::const_iterator; } Token::Token() : type_(TokenType::UNKNOWN), str_(), line_(-1) {} Token::Token(TokenType type, const std::string& str, int line) : type_(type), str_(str), line_(line) {} TokenType Token::type() const { return type_; } std::string Token::str() const { return str_; } int Token::line() const { return line_; } bool alphabet(char c) { return std::isalpha(c); } bool alphabet_or_bar(char c) { return (c == '_' || alphabet(c)); } bool nonzero_digit(char c) { return (c >= '1' && c <= '9'); } bool decimal_digit(char c) { return std::isdigit(c); } bool identifier(const std::string& str) { if (str.empty() || !alphabet_or_bar(str.front())) { return false; } for (char c : str) { if (!alphabet_or_bar(c) && !decimal_digit(c)) { return false; } } return true; } bool decimal_integer(const std::string& str) { if (str == "0") return true; if (str.empty() || !nonzero_digit(str.front())) { return false; } for (char c : str) { if (!decimal_digit(c)) { return false; } } return true; } bool symbol(const std::string& str) { using std::begin; using std::end; static std::vector<std::string> const symbol_list = { "~", "+", "-", "*", "/", "%", ":=", ":+=", ":-=", ":*=", ":/=", ":%=", "=", "=/", "<", ">", "<=", ">=", ";", "(", ")", "{", "}", "->", "~}", "and", "or", "not", "int", "def", "var", "if", "else", "while", "for", "break", "continue", "return" }; return (std::find(begin(symbol_list), end(symbol_list), str) != end(symbol_list)); } bool ignore(const std::string& str) { if(str.size() != 1) return false; return std::isspace(str[0]); } bool singleline_comment(const_iterator head, const_iterator tail) { using std::begin; using std::end; if(std::equal(head, std::next(head, 2), "~~")) { return std::find(head, tail, '\n') == std::prev(tail); } return false; } bool multiline_comment(const_iterator head, const_iterator tail) { using std::begin; using std::end; if (std::equal(head, std::next(head, 2), "{~")) { int nest = 0; for(auto it = head; std::next(it) != tail; ++it) { std::string tk(it, std::next(it, 2)); if (tk == "{~") { ++nest; } else if(tk == "~}") { --nest; } } bool closed = nest == 0 && std::equal(std::prev(tail, 2), std::prev(tail), "~}"); return (nest > 0 || closed); } return false; } bool comment(const_iterator head, const_iterator tail) { return (singleline_comment(head, tail) || multiline_comment(head, tail)); } bool string_token(const std::string& str) { using std::begin; using std::end; if (str.front() == '"') { bool escaped = false; for(auto it = std::next(begin(str)); it != end(str); ++it) { if (*it == '\\') { escaped = true; } else if (*it == '"' && (!escaped)) { return std::next(it) == end(str); } else { escaped = false; } } } return false; } TokenType match_type(std::string const& str) { if (comment(str)) return TokenType::IGNORE; if (symbol(str)) return TokenType::SYMBOL; if (identifier(str)) return TokenType::IDENTIFIER; if (decimal_integer(str)) return TokenType::NUMBER; if (string_token(str)) return TokenType::STRING; if (ignore(str)) return TokenType::IGNORE; return TokenType::UNKNOWN; } std::string extract_string(const std::string& str) { if (str.front() == '"') { bool escaped = false; std::string new_str; for(auto c : str) { if (escaped) { if(c == '"') new_str.push_back('"'); if(c == 'n') new_str.push_back('\n'); escaped = false; } else if (c == '\\') { escaped = true; } else if (c != '"') { new_str.push_back(c); } } return new_str; } return str; } TokenVector tokenize(std::istream& is) { using std::begin; using std::end; std::string const code(std::string{std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>()} + '\n'); // ファイルの末尾が改行で終わっているほうが処理しやすい。 TokenVector tokens; TokenType prev = TokenType::UNKNOWN; const_iterator head(begin(code)); int line = 1; for (auto it(begin(code)); it != end(code); ++it) { TokenType next = match_type(head, std::next(it)); if (prev != TokenType::UNKNOWN && next == TokenType::UNKNOWN) { if (prev != TokenType::IGNORE) { tokens.push_back(Token(prev, extract_string(head, it), line)); } head = it; prev = match_type(head, std::next(head)); } else { prev = next; } if (*it == '\n') ++line; } return tokens; } bool operator==(Token const& lhs, Token const& rhs) { return lhs.type() == rhs.type() && lhs.str() == rhs.str() && lhs.line() == rhs.line(); } bool operator!=(Token const& lhs, Token const& rhs) { return !( lhs == rhs ); } } // namespace klang <commit_msg>match_type を対応<commit_after>#include "lexer.hpp" #include <cctype> #include <algorithm> #include <iterator> #include <vector> namespace klang { namespace { using const_iterator = std::string::const_iterator; } Token::Token() : type_(TokenType::UNKNOWN), str_(), line_(-1) {} Token::Token(TokenType type, const std::string& str, int line) : type_(type), str_(str), line_(line) {} TokenType Token::type() const { return type_; } std::string Token::str() const { return str_; } int Token::line() const { return line_; } bool alphabet(char c) { return std::isalpha(c); } bool alphabet_or_bar(char c) { return (c == '_' || alphabet(c)); } bool nonzero_digit(char c) { return (c >= '1' && c <= '9'); } bool decimal_digit(char c) { return std::isdigit(c); } bool identifier(const std::string& str) { if (str.empty() || !alphabet_or_bar(str.front())) { return false; } for (char c : str) { if (!alphabet_or_bar(c) && !decimal_digit(c)) { return false; } } return true; } bool decimal_integer(const std::string& str) { if (str == "0") return true; if (str.empty() || !nonzero_digit(str.front())) { return false; } for (char c : str) { if (!decimal_digit(c)) { return false; } } return true; } bool symbol(const std::string& str) { using std::begin; using std::end; static std::vector<std::string> const symbol_list = { "~", "+", "-", "*", "/", "%", ":=", ":+=", ":-=", ":*=", ":/=", ":%=", "=", "=/", "<", ">", "<=", ">=", ";", "(", ")", "{", "}", "->", "~}", "and", "or", "not", "int", "def", "var", "if", "else", "while", "for", "break", "continue", "return" }; return (std::find(begin(symbol_list), end(symbol_list), str) != end(symbol_list)); } bool ignore(const std::string& str) { if(str.size() != 1) return false; return std::isspace(str[0]); } bool singleline_comment(const_iterator head, const_iterator tail) { using std::begin; using std::end; if(std::equal(head, std::next(head, 2), "~~")) { return std::find(head, tail, '\n') == std::prev(tail); } return false; } bool multiline_comment(const_iterator head, const_iterator tail) { using std::begin; using std::end; if (std::equal(head, std::next(head, 2), "{~")) { int nest = 0; for(auto it = head; std::next(it) != tail; ++it) { std::string tk(it, std::next(it, 2)); if (tk == "{~") { ++nest; } else if(tk == "~}") { --nest; } } bool closed = nest == 0 && std::equal(std::prev(tail, 2), std::prev(tail), "~}"); return (nest > 0 || closed); } return false; } bool comment(const_iterator head, const_iterator tail) { return (singleline_comment(head, tail) || multiline_comment(head, tail)); } bool string_token(const std::string& str) { using std::begin; using std::end; if (str.front() == '"') { bool escaped = false; for(auto it = std::next(begin(str)); it != end(str); ++it) { if (*it == '\\') { escaped = true; } else if (*it == '"' && (!escaped)) { return std::next(it) == end(str); } else { escaped = false; } } } return false; } TokenType match_type(const_iterator head, const_iterator tail) { if (comment(head, tail)) return TokenType::IGNORE; if (symbol(head, tail)) return TokenType::SYMBOL; if (identifier(head, tail)) return TokenType::IDENTIFIER; if (decimal_integer(head, tail)) return TokenType::NUMBER; if (string_token(head, tail)) return TokenType::STRING; if (ignore(head, tail)) return TokenType::IGNORE; return TokenType::UNKNOWN; } std::string extract_string(const std::string& str) { if (str.front() == '"') { bool escaped = false; std::string new_str; for(auto c : str) { if (escaped) { if(c == '"') new_str.push_back('"'); if(c == 'n') new_str.push_back('\n'); escaped = false; } else if (c == '\\') { escaped = true; } else if (c != '"') { new_str.push_back(c); } } return new_str; } return str; } TokenVector tokenize(std::istream& is) { using std::begin; using std::end; std::string const code(std::string{std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>()} + '\n'); // ファイルの末尾が改行で終わっているほうが処理しやすい。 TokenVector tokens; TokenType prev = TokenType::UNKNOWN; const_iterator head(begin(code)); int line = 1; for (auto it(begin(code)); it != end(code); ++it) { TokenType next = match_type(head, std::next(it)); if (prev != TokenType::UNKNOWN && next == TokenType::UNKNOWN) { if (prev != TokenType::IGNORE) { tokens.push_back(Token(prev, extract_string(head, it), line)); } head = it; prev = match_type(head, std::next(head)); } else { prev = next; } if (*it == '\n') ++line; } return tokens; } bool operator==(Token const& lhs, Token const& rhs) { return lhs.type() == rhs.type() && lhs.str() == rhs.str() && lhs.line() == rhs.line(); } bool operator!=(Token const& lhs, Token const& rhs) { return !( lhs == rhs ); } } // namespace klang <|endoftext|>
<commit_before>#ifdef MALLOC_PROF #include <google/tcmalloc.h> #include <stdio.h> #include <perfmon.hpp> perfmon_duration_sampler_t pm_operator_new("operator_new", secs_to_ticks(1.0)), pm_operator_delete("operator_delete", secs_to_ticks(1.0)); void* operator new(size_t size) { block_pm_duration set_timer(&pm_operator_new); return tc_new(size); } void operator delete(void* p) __THROW { block_pm_duration set_timer(&pm_operator_delete); tc_delete(p); } void* operator new[](size_t size) { block_pm_duration set_timer(&pm_operator_new); return tc_newarray(size); } void operator delete[](void* p) __THROW { block_pm_duration set_timer(&pm_operator_delete); tc_deletearray(p); } #endif /* void* operator new(size_t size, const std::nothrow_t& nt) __THROW { return tc_new_nothrow(size, nt); } void* operator new[](size_t size, const std::nothrow_t& nt) __THROW { return tc_newarray_nothrow(size, nt); } void operator delete(void* ptr, const std::nothrow_t& nt) __THROW { return tc_delete_nothrow(ptr, nt); } void operator delete[](void* ptr, const std::nothrow_t& nt) __THROW { return tc_deletearray_nothrow(ptr, nt); } */ <commit_msg>Removed commented code in malloc.cc.<commit_after>#ifdef MALLOC_PROF #include <google/tcmalloc.h> #include <stdio.h> #include <perfmon.hpp> perfmon_duration_sampler_t pm_operator_new("operator_new", secs_to_ticks(1.0)), pm_operator_delete("operator_delete", secs_to_ticks(1.0)); void* operator new(size_t size) { block_pm_duration set_timer(&pm_operator_new); return tc_new(size); } void operator delete(void* p) __THROW { block_pm_duration set_timer(&pm_operator_delete); tc_delete(p); } void* operator new[](size_t size) { block_pm_duration set_timer(&pm_operator_new); return tc_newarray(size); } void operator delete[](void* p) __THROW { block_pm_duration set_timer(&pm_operator_delete); tc_deletearray(p); } #endif <|endoftext|>
<commit_before> // This file contains definition of C++ new/delete operators #include <stddef.h> #include <malloc.h> #include "stdexcept.h" namespace std { void terminate(); } typedef void (*new_handler)(); static new_handler new_handl = &std::terminate; namespace std { new_handler set_new_handler(new_handler handl) { new_handler old = new_handl; new_handl = handl; return old; } } __attribute__((weak)) void * operator new(size_t size) { void * mem = malloc(size); while(mem == NULL) { if(new_handl != NULL) { new_handl(); } else { throw std::bad_alloc(); } mem = malloc(size); } return mem; } __attribute__((weak)) void operator delete(void * ptr) { free(ptr); } __attribute__((weak)) void * operator new[](size_t size) { return ::operator new(size); } __attribute__((weak)) void operator delete[](void * ptr) { ::operator delete(ptr); } <commit_msg>am d473efff: nothrow operator new was implemented (fix for COMPILER-8913)<commit_after> // This file contains definition of C++ new/delete operators #include <stddef.h> #include <malloc.h> #include "stdexcept.h" namespace std { void terminate(); } typedef void (*new_handler)(); static new_handler new_handl = &std::terminate; namespace std { new_handler set_new_handler(new_handler handl) { new_handler old = new_handl; new_handl = handl; return old; } } __attribute__((weak)) void * operator new(size_t size) { void * mem = malloc(size); while(mem == NULL) { if(new_handl != NULL) { new_handl(); } else { throw std::bad_alloc(); } mem = malloc(size); } return mem; } namespace std { struct nothrow_t {}; } __attribute__((weak)) void * operator new(size_t size, const std::nothrow_t &) throw() { void * mem = malloc(size); while(mem == NULL) { if(new_handl != NULL) { new_handl(); } else { return NULL; } mem = malloc(size); } return mem; } __attribute__((weak)) void operator delete(void * ptr) { free(ptr); } __attribute__((weak)) void * operator new[](size_t size) { return ::operator new(size); } __attribute__((weak)) void operator delete[](void * ptr) { ::operator delete(ptr); } <|endoftext|>
<commit_before><commit_msg>fix out of bounds access in matc<commit_after><|endoftext|>
<commit_before>#pragma once #include <openMVG/keyframe/SharpnessSelectionPreset.hpp> #include <openMVG/features/features.hpp> #include <openMVG/dataio/FeedProvider.hpp> #include <openMVG/voctree/vocabulary_tree.hpp> #include <OpenImageIO/imageio.h> #include <string> #include <vector> #include <memory> #include <limits> namespace oiio = OpenImageIO; namespace openMVG { namespace image { template<typename T> class Image; } // namespace image namespace keyframe { class KeyframeSelector { private: // SIFT descriptor definition const static std::size_t _dimension = 128; using DescriptorFloat = openMVG::features::Descriptor<float, _dimension>; public: /** * @brief Camera informations */ struct CameraInfo { /// Camera brand std::string brand = "Pinhole"; /// Camera model std::string model = "Pinhole"; /// Focal length in mm or px float focalLength = 1.2f; /// If focalIsMM is false, focalLength is in px bool focalIsMM = true; }; /** * @brief KeyframeSelector constructor * @param[in] mediaPath video file path or image sequence directory * @param[in] sensorDbPath camera sensor width database path * @param[in] voctreeFilePath vocabulary tree path * @param[in] outputDirectory output keyframes directory */ KeyframeSelector(const std::vector<std::string>& mediaPaths, const std::string& sensorDbPath, const std::string& voctreeFilePath, const std::string& outputDirectory); /** * @brief KeyframeSelector copy constructor - NO COPY * @param[in] copy keyframeSelector */ KeyframeSelector(const KeyframeSelector& copy) = delete; /** * @brief Process media paths and extract keyframes */ void process(); /** * @brief Set cameras informations for output keyframes * @param[in] cameras informations */ void setCameraInfos(const std::vector<CameraInfo>& CameraInfos) { _cameraInfos = CameraInfos; } /** * @brief Set Sharpness selection preset * @param[in] sharpnessPreset enum */ void setSharpnessSelectionPreset(ESharpnessSelectionPreset sharpnessPreset) { switch(sharpnessPreset) { case ESharpnessSelectionPreset::ULTRA: _sharpnessThreshold = 20.0f; break; case ESharpnessSelectionPreset::HIGH: _sharpnessThreshold = 17.0f; break; case ESharpnessSelectionPreset::NORMAL: _sharpnessThreshold = 15.0f; break; case ESharpnessSelectionPreset::MEDIUM: _sharpnessThreshold = 10.0f; break; case ESharpnessSelectionPreset::LOW: _sharpnessThreshold = 8.0f; break; case ESharpnessSelectionPreset::VERY_LOW: _sharpnessThreshold = 6.0f; break; case ESharpnessSelectionPreset::NONE: _sharpnessThreshold = .0f; break; default: throw std::out_of_range("Invalid sharpnessPreset enum"); } } /** * @brief Set sharp subset size for process algorithm * @param[in] subset sharp part of the image (1 = all, 2 = size/2, ...) */ void setSharpSubset(unsigned int subset) { _sharpSubset = subset; } /** * @brief Set min frame step for process algorithm * @param[in] frameStep minimum number of frames between two keyframes */ void setMinFrameStep(unsigned int frameStep) { _minFrameStep = frameStep; } /** * @brief Set max frame step for process algorithm * @param[in] frameStep maximum number of frames after which a keyframe can be taken */ void setMaxFrameStep(unsigned int frameStep) { _maxFrameStep = frameStep; } /** * @brief Set max output frame number for process algorithm * @param[in] nbFrame maximum number of output frames (if 0, no limit) */ void setMaxOutFrame(unsigned int nbFrame) { _maxOutFrame = nbFrame; } /** * @brief Get sharp subset size for process algorithm * @return sharp part of the image (1 = all, 2 = size/2, ...) */ unsigned int getSharpSubset() const { return _sharpSubset; } /** * @brief Get min frame step for process algorithm * @return minimum number of frames between two keyframes */ unsigned int getMinFrameStep() const { return _minFrameStep; } /** * @brief Get max output frame number for process algorithm * @return maximum number of frames for trying to select a keyframe */ unsigned int getMaxFrameStep() const { return _maxFrameStep; } /** * @brief Get max output frame number for process algorithm * @return maximum number of output frames (if 0, no limit) */ unsigned int getMaxOutFrame() const { return _maxOutFrame; } private: // Paths /// Media paths std::vector<std::string> _mediaPaths; /// Camera sensor width database std::string _sensorDbPath; /// Voctree file path std::string _voctreeFilePath; /// Output folder for keyframes std::string _outputDirectory; // Algorithm variables /// Sharp part of the image (1 = all, 2 = size/2, ...) unsigned int _sharpSubset = 4; /// Minimum number of frame between two keyframes unsigned int _minFrameStep = 12; /// Maximum number of frame for evaluation unsigned int _maxFrameStep = 36; /// Maximum number of output frame (0 = no limit) unsigned int _maxOutFrame = 0; /// Number of tiles per side unsigned int _nbTileSide = 20; /// Number of previous keyframe distances in order to evaluate distance score unsigned int _nbKeyFrameDist = 10; /// Sharpness threshold (image with higher sharpness will be selected) float _sharpnessThreshold = 15.0f; /// Distance max score (image with smallest distance from the last keyframe will be selected) float _distScoreMax = 100.0f; /// Camera metadatas std::vector<CameraInfo> _cameraInfos; // Tools /// Image describer in order to extract describer std::unique_ptr<features::Image_describer> _imageDescriber; /// Voctree in order to compute sparseHistogram std::unique_ptr< openMVG::voctree::VocabularyTree<DescriptorFloat> > _voctree; /// Feed provider for media paths images extraction std::vector< std::unique_ptr<dataio::FeedProvider> > _feeds; // Process structures /** * @brief Process media global informations */ struct MediaInfo { /// height of the tile unsigned int tileHeight = 0; /// width of the tile unsigned int tileWidth = 0; /// openImageIO image spec oiio::ImageSpec spec; }; /** * @brief Process media informations at a specific frame */ struct MediaData { /// sharpness score float sharpness = 0; /// maximum distance score with keyframe media histograms float distScore = 0; /// sparseHistogram voctree::SparseHistogram histogram; }; /** * @brief Process frame (or set of frames) informations */ struct FrameData { /// average sharpness score of all media float avgSharpness = 0; /// maximum voctree distance score of all media float maxDistScore = 0; /// frame (or set of frames) selected for evaluation bool selected = false; /// frame is a keyframe bool keyframe = false; /// medias process data std::vector<MediaData> mediasData; /** * @brief Compute average sharpness score */ void computeAvgSharpness() { for(const auto& media : mediasData) avgSharpness += media.sharpness; avgSharpness /= mediasData.size(); } }; /// MediaInfo structure per input medias std::vector<MediaInfo> _mediasInfo; /// FrameData structure per frame std::vector<FrameData> _framesData; /// Keyframe indexes container std::vector<std::size_t> _keyframeIndexes; /** * @brief Compute sharpness score of a given image * @param[in] imageGray given image in grayscale * @param[in] tileHeight height of tile * @param[in] tileWidth width of tile * @param[in] tileSharpSubset number of sharp tiles * @return sharpness score */ float computeSharpness(const image::Image<unsigned char>& imageGray, const unsigned int tileHeight, const unsigned int tileWidth, const unsigned int tileSharpSubset) const; /** * @brief Compute sharpness and distance score for a given image * @param[in] image an image of the media * @param[in] frameIndex the image index in the media sequence * @param[in] mediaIndex the media index * @param[in] tileSharpSubset number of sharp tiles * @return true if the frame is selected */ bool computeFrameData(const image::Image<image::RGBColor>& image, std::size_t frameIndex, std::size_t mediaIndex, unsigned int tileSharpSubset); /** * @brief Write a keyframe and metadata * @param[in] image an image of the media * @param[in] frameIndex the image index in the media sequence * @param[in] mediaIndex the media index */ void writeKeyframe(const image::Image<image::RGBColor>& image, std::size_t frameIndex, std::size_t mediaIndex); /** * @brief Convert focal length from px to mm using sensor width database * @param[in] camera informations * @param[in] imageWidth media image width in px */ void convertFocalLengthInMM(CameraInfo& cameraInfo, int imageWidth); }; } // namespace keyframe } // namespace openMVG <commit_msg>[keyframe] Change default brand to `Custom` and default model to `radial3`<commit_after>#pragma once #include <openMVG/keyframe/SharpnessSelectionPreset.hpp> #include <openMVG/features/features.hpp> #include <openMVG/dataio/FeedProvider.hpp> #include <openMVG/voctree/vocabulary_tree.hpp> #include <OpenImageIO/imageio.h> #include <string> #include <vector> #include <memory> #include <limits> namespace oiio = OpenImageIO; namespace openMVG { namespace image { template<typename T> class Image; } // namespace image namespace keyframe { class KeyframeSelector { private: // SIFT descriptor definition const static std::size_t _dimension = 128; using DescriptorFloat = openMVG::features::Descriptor<float, _dimension>; public: /** * @brief Camera informations */ struct CameraInfo { /// Camera brand std::string brand = "Custom"; /// Camera model std::string model = "radial3"; /// Focal length in mm or px float focalLength = 1.2f; /// If focalIsMM is false, focalLength is in px bool focalIsMM = true; }; /** * @brief KeyframeSelector constructor * @param[in] mediaPath video file path or image sequence directory * @param[in] sensorDbPath camera sensor width database path * @param[in] voctreeFilePath vocabulary tree path * @param[in] outputDirectory output keyframes directory */ KeyframeSelector(const std::vector<std::string>& mediaPaths, const std::string& sensorDbPath, const std::string& voctreeFilePath, const std::string& outputDirectory); /** * @brief KeyframeSelector copy constructor - NO COPY * @param[in] copy keyframeSelector */ KeyframeSelector(const KeyframeSelector& copy) = delete; /** * @brief Process media paths and extract keyframes */ void process(); /** * @brief Set cameras informations for output keyframes * @param[in] cameras informations */ void setCameraInfos(const std::vector<CameraInfo>& CameraInfos) { _cameraInfos = CameraInfos; } /** * @brief Set Sharpness selection preset * @param[in] sharpnessPreset enum */ void setSharpnessSelectionPreset(ESharpnessSelectionPreset sharpnessPreset) { switch(sharpnessPreset) { // arbitrary thresholds case ESharpnessSelectionPreset::ULTRA: _sharpnessThreshold = 20.0f; break; case ESharpnessSelectionPreset::HIGH: _sharpnessThreshold = 17.0f; break; case ESharpnessSelectionPreset::NORMAL: _sharpnessThreshold = 15.0f; break; case ESharpnessSelectionPreset::MEDIUM: _sharpnessThreshold = 10.0f; break; case ESharpnessSelectionPreset::LOW: _sharpnessThreshold = 8.0f; break; case ESharpnessSelectionPreset::VERY_LOW: _sharpnessThreshold = 6.0f; break; case ESharpnessSelectionPreset::NONE: _sharpnessThreshold = .0f; break; default: throw std::out_of_range("Invalid sharpnessPreset enum"); } } /** * @brief Set sharp subset size for process algorithm * @param[in] subset sharp part of the image (1 = all, 2 = size/2, ...) */ void setSharpSubset(unsigned int subset) { _sharpSubset = subset; } /** * @brief Set min frame step for process algorithm * @param[in] frameStep minimum number of frames between two keyframes */ void setMinFrameStep(unsigned int frameStep) { _minFrameStep = frameStep; } /** * @brief Set max frame step for process algorithm * @param[in] frameStep maximum number of frames after which a keyframe can be taken */ void setMaxFrameStep(unsigned int frameStep) { _maxFrameStep = frameStep; } /** * @brief Set max output frame number for process algorithm * @param[in] nbFrame maximum number of output frames (if 0, no limit) */ void setMaxOutFrame(unsigned int nbFrame) { _maxOutFrame = nbFrame; } /** * @brief Get sharp subset size for process algorithm * @return sharp part of the image (1 = all, 2 = size/2, ...) */ unsigned int getSharpSubset() const { return _sharpSubset; } /** * @brief Get min frame step for process algorithm * @return minimum number of frames between two keyframes */ unsigned int getMinFrameStep() const { return _minFrameStep; } /** * @brief Get max output frame number for process algorithm * @return maximum number of frames for trying to select a keyframe */ unsigned int getMaxFrameStep() const { return _maxFrameStep; } /** * @brief Get max output frame number for process algorithm * @return maximum number of output frames (if 0, no limit) */ unsigned int getMaxOutFrame() const { return _maxOutFrame; } private: // Paths /// Media paths std::vector<std::string> _mediaPaths; /// Camera sensor width database std::string _sensorDbPath; /// Voctree file path std::string _voctreeFilePath; /// Output folder for keyframes std::string _outputDirectory; // Algorithm variables /// Sharp part of the image (1 = all, 2 = size/2, ...) unsigned int _sharpSubset = 4; /// Minimum number of frame between two keyframes unsigned int _minFrameStep = 12; /// Maximum number of frame for evaluation unsigned int _maxFrameStep = 36; /// Maximum number of output frame (0 = no limit) unsigned int _maxOutFrame = 0; /// Number of tiles per side unsigned int _nbTileSide = 20; /// Number of previous keyframe distances in order to evaluate distance score unsigned int _nbKeyFrameDist = 10; /// Sharpness threshold (image with higher sharpness will be selected) float _sharpnessThreshold = 15.0f; /// Distance max score (image with smallest distance from the last keyframe will be selected) float _distScoreMax = 100.0f; /// Camera metadatas std::vector<CameraInfo> _cameraInfos; // Tools /// Image describer in order to extract describer std::unique_ptr<features::Image_describer> _imageDescriber; /// Voctree in order to compute sparseHistogram std::unique_ptr< openMVG::voctree::VocabularyTree<DescriptorFloat> > _voctree; /// Feed provider for media paths images extraction std::vector< std::unique_ptr<dataio::FeedProvider> > _feeds; // Process structures /** * @brief Process media global informations */ struct MediaInfo { /// height of the tile unsigned int tileHeight = 0; /// width of the tile unsigned int tileWidth = 0; /// openImageIO image spec oiio::ImageSpec spec; }; /** * @brief Process media informations at a specific frame */ struct MediaData { /// sharpness score float sharpness = 0; /// maximum distance score with keyframe media histograms float distScore = 0; /// sparseHistogram voctree::SparseHistogram histogram; }; /** * @brief Process frame (or set of frames) informations */ struct FrameData { /// average sharpness score of all media float avgSharpness = 0; /// maximum voctree distance score of all media float maxDistScore = 0; /// frame (or set of frames) selected for evaluation bool selected = false; /// frame is a keyframe bool keyframe = false; /// medias process data std::vector<MediaData> mediasData; /** * @brief Compute average sharpness score */ void computeAvgSharpness() { for(const auto& media : mediasData) avgSharpness += media.sharpness; avgSharpness /= mediasData.size(); } }; /// MediaInfo structure per input medias std::vector<MediaInfo> _mediasInfo; /// FrameData structure per frame std::vector<FrameData> _framesData; /// Keyframe indexes container std::vector<std::size_t> _keyframeIndexes; /** * @brief Compute sharpness score of a given image * @param[in] imageGray given image in grayscale * @param[in] tileHeight height of tile * @param[in] tileWidth width of tile * @param[in] tileSharpSubset number of sharp tiles * @return sharpness score */ float computeSharpness(const image::Image<unsigned char>& imageGray, const unsigned int tileHeight, const unsigned int tileWidth, const unsigned int tileSharpSubset) const; /** * @brief Compute sharpness and distance score for a given image * @param[in] image an image of the media * @param[in] frameIndex the image index in the media sequence * @param[in] mediaIndex the media index * @param[in] tileSharpSubset number of sharp tiles * @return true if the frame is selected */ bool computeFrameData(const image::Image<image::RGBColor>& image, std::size_t frameIndex, std::size_t mediaIndex, unsigned int tileSharpSubset); /** * @brief Write a keyframe and metadata * @param[in] image an image of the media * @param[in] frameIndex the image index in the media sequence * @param[in] mediaIndex the media index */ void writeKeyframe(const image::Image<image::RGBColor>& image, std::size_t frameIndex, std::size_t mediaIndex); /** * @brief Convert focal length from px to mm using sensor width database * @param[in] camera informations * @param[in] imageWidth media image width in px */ void convertFocalLengthInMM(CameraInfo& cameraInfo, int imageWidth); }; } // namespace keyframe } // namespace openMVG <|endoftext|>
<commit_before>/* * This file is part of the Polkit-qt project * Copyright (C) 2009 Daniel Nicoletti <dantti85-pk@yahoo.com.br> * * 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 "polkit_qt_context.h" #include "polkit_qt_singleton.h" #include <QtCore/QSocketNotifier> #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QStringList> #include <QtDBus/QDBusInterface> #include <QtDBus/QDBusReply> #include <polkit-dbus/polkit-dbus.h> using namespace QPolicyKit; class ContextHelper { public: ContextHelper() : q(0) {} ~ContextHelper() { delete q; } Context *q; }; POLKIT_QT_GLOBAL_STATIC(ContextHelper, s_globalContext) Context *Context::instance() { if (!s_globalContext->q) { new Context; } return s_globalContext->q; } // I'm using null instead of 0 as polkit will return // NULL on failures Context::Context(QObject *parent) : QObject(parent) , pkContext(NULL) , pkTracker(NULL) , m_hasError(false) { Q_ASSERT(!s_globalContext->q); s_globalContext->q = this; qDebug() << "Context - Constructing singleton"; init(); } Context::~Context() { if (pkContext != NULL) { polkit_context_unref(pkContext); } if (pkTracker != NULL) { polkit_tracker_unref(pkTracker); } } void Context::init() { DBusError error; DBusError dbus_error; PolKitError *pk_error; dbus_error_init(&error); // if ((_singleton->priv->system_bus = dbus_g_bus_get (DBUS_BUS_SYSTEM, error)) == NULL) { // goto error; // } if ((m_systemBus = dbus_bus_get(DBUS_BUS_SYSTEM, &error )) == NULL) { qWarning() << "Failed to initialize DBus"; } pkContext = polkit_context_new (); polkit_context_set_io_watch_functions (pkContext, io_add_watch, io_remove_watch); polkit_context_set_config_changed (pkContext, pk_config_changed, this); pk_error = NULL; if (!polkit_context_init (pkContext, &pk_error)) { qWarning() << "Failed to initialize PolicyKit context: " << polkit_error_get_error_message (pk_error); m_lastError = polkit_error_get_error_message (pk_error); m_hasError = true; if (pkContext != NULL) { polkit_context_unref(pkContext); } polkit_error_free (pk_error); return; } /* TODO FIXME: I'm pretty sure dbus-glib blows in a way that * we can't say we're interested in all signals from all * members on all interfaces for a given service... So we do * this.. */ dbus_error_init (&dbus_error); // /* need to listen to NameOwnerChanged */ // dbus_bus_add_match (m_systemBus, // "type='signal'" // ",interface='"DBUS_INTERFACE_DBUS"'" // ",sender='"DBUS_SERVICE_DBUS"'" // ",member='NameOwnerChanged'", // &dbus_error); if (QDBusConnection::systemBus().connect( DBUS_SERVICE_DBUS, QString(), DBUS_INTERFACE_DBUS, "NameOwnerChanged", this, SLOT(dbusFilter(const QDBusMessage &)))) { qWarning() << "---------------------OK"; } else { qWarning() << "---------------------not Ok"; } // if (dbus_error_is_set (&dbus_error)) { // // dbus_set_g_error (error, &dbus_error); // dbus_error_free (&dbus_error); // m_hasError = true; // qWarning() << "Failed to initialize NameOwnerChanged"; // return; // // goto error; // } // // Ok, let's get what we need here QStringList sigs; sigs += getSignals(introspect("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Manager", QDBusConnection::systemBus())); sigs += getSignals(introspect("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Session1", QDBusConnection::systemBus())); sigs += getSignals(introspect("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Seat1", QDBusConnection::systemBus())); foreach (const QString &sig, sigs) { if (QDBusConnection::systemBus().connect("org.freedesktop.ConsoleKit", QString(), "org.freedesktop.ConsoleKit", sig, this, SLOT(dbusFilter(const QDBusMessage &)))) { qWarning() << "---------------------OK"; } else { qWarning() << "---------------------not Ok"; } } /* need to listen to ConsoleKit signals */ // dbus_bus_add_match (m_systemBus, // "type='signal',sender='org.freedesktop.ConsoleKit'", // &dbus_error); // if (dbus_error_is_set (&dbus_error)) { // dbus_set_g_error (error, &dbus_error); dbus_error_free (&dbus_error); qWarning() << "Failed to initialize ConsoleKit"; m_hasError = true; return; } // // if (!dbus_connection_add_filter (m_systemBus, // filter, // this, // NULL)) { // // *error = g_error_new_literal (POLKIT_GNOME_CONTEXT_ERROR, // // POLKIT_GNOME_CONTEXT_ERROR_FAILED, // // "Cannot add D-Bus filter"); // // goto error; // qWarning() << "Failed to dbus_connection_add_filter"; // m_hasError = true; // return; // } // DBusConnection *con; // con = dbus_bus_get(DBUS_BUS_SYSTEM, &dbus_error); pkTracker = polkit_tracker_new(); polkit_tracker_set_system_bus_connection(pkTracker, m_systemBus); if (dbus_error_is_set (&dbus_error)) { m_hasError = true; m_lastError = QString("DBus error name: %1. message: %2").arg(dbus_error.name).arg(dbus_error.message); if (pkContext != NULL) { polkit_context_unref(pkContext); } if (pkTracker != NULL) { polkit_tracker_unref(pkTracker); } dbus_error_free (&dbus_error); return; } polkit_tracker_init (pkTracker); m_lastError.clear(); m_hasError = false; } void Context::dbusFilter(const QDBusMessage &message) { qDebug() << "=============================================" << message.service(); qDebug() << message.path(); qDebug() << message.interface() << DBUS_INTERFACE_DBUS; qDebug() << message.member(); // forward only NameOwnerChanged and ConsoleKit signals to PolkitTracker if ((message.type() == QDBusMessage::SignalMessage && message.interface() == "org.freedesktop.DBus" && message.member() == "NameOwnerChanged") || (!message.interface().isEmpty() && message.interface().startsWith("org.freedesktop.ConsoleKit")) ) { qDebug() << "inside"; DBusMessage *msg = 0; msg = dbus_message_new_method_call(message.service().toUtf8().data(), message.path().toUtf8().data(), message.interface().toUtf8().data(), message.member().toUtf8().data()); if (msg && polkit_tracker_dbus_func(pkTracker, msg)) { qDebug() << "++++++++++++++++++++++ EMIT CONSOLE_KIT_DB_CHANGED"; emit consoleKitDBChanged(); } } qDebug() << "====================END======================" << message.service(); } bool Context::hasError() { if (m_hasError) { // try init again maybe something get // back to normal (as DBus might restarted, crashed...) init(); } return m_hasError; } QString Context::lastError() const { return m_lastError; } int Context::io_add_watch(PolKitContext *context, int fd) { qDebug() << "add_watch" << context << fd; QSocketNotifier *notify = new QSocketNotifier(fd, QSocketNotifier::Read, Context::instance()); Context::instance()->m_watches[fd] = notify; notify->connect(notify, SIGNAL(activated(int)), Context::instance(), SLOT(watchActivatedContext(int))); return fd; // use simply the fd as the unique id for the watch } void Context::watchActivatedContext(int fd) { Q_ASSERT(m_watches.contains(fd)); // kDebug() << "watchActivated" << fd; polkit_context_io_func(pkContext, fd); } void Context::io_remove_watch(PolKitContext *context, int id) { Q_ASSERT(id > 0); qDebug() << "remove_watch" << context << id; if (!Context::instance()->m_watches.contains(id)) return; // policykit likes to do this more than once QSocketNotifier *notify = Context::instance()->m_watches.take(id); notify->deleteLater(); notify->setEnabled(false); } void Context::pk_config_changed(PolKitContext *context, void *user_data) { Q_UNUSED(context); Q_UNUSED(user_data); qDebug() << "PolicyKit reports that the config have changed"; emit Context::instance()->configChanged(); } QDomDocument Context::introspect(const QString &service, const QString &path, const QDBusConnection &c) { QDomDocument doc; QDBusInterface iface(service, path, "org.freedesktop.DBus.Introspectable", c); if (!iface.isValid()) { QDBusError err(iface.lastError()); /*emit busError(QString("Cannot introspect object %1 at %2:\n %3 (%4)\n").arg(path).arg( service).arg(err.name()).arg(err.message()));*/ return doc; } QDBusReply<QString> xml = iface.call("Introspect"); if (!xml.isValid()) { QDBusError err(xml.error()); if (err.isValid()) { /*emit busError(QString("Call to object %1 at %2:\n %3 (%4) failed\n").arg( path).arg(service).arg(err.name()).arg(err.message()));*/ } else { /*emit busError(QString("Invalid XML received from object %1 at %2\n").arg( path).arg(service));*/ } return doc; } doc.setContent(xml); return doc; } QStringList Context::getSignals(const QDomDocument &doc) { QStringList retlist; QDomElement node = doc.documentElement(); QDomElement child = node.firstChildElement(); while (!child.isNull()) { if (child.tagName() == QLatin1String("node") || child.tagName() == QLatin1String("interface")) { QDomElement iface = child.firstChildElement(); while (!iface.isNull()) { if (iface.tagName() == QLatin1String("signal")) { qDebug() << "Found signal: " << iface.attribute("name"); retlist.append(iface.attribute("name")); } iface = iface.nextSiblingElement(); } } child = child.nextSiblingElement(); } return retlist; } #include "polkit_qt_context.moc" <commit_msg>Showing errors<commit_after>/* * This file is part of the Polkit-qt project * Copyright (C) 2009 Daniel Nicoletti <dantti85-pk@yahoo.com.br> * * 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 "polkit_qt_context.h" #include "polkit_qt_singleton.h" #include <QtCore/QSocketNotifier> #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QStringList> #include <QtDBus/QDBusInterface> #include <QtDBus/QDBusReply> #include <polkit-dbus/polkit-dbus.h> using namespace QPolicyKit; class ContextHelper { public: ContextHelper() : q(0) {} ~ContextHelper() { delete q; } Context *q; }; POLKIT_QT_GLOBAL_STATIC(ContextHelper, s_globalContext) Context *Context::instance() { if (!s_globalContext->q) { new Context; } return s_globalContext->q; } // I'm using null instead of 0 as polkit will return // NULL on failures Context::Context(QObject *parent) : QObject(parent) , pkContext(NULL) , pkTracker(NULL) , m_hasError(false) { Q_ASSERT(!s_globalContext->q); s_globalContext->q = this; qDebug() << "Context - Constructing singleton"; init(); } Context::~Context() { if (pkContext != NULL) { polkit_context_unref(pkContext); } if (pkTracker != NULL) { polkit_tracker_unref(pkTracker); } } void Context::init() { DBusError error; DBusError dbus_error; PolKitError *pk_error; dbus_error_init(&error); // if ((_singleton->priv->system_bus = dbus_g_bus_get (DBUS_BUS_SYSTEM, error)) == NULL) { // goto error; // } if ((m_systemBus = dbus_bus_get(DBUS_BUS_SYSTEM, &error )) == NULL) { qWarning() << "Failed to initialize DBus"; } pkContext = polkit_context_new (); polkit_context_set_io_watch_functions (pkContext, io_add_watch, io_remove_watch); polkit_context_set_config_changed (pkContext, pk_config_changed, this); pk_error = NULL; if (!polkit_context_init (pkContext, &pk_error)) { qWarning() << "Failed to initialize PolicyKit context: " << polkit_error_get_error_message (pk_error); m_lastError = polkit_error_get_error_message (pk_error); m_hasError = true; if (pkContext != NULL) { polkit_context_unref(pkContext); } polkit_error_free (pk_error); return; } /* TODO FIXME: I'm pretty sure dbus-glib blows in a way that * we can't say we're interested in all signals from all * members on all interfaces for a given service... So we do * this.. */ dbus_error_init (&dbus_error); // /* need to listen to NameOwnerChanged */ // dbus_bus_add_match (m_systemBus, // "type='signal'" // ",interface='"DBUS_INTERFACE_DBUS"'" // ",sender='"DBUS_SERVICE_DBUS"'" // ",member='NameOwnerChanged'", // &dbus_error); if (QDBusConnection::systemBus().connect( DBUS_SERVICE_DBUS, QString(), DBUS_INTERFACE_DBUS, "NameOwnerChanged", this, SLOT(dbusFilter(const QDBusMessage &)))) { qWarning() << "---------------------OK"; } else { qWarning() << "---------------------not Ok"; } // if (dbus_error_is_set (&dbus_error)) { // // dbus_set_g_error (error, &dbus_error); // dbus_error_free (&dbus_error); // m_hasError = true; // qWarning() << "Failed to initialize NameOwnerChanged"; // return; // // goto error; // } // // Ok, let's get what we need here QStringList sigs; sigs += getSignals(introspect("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Manager", QDBusConnection::systemBus())); sigs += getSignals(introspect("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Session1", QDBusConnection::systemBus())); sigs += getSignals(introspect("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Seat1", QDBusConnection::systemBus())); foreach (const QString &sig, sigs) { if (QDBusConnection::systemBus().connect("org.freedesktop.ConsoleKit", QString(), "org.freedesktop.ConsoleKit", sig, this, SLOT(dbusFilter(const QDBusMessage &)))) { qWarning() << "---------------------OK"; } else { qWarning() << "---------------------not Ok"; } } /* need to listen to ConsoleKit signals */ // dbus_bus_add_match (m_systemBus, // "type='signal',sender='org.freedesktop.ConsoleKit'", // &dbus_error); // if (dbus_error_is_set (&dbus_error)) { // dbus_set_g_error (error, &dbus_error); dbus_error_free (&dbus_error); qWarning() << "Failed to initialize ConsoleKit"; m_hasError = true; return; } // // if (!dbus_connection_add_filter (m_systemBus, // filter, // this, // NULL)) { // // *error = g_error_new_literal (POLKIT_GNOME_CONTEXT_ERROR, // // POLKIT_GNOME_CONTEXT_ERROR_FAILED, // // "Cannot add D-Bus filter"); // // goto error; // qWarning() << "Failed to dbus_connection_add_filter"; // m_hasError = true; // return; // } // DBusConnection *con; // con = dbus_bus_get(DBUS_BUS_SYSTEM, &dbus_error); pkTracker = polkit_tracker_new(); polkit_tracker_set_system_bus_connection(pkTracker, m_systemBus); if (dbus_error_is_set (&dbus_error)) { m_hasError = true; m_lastError = QString("DBus error name: %1. message: %2").arg(dbus_error.name).arg(dbus_error.message); if (pkContext != NULL) { polkit_context_unref(pkContext); } if (pkTracker != NULL) { polkit_tracker_unref(pkTracker); } dbus_error_free (&dbus_error); return; } polkit_tracker_init (pkTracker); m_lastError.clear(); m_hasError = false; } void Context::dbusFilter(const QDBusMessage &message) { qDebug() << "=============================================" << message.service(); qDebug() << message.path(); qDebug() << message.interface() << DBUS_INTERFACE_DBUS; qDebug() << message.member(); // forward only NameOwnerChanged and ConsoleKit signals to PolkitTracker if ((message.type() == QDBusMessage::SignalMessage && message.interface() == "org.freedesktop.DBus" && message.member() == "NameOwnerChanged") || (!message.interface().isEmpty() && message.interface().startsWith("org.freedesktop.ConsoleKit")) ) { qDebug() << "inside"; DBusMessage *msg = 0; msg = dbus_message_new_method_call(message.service().toUtf8().data(), message.path().toUtf8().data(), message.interface().toUtf8().data(), message.member().toUtf8().data()); if (msg && polkit_tracker_dbus_func(pkTracker, msg)) { qDebug() << "++++++++++++++++++++++ EMIT CONSOLE_KIT_DB_CHANGED"; emit consoleKitDBChanged(); } } qDebug() << "====================END======================" << message.service(); } bool Context::hasError() { if (m_hasError) { // try init again maybe something get // back to normal (as DBus might restarted, crashed...) init(); } return m_hasError; } QString Context::lastError() const { return m_lastError; } int Context::io_add_watch(PolKitContext *context, int fd) { qDebug() << "add_watch" << context << fd; QSocketNotifier *notify = new QSocketNotifier(fd, QSocketNotifier::Read, Context::instance()); Context::instance()->m_watches[fd] = notify; notify->connect(notify, SIGNAL(activated(int)), Context::instance(), SLOT(watchActivatedContext(int))); return fd; // use simply the fd as the unique id for the watch } void Context::watchActivatedContext(int fd) { Q_ASSERT(m_watches.contains(fd)); // kDebug() << "watchActivated" << fd; polkit_context_io_func(pkContext, fd); } void Context::io_remove_watch(PolKitContext *context, int id) { Q_ASSERT(id > 0); qDebug() << "remove_watch" << context << id; if (!Context::instance()->m_watches.contains(id)) return; // policykit likes to do this more than once QSocketNotifier *notify = Context::instance()->m_watches.take(id); notify->deleteLater(); notify->setEnabled(false); } void Context::pk_config_changed(PolKitContext *context, void *user_data) { Q_UNUSED(context); Q_UNUSED(user_data); qDebug() << "PolicyKit reports that the config have changed"; emit Context::instance()->configChanged(); } QDomDocument Context::introspect(const QString &service, const QString &path, const QDBusConnection &c) { QDomDocument doc; QDBusInterface iface(service, path, "org.freedesktop.DBus.Introspectable", c); if (!iface.isValid()) { QDBusError err(iface.lastError()); qDebug() << QString("Cannot introspect object %1 at %2:\n %3 (%4)\n").arg(path).arg( service).arg(err.name()).arg(err.message()); return doc; } QDBusReply<QString> xml = iface.call("Introspect"); if (!xml.isValid()) { QDBusError err(xml.error()); if (err.isValid()) { qDebug() << QString("Call to object %1 at %2:\n %3 (%4) failed\n").arg( path).arg(service).arg(err.name()).arg(err.message()); } else { qDebug() << QString("Invalid XML received from object %1 at %2\n").arg( path).arg(service); } return doc; } doc.setContent(xml); return doc; } QStringList Context::getSignals(const QDomDocument &doc) { QStringList retlist; QDomElement node = doc.documentElement(); QDomElement child = node.firstChildElement(); while (!child.isNull()) { if (child.tagName() == QLatin1String("node") || child.tagName() == QLatin1String("interface")) { QDomElement iface = child.firstChildElement(); while (!iface.isNull()) { if (iface.tagName() == QLatin1String("signal")) { qDebug() << "Found signal: " << iface.attribute("name"); retlist.append(iface.attribute("name")); } iface = iface.nextSiblingElement(); } } child = child.nextSiblingElement(); } return retlist; } #include "polkit_qt_context.moc" <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include <osvr/Common/PathTreeSerialization.h> #include <osvr/Common/PathTreeFull.h> #include <osvr/Common/PathElementTools.h> #include <osvr/Common/PathNode.h> #include <osvr/Common/ApplyPathNodeVisitor.h> #include <osvr/Util/Verbosity.h> // Library/third-party includes #include <json/value.h> #include <json/reader.h> #include <boost/variant.hpp> #include <boost/mpl/for_each.hpp> // Standard includes #include <type_traits> namespace osvr { namespace common { namespace { /// @brief "using" statement to combine/simplify the enable_if test for /// an element type's serialization. template <typename Input, typename Known> using enable_if_element_type = std::enable_if_t< std::is_same<std::remove_const_t<Input>, Known>::value>; /// The serializationHandler function templates allow serialization /// and deserialization code to be generated from the same operations /// (ensuring keys stay in sync, etc.) /// @brief Serialization handler for DeviceElement template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::DeviceElement> serializationHandler(Functor &f, ValType &value) { f("device_name", value.getDeviceName()); f("server", value.getServer()); f("descriptor", value.getDescriptor()); } /// @brief Serialization handler for AliasElement template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::AliasElement> serializationHandler(Functor &f, ValType &value) { f("source", value.getSource()); f("priority", value.priority(), ALIASPRIORITY_MINIMUM /* default value */); } /// @brief Serialization handler for StringElement template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::StringElement> serializationHandler(Functor &f, ValType &value) { f("string", value.getString()); } // Serialization handlers for elements without extra data template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::NullElement> serializationHandler(Functor &, ValType &) {} template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::PluginElement> serializationHandler(Functor &, ValType &) {} template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::InterfaceElement> serializationHandler(Functor &, ValType &) {} template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::SensorElement> serializationHandler(Functor &, ValType &) {} /// @brief Functor for use with PathElementSerializationHandler, for the /// direction PathElement->JSON class PathElementToJSONFunctor : boost::noncopyable { public: PathElementToJSONFunctor(Json::Value &val) : m_val(val) {} template <typename T> void operator()(const char name[], T const &data, ...) { m_val[name] = data; } private: Json::Value &m_val; }; /// @brief A PathNodeVisitor that returns a JSON object corresponding to /// a single PathNode. class PathNodeToJsonVisitor : public boost::static_visitor<Json::Value> { public: PathNodeToJsonVisitor() : boost::static_visitor<Json::Value>() {} Json::Value setup(PathNode const &node) { Json::Value val{Json::objectValue}; val["path"] = getFullPath(node); val["type"] = getTypeName(node); return val; } template <typename T> Json::Value operator()(PathNode const &node, T const &elt) { auto ret = setup(node); PathElementToJSONFunctor f(ret); serializationHandler(f, elt); return ret; } }; Json::Value pathNodeToJson(PathNode const &node) { PathNodeToJsonVisitor visitor; return applyPathNodeVisitor(visitor, node); } /// @brief A PathNode (tree) visitor to recursively convert nodes in a /// PathTree to JSON class PathTreeToJsonVisitor { public: PathTreeToJsonVisitor(bool keepNulls) : m_ret(Json::arrayValue), m_keepNulls(keepNulls) {} Json::Value getResult() { return m_ret; } void operator()(PathNode const &node) { if (m_keepNulls || !elements::isNull(node.value())) { // If we're keeping nulls or this isn't a null... m_ret.append(pathNodeToJson(node)); } // Recurse on children node.visitConstChildren(*this); } private: Json::Value m_ret; bool m_keepNulls; }; /// @brief Functor for use with PathElementSerializationHandler, for the /// direction JSON->PathElement class PathElementFromJsonFunctor : boost::noncopyable { public: PathElementFromJsonFunctor(Json::Value const &val) : m_val(val) {} void operator()(const char name[], std::string &dataRef) { m_requireName(name); dataRef = m_val[name].asString(); } void operator()(const char name[], bool &dataRef) { m_requireName(name); dataRef = m_val[name].asBool(); } void operator()(const char name[], Json::Value &dataRef) { m_requireName(name); if (m_val[name].isString()) { Json::Reader reader; Json::Value val; if (reader.parse(m_val[name].asString(), val)) { dataRef = val; } } else { dataRef = m_val[name]; } } void operator()(const char name[], bool &dataRef, bool defaultVal) { if (m_hasName(name)) { dataRef = m_val[name].asBool(); } else { dataRef = defaultVal; } } void operator()(const char name[], uint8_t &dataRef, uint8_t defaultVal) { if (m_hasName(name)) { dataRef = static_cast<uint8_t>(m_val[name].asInt()); } else { dataRef = defaultVal; } } /// @todo add more methods here if other data types are stored private: void m_requireName(const char name[]) { if (!m_hasName(name)) { throw std::runtime_error( "Missing JSON object member named " + std::string(name)); } } bool m_hasName(const char name[]) { return m_val.isMember(name); } Json::Value const &m_val; }; /// @brief Functor for use with the PathElement's type list and /// mpl::for_each, to convert from type name string to actual type and /// load the data. class DeserializeElementFunctor { public: DeserializeElementFunctor(Json::Value const &val, elements::PathElement &elt) : m_val(val), m_typename(val["type"].asString()), m_elt(elt) {} /// @brief Don't try to generate an assignment operator. DeserializeElementFunctor & operator=(const DeserializeElementFunctor &) = delete; template <typename T> void operator()(T const &) { if (elements::getTypeName<T>() == m_typename) { T value; PathElementFromJsonFunctor functor(m_val); serializationHandler(functor, value); m_elt = value; } } private: Json::Value const &m_val; std::string const m_typename; elements::PathElement &m_elt; }; } // namespace Json::Value pathTreeToJson(PathTree &tree, bool keepNulls) { auto visitor = PathTreeToJsonVisitor{keepNulls}; tree.visitConstTree(visitor); return visitor.getResult(); } void jsonToPathTree(PathTree &tree, Json::Value nodes) { for (auto const &node : nodes) { elements::PathElement elt; DeserializeElementFunctor functor{node, elt}; boost::mpl::for_each<elements::PathElement::types>(functor); tree.getNodeByPath(node["path"].asString()).value() = elt; } } } // namespace common } // namespace osvr<commit_msg>Clean up and comment path tree serialization<commit_after>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include <osvr/Common/PathTreeSerialization.h> #include <osvr/Common/PathTreeFull.h> #include <osvr/Common/PathElementTools.h> #include <osvr/Common/PathNode.h> #include <osvr/Common/ApplyPathNodeVisitor.h> #include <osvr/Util/Verbosity.h> // Library/third-party includes #include <json/value.h> #include <json/reader.h> #include <boost/variant.hpp> #include <boost/mpl/for_each.hpp> // Standard includes #include <type_traits> namespace osvr { namespace common { namespace { /// @brief "using" statement to combine/simplify the enable_if test for /// an element type's serialization. template <typename Input, typename Known> using enable_if_element_type = std::enable_if_t< std::is_same<std::remove_const_t<Input>, Known>::value>; /// The serializationHandler function templates allow serialization /// and deserialization code to be generated from the same operations /// (ensuring keys stay in sync, etc.) /// @brief Serialization handler for DeviceElement template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::DeviceElement> serializationHandler(Functor &f, ValType &value) { f("device_name", value.getDeviceName()); f("server", value.getServer()); f("descriptor", value.getDescriptor()); } /// @brief Serialization handler for AliasElement template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::AliasElement> serializationHandler(Functor &f, ValType &value) { f("source", value.getSource()); f("priority", value.priority()); } /// @brief Serialization handler for StringElement template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::StringElement> serializationHandler(Functor &f, ValType &value) { f("string", value.getString()); } // Serialization handlers for elements without extra data template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::NullElement> serializationHandler(Functor &, ValType &) {} template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::PluginElement> serializationHandler(Functor &, ValType &) {} template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::InterfaceElement> serializationHandler(Functor &, ValType &) {} template <typename Functor, typename ValType> inline enable_if_element_type<ValType, elements::SensorElement> serializationHandler(Functor &, ValType &) {} /// @brief Functor for use with PathElementSerializationHandler, for the /// direction PathElement->JSON class PathElementToJSONFunctor : boost::noncopyable { public: PathElementToJSONFunctor(Json::Value &val) : m_val(val) {} template <typename T> void operator()(const char name[], T const &data, ...) { m_val[name] = data; } private: Json::Value &m_val; }; /// @brief A PathNodeVisitor that returns a JSON object corresponding to /// a single PathNode. class PathNodeToJsonVisitor : public boost::static_visitor<Json::Value> { public: PathNodeToJsonVisitor() : boost::static_visitor<Json::Value>() {} Json::Value setup(PathNode const &node) { Json::Value val{Json::objectValue}; val["path"] = getFullPath(node); val["type"] = getTypeName(node); return val; } template <typename T> Json::Value operator()(PathNode const &node, T const &elt) { auto ret = setup(node); PathElementToJSONFunctor f(ret); serializationHandler(f, elt); return ret; } }; Json::Value pathNodeToJson(PathNode const &node) { PathNodeToJsonVisitor visitor; return applyPathNodeVisitor(visitor, node); } /// @brief A PathNode (tree) visitor to recursively convert nodes in a /// PathTree to JSON class PathTreeToJsonVisitor { public: PathTreeToJsonVisitor(bool keepNulls) : m_ret(Json::arrayValue), m_keepNulls(keepNulls) {} Json::Value getResult() { return m_ret; } void operator()(PathNode const &node) { if (m_keepNulls || !elements::isNull(node.value())) { // If we're keeping nulls or this isn't a null... m_ret.append(pathNodeToJson(node)); } // Recurse on children node.visitConstChildren(*this); } private: Json::Value m_ret; bool m_keepNulls; }; /// @brief Functor for use with a serializationHandler overload, for the /// direction JSON->PathElement class PathElementFromJsonFunctor : boost::noncopyable { public: PathElementFromJsonFunctor(Json::Value const &val) : m_val(val) {} /// @brief Deserialize a string void operator()(const char name[], std::string &dataRef) { m_requireName(name); dataRef = m_val[name].asString(); } /// @brief Deserialize a bool void operator()(const char name[], bool &dataRef) { m_requireName(name); dataRef = m_val[name].asBool(); } /// @brief Deserialize a bool with default void operator()(const char name[], bool &dataRef, bool defaultVal) { if (m_hasName(name)) { dataRef = m_val[name].asBool(); } else { dataRef = defaultVal; } } /// @brief Deserialize a Json::Value from either nested JSON or a /// JSON string void operator()(const char name[], Json::Value &dataRef) { m_requireName(name); if (m_val[name].isString()) { Json::Reader reader; Json::Value val; if (reader.parse(m_val[name].asString(), val)) { dataRef = val; } } else { dataRef = m_val[name]; } } /// @brief Deserialize a uint8_t (e.g. AliasPriority) void operator()(const char name[], uint8_t &dataRef) { m_requireName(name); dataRef = static_cast<uint8_t>(m_val[name].asInt()); } /// @brief Deserialize a uint8_t (e.g. AliasPriority) with default void operator()(const char name[], uint8_t &dataRef, uint8_t defaultVal) { if (m_hasName(name)) { dataRef = static_cast<uint8_t>(m_val[name].asInt()); } else { dataRef = defaultVal; } } /// @todo add more methods here if other data types are stored private: void m_requireName(const char name[]) { if (!m_hasName(name)) { throw std::runtime_error( "Missing JSON object member named " + std::string(name)); } } bool m_hasName(const char name[]) { return m_val.isMember(name); } Json::Value const &m_val; }; /// @brief Functor for use with the PathElement's type list and /// mpl::for_each, to convert from type name string to actual type and /// load the data. class DeserializeElementFunctor { public: DeserializeElementFunctor(Json::Value const &val, elements::PathElement &elt) : m_val(val), m_typename(val["type"].asString()), m_elt(elt) {} /// @brief Don't try to generate an assignment operator. DeserializeElementFunctor & operator=(const DeserializeElementFunctor &) = delete; template <typename T> void operator()(T const &) { if (elements::getTypeName<T>() == m_typename) { T value; PathElementFromJsonFunctor functor(m_val); serializationHandler(functor, value); m_elt = value; } } private: Json::Value const &m_val; std::string const m_typename; elements::PathElement &m_elt; }; } // namespace Json::Value pathTreeToJson(PathTree &tree, bool keepNulls) { auto visitor = PathTreeToJsonVisitor{keepNulls}; tree.visitConstTree(visitor); return visitor.getResult(); } void jsonToPathTree(PathTree &tree, Json::Value nodes) { for (auto const &node : nodes) { elements::PathElement elt; DeserializeElementFunctor functor{node, elt}; boost::mpl::for_each<elements::PathElement::types>(functor); tree.getNodeByPath(node["path"].asString()).value() = elt; } } } // namespace common } // namespace osvr<|endoftext|>
<commit_before>// Copyright (c) 2014 Google, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // FarmHash, by Geoff Pike // // TODO: Add license, Google's license, readme, and new copyright. #include "FarmHash.hpp" #include <cstring> #include <algorithm> // --------------------------------------------------------------------- namespace { // Give hints to the optimizer (even though humans are notoriously bad at doing so). #if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER) inline bool IsLikely ( const bool x ) { return __builtin_expect(x, true ); } inline bool IsUnlikely( const bool x ) { return __builtin_expect(x, false); } #else inline bool IsLikely ( const bool x ) { return x; } inline bool IsUnlikely( const bool x ) { return x; } #endif // Byte-order independent fetching. inline uint64_t Fetch64(const uint8_t *p) { uint64_t result; std::memcpy(&result, p, sizeof(result)); return uint64_in_little_endian_order(result); } inline uint32_t Fetch32(const uint8_t *p) { uint32_t result; std::memcpy(&result, p, sizeof(result)); return uint32_in_little_endian_order(result); } // Byteswapping functions. inline uint32_t ByteSwap32(uint32_t value) { return bswap_32(value); } inline uint64_t ByteSwap64(uint64_t value) { return bswap_64(value); } #if defined(_MSC_VER) inline uint32_t RotateRight32(uint32_t value, int shift) { return _rotr (value, shift); } inline uint64_t RotateRight64(uint64_t value, int shift) { return _rotr64(value, shift); } #else // modern compilers automatically get this right, with no 'undefined' behaviour (https://goo.gl/ZsFpuz) inline uint32_t RotateRight32(uint32_t value, unsigned shift) { shift &= 31; return (value >> shift) | (value << (32 - shift)); } inline uint64_t RotateRight64(uint64_t value, unsigned shift) { shift &= 63; return (value >> shift) | (value << (64 - shift)); } #endif } namespace FarmHash { namespace { inline uint64_t Fetch(const uint8_t *p) { return Fetch64(p); } inline uint64_t RotateRight(uint64_t value, int shift) { return RotateRight64(value, shift); } inline uint64_t ByteSwap(uint64_t value) { return ByteSwap64(value); } // Some primes between 2^63 and 2^64 for various uses. const uint64_t k0 = 0xc3a5c85c97cb3127ULL; const uint64_t k1 = 0xb492b66fbe98f273ULL; const uint64_t k2 = 0x9ae16a3b2f90404fULL; // Murmur-inspired hashing and suboperations. inline uint64_t Hash128to64(UInt128 x) { const uint64_t kMul = 0x9ddfea08eb382d69ULL; uint64_t a = (UInt128Low64(x) ^ UInt128High64(x)) * kMul; a ^= (a >> 47); uint64_t b = (UInt128High64(x) ^ a) * kMul; b ^= (b >> 47); b *= kMul; return b; } inline uint64_t ShiftMix(uint64_t value) { return value ^ (value >> 47); } inline uint64_t HashLen16(uint64_t u, uint64_t v) { return Hash128to64(UInt128(u, v)); } inline uint64_t HashLen16(uint64_t u, uint64_t v, uint64_t mul) { uint64_t a = (u ^ v) * mul; a ^= (a >> 47); uint64_t b = (v ^ a) * mul; b ^= (b >> 47); b *= mul; return b; } inline uint64_t HashLen0to16(const uint8_t *s, size_t len) { if (len >= 8) { uint64_t mul = k2 + len * 2; uint64_t a = Fetch(s) + k2; uint64_t b = Fetch(s + len - 8); uint64_t c = RotateRight(b, 37) * mul + a; uint64_t d = (RotateRight(a, 25) + b) * mul; return HashLen16(c, d, mul); } if (len >= 4) { uint64_t mul = k2 + len * 2; uint64_t a = Fetch32(s); return HashLen16(len + (a << 3), Fetch32(s + len - 4), mul); } if (len > 0) { uint8_t a = s[0]; uint8_t b = s[len >> 1]; uint8_t c = s[len - 1]; uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8); uint32_t z = len + (static_cast<uint32_t>(c) << 2); return ShiftMix(y * k2 ^ z * k0) * k2; } return k2; } // Return a 16-byte hash for 48 bytes. Quick and dirty. // Callers do best to use "random-looking" value for a and b. inline std::pair<uint64_t,uint64_t> WeakHashLen32WithSeeds(uint64_t w, uint64_t x, uint64_t y, uint64_t z, uint64_t a, uint64_t b) { a += w; b = RotateRight(b + a + z, 21); uint64_t c = a; a += x; a += y; b += RotateRight(a, 44); return std::make_pair(a + z, b + c); } // Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty. inline std::pair<uint64_t,uint64_t> WeakHashLen32WithSeeds(const uint8_t *s, uint64_t a, uint64_t b) { return WeakHashLen32WithSeeds(Fetch(s), Fetch(s + 8), Fetch(s + 16), Fetch(s + 24), a, b); } // A subroutine for CityHash128(). Returns a decent 128-bit hash for strings // of any length representable in signed long. Based on City and Murmur. inline UInt128 CityMurmur(const uint8_t *s, size_t len, UInt128 seed) { uint64_t a = UInt128Low64(seed); uint64_t b = UInt128High64(seed); uint64_t c = 0; uint64_t d = 0; signed long l = len - 16; if (l <= 0) { // len <= 16 a = ShiftMix(a * k1) * k1; c = b * k1 + HashLen0to16(s, len); d = ShiftMix(a + (len >= 8 ? Fetch(s) : c)); } else { // len > 16 c = HashLen16(Fetch(s + len - 8) + k1, a); d = HashLen16(b + len, c + Fetch(s + len - 16)); a += d; do { a ^= ShiftMix(Fetch(s) * k1) * k1; a *= k1; b ^= a; c ^= ShiftMix(Fetch(s + 8) * k1) * k1; c *= k1; d ^= c; s += 16; l -= 16; } while (l > 0); } a = HashLen16(a, c); b = HashLen16(d, b); return UInt128(a ^ b, HashLen16(b, a)); } } UInt128 CityHash128WithSeed(const uint8_t *s, size_t len, UInt128 seed) { // We expect len >= 128 to be the common case. if (IsUnlikely(len < 128)) { return CityMurmur(s, len, seed); } // Keep 56 bytes of state: v, w, x, y, and z. std::pair<uint64_t,uint64_t> v, w; uint64_t x = UInt128Low64(seed); uint64_t y = UInt128High64(seed); uint64_t z = len * k1; v.first = RotateRight(y ^ k1, 49) * k1 + Fetch(s); v.second = RotateRight(v.first, 42) * k1 + Fetch(s + 8); w.first = RotateRight(y + z, 35) * k1 + x; w.second = RotateRight(x + Fetch(s + 88), 53) * k1; // This is the same inner loop as CityHash64(), manually unrolled. do { x = RotateRight(x + y + v.first + Fetch(s + 8), 37) * k1; y = RotateRight(y + v.second + Fetch(s + 48), 42) * k1; x ^= w.second; y += v.first + Fetch(s + 40); z = RotateRight(z + w.first, 33) * k1; v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + Fetch(s + 16)); std::swap(z, x); s += 64; x = RotateRight(x + y + v.first + Fetch(s + 8), 37) * k1; y = RotateRight(y + v.second + Fetch(s + 48), 42) * k1; x ^= w.second; y += v.first + Fetch(s + 40); z = RotateRight(z + w.first, 33) * k1; v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + Fetch(s + 16)); std::swap(z, x); s += 64; len -= 128; } while (IsLikely(len >= 128)); x += RotateRight(v.first + z, 49) * k0; y = y * k0 + RotateRight(w.second, 37); z = z * k0 + RotateRight(w.first, 27); w.first *= 9; v.first *= k0; // If 0 < len < 128, hash up to 4 chunks of 32 bytes each from the end of s. for (size_t tail_done = 0; tail_done < len; ) { tail_done += 32; y = RotateRight(x + y, 42) * k0 + v.second; w.first += Fetch(s + len - tail_done + 16); x = x * k0 + w.first; z += w.second + Fetch(s + len - tail_done); w.second += v.first; v = WeakHashLen32WithSeeds(s + len - tail_done, v.first + z, v.second); v.first *= k0; } // At this point our 56 bytes of state should contain more than // enough information for a strong 128-bit hash. We use two // different 56-byte-to-8-byte hashes to get a 16-byte final result. x = HashLen16(x, v.first); y = HashLen16(y + z, w.first); return UInt128(HashLen16(x + v.second, w.second) + y, HashLen16(x + w.second, y + v.second)); } UInt128 CityHash128(const uint8_t *s, size_t len) { return len >= 16 ? CityHash128WithSeed(s + 16, len - 16, UInt128(Fetch(s), Fetch(s + 8) + k0)) : CityHash128WithSeed(s, len, UInt128(k0, k1)); } UInt128 Fingerprint128(const uint8_t *s, size_t len) { return CityHash128(s, len); } } <commit_msg>Remove unused byteswapping functions<commit_after>// Copyright (c) 2014 Google, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // FarmHash, by Geoff Pike // // TODO: Add license, Google's license, readme, and new copyright. #include "FarmHash.hpp" #include <cstring> #include <algorithm> // --------------------------------------------------------------------- namespace { // Give hints to the optimizer (even though humans are notoriously bad at doing so). #if defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER) inline bool IsLikely ( const bool x ) { return __builtin_expect(x, true ); } inline bool IsUnlikely( const bool x ) { return __builtin_expect(x, false); } #else inline bool IsLikely ( const bool x ) { return x; } inline bool IsUnlikely( const bool x ) { return x; } #endif // Byte-order independent fetching. inline uint64_t Fetch64(const uint8_t *p) { uint64_t result; std::memcpy(&result, p, sizeof(result)); return uint64_in_little_endian_order(result); } inline uint32_t Fetch32(const uint8_t *p) { uint32_t result; std::memcpy(&result, p, sizeof(result)); return uint32_in_little_endian_order(result); } // Cyclical rotation of unsigned integers. #if defined(_MSC_VER) // inline uint32_t RotateRight32(uint32_t value, int shift) { return _rotr (value, shift); } inline uint64_t RotateRight64(uint64_t value, int shift) { return _rotr64(value, shift); } #else // modern compilers automatically get this right, with no 'undefined' behaviour (https://goo.gl/ZsFpuz) // inline uint32_t RotateRight32(uint32_t value, unsigned shift) { shift &= 31; return (value >> shift) | (value << (32 - shift)); } inline uint64_t RotateRight64(uint64_t value, unsigned shift) { shift &= 63; return (value >> shift) | (value << (64 - shift)); } #endif } namespace FarmHash { namespace { inline uint64_t Fetch(const uint8_t *p) { return Fetch64(p); } inline uint64_t RotateRight(uint64_t value, int shift) { return RotateRight64(value, shift); } // inline uint64_t ByteSwap(uint64_t value) { return ByteSwap64(value); } // Some primes between 2^63 and 2^64 for various uses. const uint64_t k0 = 0xc3a5c85c97cb3127ULL; const uint64_t k1 = 0xb492b66fbe98f273ULL; const uint64_t k2 = 0x9ae16a3b2f90404fULL; // Murmur-inspired hashing and suboperations. inline uint64_t Hash128to64(UInt128 x) { const uint64_t kMul = 0x9ddfea08eb382d69ULL; uint64_t a = (UInt128Low64(x) ^ UInt128High64(x)) * kMul; a ^= (a >> 47); uint64_t b = (UInt128High64(x) ^ a) * kMul; b ^= (b >> 47); b *= kMul; return b; } inline uint64_t ShiftMix(uint64_t value) { return value ^ (value >> 47); } inline uint64_t HashLen16(uint64_t u, uint64_t v) { return Hash128to64(UInt128(u, v)); } inline uint64_t HashLen16(uint64_t u, uint64_t v, uint64_t mul) { uint64_t a = (u ^ v) * mul; a ^= (a >> 47); uint64_t b = (v ^ a) * mul; b ^= (b >> 47); b *= mul; return b; } inline uint64_t HashLen0to16(const uint8_t *s, size_t len) { if (len >= 8) { uint64_t mul = k2 + len * 2; uint64_t a = Fetch(s) + k2; uint64_t b = Fetch(s + len - 8); uint64_t c = RotateRight(b, 37) * mul + a; uint64_t d = (RotateRight(a, 25) + b) * mul; return HashLen16(c, d, mul); } if (len >= 4) { uint64_t mul = k2 + len * 2; uint64_t a = Fetch32(s); return HashLen16(len + (a << 3), Fetch32(s + len - 4), mul); } if (len > 0) { uint8_t a = s[0]; uint8_t b = s[len >> 1]; uint8_t c = s[len - 1]; uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8); uint32_t z = len + (static_cast<uint32_t>(c) << 2); return ShiftMix(y * k2 ^ z * k0) * k2; } return k2; } // Return a 16-byte hash for 48 bytes. Quick and dirty. // Callers do best to use "random-looking" value for a and b. inline std::pair<uint64_t,uint64_t> WeakHashLen32WithSeeds(uint64_t w, uint64_t x, uint64_t y, uint64_t z, uint64_t a, uint64_t b) { a += w; b = RotateRight(b + a + z, 21); uint64_t c = a; a += x; a += y; b += RotateRight(a, 44); return std::make_pair(a + z, b + c); } // Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty. inline std::pair<uint64_t,uint64_t> WeakHashLen32WithSeeds(const uint8_t *s, uint64_t a, uint64_t b) { return WeakHashLen32WithSeeds(Fetch(s), Fetch(s + 8), Fetch(s + 16), Fetch(s + 24), a, b); } // A subroutine for CityHash128(). Returns a decent 128-bit hash for strings // of any length representable in signed long. Based on City and Murmur. inline UInt128 CityMurmur(const uint8_t *s, size_t len, UInt128 seed) { uint64_t a = UInt128Low64(seed); uint64_t b = UInt128High64(seed); uint64_t c = 0; uint64_t d = 0; signed long l = len - 16; if (l <= 0) { // len <= 16 a = ShiftMix(a * k1) * k1; c = b * k1 + HashLen0to16(s, len); d = ShiftMix(a + (len >= 8 ? Fetch(s) : c)); } else { // len > 16 c = HashLen16(Fetch(s + len - 8) + k1, a); d = HashLen16(b + len, c + Fetch(s + len - 16)); a += d; do { a ^= ShiftMix(Fetch(s) * k1) * k1; a *= k1; b ^= a; c ^= ShiftMix(Fetch(s + 8) * k1) * k1; c *= k1; d ^= c; s += 16; l -= 16; } while (l > 0); } a = HashLen16(a, c); b = HashLen16(d, b); return UInt128(a ^ b, HashLen16(b, a)); } } UInt128 CityHash128WithSeed(const uint8_t *s, size_t len, UInt128 seed) { // We expect len >= 128 to be the common case. if (IsUnlikely(len < 128)) { return CityMurmur(s, len, seed); } // Keep 56 bytes of state: v, w, x, y, and z. std::pair<uint64_t,uint64_t> v, w; uint64_t x = UInt128Low64(seed); uint64_t y = UInt128High64(seed); uint64_t z = len * k1; v.first = RotateRight(y ^ k1, 49) * k1 + Fetch(s); v.second = RotateRight(v.first, 42) * k1 + Fetch(s + 8); w.first = RotateRight(y + z, 35) * k1 + x; w.second = RotateRight(x + Fetch(s + 88), 53) * k1; // This is the same inner loop as CityHash64(), manually unrolled. do { x = RotateRight(x + y + v.first + Fetch(s + 8), 37) * k1; y = RotateRight(y + v.second + Fetch(s + 48), 42) * k1; x ^= w.second; y += v.first + Fetch(s + 40); z = RotateRight(z + w.first, 33) * k1; v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + Fetch(s + 16)); std::swap(z, x); s += 64; x = RotateRight(x + y + v.first + Fetch(s + 8), 37) * k1; y = RotateRight(y + v.second + Fetch(s + 48), 42) * k1; x ^= w.second; y += v.first + Fetch(s + 40); z = RotateRight(z + w.first, 33) * k1; v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + Fetch(s + 16)); std::swap(z, x); s += 64; len -= 128; } while (IsLikely(len >= 128)); x += RotateRight(v.first + z, 49) * k0; y = y * k0 + RotateRight(w.second, 37); z = z * k0 + RotateRight(w.first, 27); w.first *= 9; v.first *= k0; // If 0 < len < 128, hash up to 4 chunks of 32 bytes each from the end of s. for (size_t tail_done = 0; tail_done < len; ) { tail_done += 32; y = RotateRight(x + y, 42) * k0 + v.second; w.first += Fetch(s + len - tail_done + 16); x = x * k0 + w.first; z += w.second + Fetch(s + len - tail_done); w.second += v.first; v = WeakHashLen32WithSeeds(s + len - tail_done, v.first + z, v.second); v.first *= k0; } // At this point our 56 bytes of state should contain more than // enough information for a strong 128-bit hash. We use two // different 56-byte-to-8-byte hashes to get a 16-byte final result. x = HashLen16(x, v.first); y = HashLen16(y + z, w.first); return UInt128(HashLen16(x + v.second, w.second) + y, HashLen16(x + w.second, y + v.second)); } UInt128 CityHash128(const uint8_t *s, size_t len) { return len >= 16 ? CityHash128WithSeed(s + 16, len - 16, UInt128(Fetch(s), Fetch(s + 8) + k0)) : CityHash128WithSeed(s, len, UInt128(k0, k1)); } UInt128 Fingerprint128(const uint8_t *s, size_t len) { return CityHash128(s, len); } } <|endoftext|>
<commit_before>#include "coverage.h" #include "featurecoverage.h" #include "feature.h" #include "featureiterator.h" #include "drawingcolor.h" #include "drawers/drawerfactory.h" #include "rootdrawer.h" #include "table.h" #include "range.h" #include "itemrange.h" #include "identifieritem.h" #include "identifierrange.h" #include "colorrange.h" #include "colorlookup.h" #include "itemdomain.h" #include "representation.h" #include "drawers/attributevisualproperties.h" #include "drawers/drawerattributesetter.h" #include "drawers/drawerattributesetterfactory.h" #include "drawerattributesetters/basespatialattributesetter.h" #include "featurelayerdrawer.h" #include "tesselation/ilwistesselator.h" //#include "openglhelper.h" using namespace Ilwis; using namespace Geodrawer; REGISTER_DRAWER(FeatureLayerDrawer) FeatureLayerDrawer::FeatureLayerDrawer(DrawerInterface *parentDrawer, RootDrawer *rootdrawer, const IOOptions &options) : LayerDrawer("FeatureLayerDrawer", parentDrawer, rootdrawer, options) { _vertexShader = "featurevertexshader_nvdia.glsl"; _fragmentShader = "featurefragmentshader_nvdia.glsl"; } DrawerInterface *FeatureLayerDrawer::create(DrawerInterface *parentDrawer, RootDrawer *rootdrawer, const IOOptions &options) { return new FeatureLayerDrawer(parentDrawer, rootdrawer, options) ; } void createAttributeSetter(const IFeatureCoverage& features, std::vector<std::shared_ptr<BaseSpatialAttributeSetter>>& setters, RootDrawer *rootdrawer) { QVariant v = qVariantFromValue((void *) rootdrawer); IOOptions opt("rootdrawer", v); setters[itPOINT].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplepointsetter",opt)); setters[itLINE].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplelinesetter", opt)); setters[itPOLYGON].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplepolygonsetter", opt)); for(int i=0; i < setters.size(); ++i){ if(setters[i]){ setters[i]->sourceCsySystem(features->coordinateSystem()); } } } bool FeatureLayerDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options) { if(!LayerDrawer::prepare(prepType, options)) return false; if ( hasType(prepType, ptSHADERS) && !isPrepared(ptSHADERS)){ _vboColor = _shaders.attributeLocation("vertexColor"); _scaleCenter = _shaders.uniformLocation("scalecenter"); _scaleFactor = _shaders.uniformLocation("scalefactor"); _prepared |= DrawerInterface::ptSHADERS; } if ( hasType(prepType, DrawerInterface::ptGEOMETRY) && !isPrepared(DrawerInterface::ptGEOMETRY)){ IFeatureCoverage features = coverage().as<FeatureCoverage>(); if ( !features.isValid()){ return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"FeatureCoverage", TR("Visualization")); } // set all to 0 _indices = std::vector<VertexIndex>(); _vertices = QVector<QVector3D>(); _normals = QVector<QVector3D>(); _colors = std::vector<VertexColor>(); // get a description of how to render VisualAttribute attr = visualAttribute(activeAttribute()); std::vector<std::shared_ptr<BaseSpatialAttributeSetter>> setters(5); // types are 1 2 4, for performance a vector is used thoug not all elements are used // for the moment I use the simple setters, in the future this will be representation dependent createAttributeSetter(features, setters, rootDrawer()); _featureDrawings.resize(features->featureCount()); int featureIndex = 0; for(const SPFeatureI& feature : features){ QVariant value = attr.columnIndex() != iUNDEF ? feature(attr.columnIndex()) : featureIndex; IlwisTypes geomtype = feature->geometryType(); _featureDrawings[featureIndex] = setters[geomtype]->setSpatialAttributes(feature,_vertices,_normals); const QColor& clr = geomtype == itPOLYGON ? _boundaryColor : _lineColor; setters[geomtype]->setColorAttributes(attr,value,clr,_featureDrawings[featureIndex],_colors) ; ++featureIndex; } // implicity the redoing of the geometry is also redoing the representation stuff(a.o. colors) _prepared |= ( DrawerInterface::ptGEOMETRY | DrawerInterface::ptRENDER); } if ( hasType(prepType, DrawerInterface::ptRENDER) && !isPrepared(DrawerInterface::ptRENDER)){ IFeatureCoverage features = coverage().as<FeatureCoverage>(); int featureIndex = 0; std::vector<std::shared_ptr<BaseSpatialAttributeSetter>> setters(5); // types are 1 2 4, for performance a vector is used thoug not all elements are used // for the moment I use the simple setters, in the future this will be representation dependent createAttributeSetter(features, setters, rootDrawer()); VisualAttribute attr = visualAttribute(activeAttribute()); if ( !features.isValid()){ return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"FeatureCoverage", TR("Visualization")); } _colors.resize(0); bool polygononly = false; if ( options.contains("polygononly")) polygononly = options["polygononly"].toBool(); for(const SPFeatureI& feature : features){ if ( polygononly && feature->geometryType() != itPOLYGON){ ++featureIndex; continue; } QVariant value = attr.columnIndex() != iUNDEF ? feature(attr.columnIndex()) : featureIndex; IlwisTypes geomtype = feature->geometryType(); const QColor& clr = geomtype == itPOLYGON ? _boundaryColor : _lineColor; setters[geomtype]->setColorAttributes(attr,value,clr,_featureDrawings[featureIndex],_colors) ; ++featureIndex; } _prepared |= DrawerInterface::ptRENDER; } //initialize(); return true; } void FeatureLayerDrawer::unprepare(DrawerInterface::PreparationType prepType) { LayerDrawer::unprepare(prepType); if ( hasType(prepType, DrawerInterface::ptGEOMETRY)) { _prepared &= ~ ptGEOMETRY; } } void FeatureLayerDrawer::setActiveVisualAttribute(const QString &attr) { IFeatureCoverage features = coverage().as<FeatureCoverage>(); if ( features.isValid()) { if ( features->attributeDefinitions().columnIndex(attr) != iUNDEF){ IRepresentation newrpr = Representation::defaultRepresentation(features->attributeDefinitions().columndefinition(attr).datadef().domain()); if ( newrpr.isValid()){ LayerDrawer::setActiveVisualAttribute(attr); } } } } void FeatureLayerDrawer::coverage(const ICoverage &cov) { LayerDrawer::coverage(cov); setActiveVisualAttribute(sUNDEF); IFeatureCoverage features = coverage().as<FeatureCoverage>(); for(int i = 0; i < features->attributeDefinitions().definitionCount(); ++i){ IlwisTypes attrType = features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType(); if ( hasType(attrType, itNUMERICDOMAIN | itITEMDOMAIN | itTEXTDOMAIN)){ VisualAttribute props(features->attributeDefinitions().columndefinition(i).datadef().domain(),i); if ( attrType == itNUMERICDOMAIN){ SPNumericRange numrange = features->attributeDefinitions().columndefinition(i).datadef().range<NumericRange>(); props.actualRange(NumericRange(numrange->min(), numrange->max(), numrange->resolution())); } else if ( attrType == itITEMDOMAIN){ int count = features->attributeDefinitions().columndefinition(i).datadef().domain()->range<>()->count(); props.actualRange(NumericRange(0, count - 1,1)); } visualAttribute(features->attributeDefinitions().columndefinition(i).name(), props); // try to find a reasonable default for the activeattribute if ( activeAttribute() == sUNDEF){ if ( features->attributeDefinitions().columnIndex(FEATUREVALUECOLUMN) != iUNDEF){ setActiveVisualAttribute(FEATUREVALUECOLUMN); }else if ( features->attributeDefinitions().columnIndex(COVERAGEKEYCOLUMN) != iUNDEF){ setActiveVisualAttribute(COVERAGEKEYCOLUMN); } else if ( hasType(features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType(), itNUMERICDOMAIN)){ setActiveVisualAttribute(features->attributeDefinitions().columndefinition(i).name()); } } } } } ICoverage FeatureLayerDrawer::coverage() const { return SpatialDataDrawer::coverage(); } DrawerInterface::DrawerType FeatureLayerDrawer::drawerType() const { return DrawerInterface::dtMAIN; } bool FeatureLayerDrawer::draw(const IOOptions& ) { if ( !isActive()) return false; if (!isPrepared()){ return false; } qDebug() << id(); if(!_shaders.bind()) return false; QMatrix4x4 mvp = rootDrawer()->mvpMatrix(); _shaders.setUniformValue(_modelview, mvp); _shaders.setUniformValue(_vboAlpha, alpha()); _shaders.enableAttributeArray(_vboNormal); _shaders.enableAttributeArray(_vboPosition); _shaders.enableAttributeArray(_vboColor); _shaders.setAttributeArray(_vboPosition, _vertices.constData()); _shaders.setAttributeArray(_vboNormal, _normals.constData()); _shaders.setAttributeArray(_vboColor, GL_FLOAT, (void *)_colors.data(),4); for(const FeatureDrawing& featureDrawing : _featureDrawings){ if ( featureDrawing._geomtype == itPOINT){ _shaders.setUniformValue(_scaleCenter, featureDrawing._center); _shaders.setUniformValue(_scaleFactor, (float)rootDrawer()->zoomScale()); }else{ _shaders.setUniformValue(_scaleFactor, 1.0f); if ( featureDrawing._geomtype == itLINE){ glLineWidth(_lineWidth); }else if (featureDrawing._geomtype == itPOLYGON){ glLineWidth(_boundarywidth); } } for( const VertexIndex& featurePart : featureDrawing._indices){ bool ok = true; if (featureDrawing._geomtype == itPOLYGON ){ if (featurePart._oglType == GL_LINE_STRIP) ok = _showBoundaries; else if (featurePart._oglType == GL_TRIANGLE_FAN){ ok = _showAreas; } } if ( ok) glDrawArrays(featurePart._oglType,featurePart._start,featurePart._count); } } _shaders.disableAttributeArray(_vboNormal); _shaders.disableAttributeArray(_vboPosition); _shaders.disableAttributeArray(_vboColor); _shaders.release(); return true; } QVariant FeatureLayerDrawer::attribute(const QString &attrName) const { QVariant var = LayerDrawer::attribute(attrName); if ( var.isValid()) return var; if ( attrName == "linewidth") return _lineWidth; if ( attrName == "polygonboundaries") return _showBoundaries; if ( attrName == "polygonareas"){ return _showAreas; } if ( attrName == "areatransparency") return _areaTransparency; if ( attrName == "boundarycolor") return _boundaryColor; if ( attrName == "linecolor") return _lineColor; if ( attrName == "boundarywidth") return _boundarywidth; return QVariant(); } void FeatureLayerDrawer::setAttribute(const QString &attrName, const QVariant &value) { LayerDrawer::setAttribute(attrName, value); if ( attrName == "linewidth") _lineWidth = value.toFloat(); if ( attrName == "boundarywidth") _boundarywidth = value.toFloat(); if ( attrName == "polygonboundaries") _showBoundaries = value.toBool(); if ( attrName == "polygonareas") _showAreas = value.toBool(); if ( attrName == "areatransparency") _areaTransparency = value.toFloat(); if ( attrName == "boundarycolor") _boundaryColor = value.value<QColor>(); if ( attrName == "linecolor") _lineColor = value.value<QColor>(); } <commit_msg>removed debugging code<commit_after>#include "coverage.h" #include "featurecoverage.h" #include "feature.h" #include "featureiterator.h" #include "drawingcolor.h" #include "drawers/drawerfactory.h" #include "rootdrawer.h" #include "table.h" #include "range.h" #include "itemrange.h" #include "identifieritem.h" #include "identifierrange.h" #include "colorrange.h" #include "colorlookup.h" #include "itemdomain.h" #include "representation.h" #include "drawers/attributevisualproperties.h" #include "drawers/drawerattributesetter.h" #include "drawers/drawerattributesetterfactory.h" #include "drawerattributesetters/basespatialattributesetter.h" #include "featurelayerdrawer.h" #include "tesselation/ilwistesselator.h" //#include "openglhelper.h" using namespace Ilwis; using namespace Geodrawer; REGISTER_DRAWER(FeatureLayerDrawer) FeatureLayerDrawer::FeatureLayerDrawer(DrawerInterface *parentDrawer, RootDrawer *rootdrawer, const IOOptions &options) : LayerDrawer("FeatureLayerDrawer", parentDrawer, rootdrawer, options) { _vertexShader = "featurevertexshader_nvdia.glsl"; _fragmentShader = "featurefragmentshader_nvdia.glsl"; } DrawerInterface *FeatureLayerDrawer::create(DrawerInterface *parentDrawer, RootDrawer *rootdrawer, const IOOptions &options) { return new FeatureLayerDrawer(parentDrawer, rootdrawer, options) ; } void createAttributeSetter(const IFeatureCoverage& features, std::vector<std::shared_ptr<BaseSpatialAttributeSetter>>& setters, RootDrawer *rootdrawer) { QVariant v = qVariantFromValue((void *) rootdrawer); IOOptions opt("rootdrawer", v); setters[itPOINT].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplepointsetter",opt)); setters[itLINE].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplelinesetter", opt)); setters[itPOLYGON].reset( DrawerAttributeSetterFactory::create<BaseSpatialAttributeSetter>("simplepolygonsetter", opt)); for(int i=0; i < setters.size(); ++i){ if(setters[i]){ setters[i]->sourceCsySystem(features->coordinateSystem()); } } } bool FeatureLayerDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options) { if(!LayerDrawer::prepare(prepType, options)) return false; if ( hasType(prepType, ptSHADERS) && !isPrepared(ptSHADERS)){ _vboColor = _shaders.attributeLocation("vertexColor"); _scaleCenter = _shaders.uniformLocation("scalecenter"); _scaleFactor = _shaders.uniformLocation("scalefactor"); _prepared |= DrawerInterface::ptSHADERS; } if ( hasType(prepType, DrawerInterface::ptGEOMETRY) && !isPrepared(DrawerInterface::ptGEOMETRY)){ IFeatureCoverage features = coverage().as<FeatureCoverage>(); if ( !features.isValid()){ return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"FeatureCoverage", TR("Visualization")); } // set all to 0 _indices = std::vector<VertexIndex>(); _vertices = QVector<QVector3D>(); _normals = QVector<QVector3D>(); _colors = std::vector<VertexColor>(); // get a description of how to render VisualAttribute attr = visualAttribute(activeAttribute()); std::vector<std::shared_ptr<BaseSpatialAttributeSetter>> setters(5); // types are 1 2 4, for performance a vector is used thoug not all elements are used // for the moment I use the simple setters, in the future this will be representation dependent createAttributeSetter(features, setters, rootDrawer()); _featureDrawings.resize(features->featureCount()); int featureIndex = 0; for(const SPFeatureI& feature : features){ QVariant value = attr.columnIndex() != iUNDEF ? feature(attr.columnIndex()) : featureIndex; IlwisTypes geomtype = feature->geometryType(); _featureDrawings[featureIndex] = setters[geomtype]->setSpatialAttributes(feature,_vertices,_normals); const QColor& clr = geomtype == itPOLYGON ? _boundaryColor : _lineColor; setters[geomtype]->setColorAttributes(attr,value,clr,_featureDrawings[featureIndex],_colors) ; ++featureIndex; } // implicity the redoing of the geometry is also redoing the representation stuff(a.o. colors) _prepared |= ( DrawerInterface::ptGEOMETRY | DrawerInterface::ptRENDER); } if ( hasType(prepType, DrawerInterface::ptRENDER) && !isPrepared(DrawerInterface::ptRENDER)){ IFeatureCoverage features = coverage().as<FeatureCoverage>(); int featureIndex = 0; std::vector<std::shared_ptr<BaseSpatialAttributeSetter>> setters(5); // types are 1 2 4, for performance a vector is used thoug not all elements are used // for the moment I use the simple setters, in the future this will be representation dependent createAttributeSetter(features, setters, rootDrawer()); VisualAttribute attr = visualAttribute(activeAttribute()); if ( !features.isValid()){ return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"FeatureCoverage", TR("Visualization")); } _colors.resize(0); bool polygononly = false; if ( options.contains("polygononly")) polygononly = options["polygononly"].toBool(); for(const SPFeatureI& feature : features){ if ( polygononly && feature->geometryType() != itPOLYGON){ ++featureIndex; continue; } QVariant value = attr.columnIndex() != iUNDEF ? feature(attr.columnIndex()) : featureIndex; IlwisTypes geomtype = feature->geometryType(); const QColor& clr = geomtype == itPOLYGON ? _boundaryColor : _lineColor; setters[geomtype]->setColorAttributes(attr,value,clr,_featureDrawings[featureIndex],_colors) ; ++featureIndex; } _prepared |= DrawerInterface::ptRENDER; } //initialize(); return true; } void FeatureLayerDrawer::unprepare(DrawerInterface::PreparationType prepType) { LayerDrawer::unprepare(prepType); if ( hasType(prepType, DrawerInterface::ptGEOMETRY)) { _prepared &= ~ ptGEOMETRY; } } void FeatureLayerDrawer::setActiveVisualAttribute(const QString &attr) { IFeatureCoverage features = coverage().as<FeatureCoverage>(); if ( features.isValid()) { if ( features->attributeDefinitions().columnIndex(attr) != iUNDEF){ IRepresentation newrpr = Representation::defaultRepresentation(features->attributeDefinitions().columndefinition(attr).datadef().domain()); if ( newrpr.isValid()){ LayerDrawer::setActiveVisualAttribute(attr); } } } } void FeatureLayerDrawer::coverage(const ICoverage &cov) { LayerDrawer::coverage(cov); setActiveVisualAttribute(sUNDEF); IFeatureCoverage features = coverage().as<FeatureCoverage>(); for(int i = 0; i < features->attributeDefinitions().definitionCount(); ++i){ IlwisTypes attrType = features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType(); if ( hasType(attrType, itNUMERICDOMAIN | itITEMDOMAIN | itTEXTDOMAIN)){ VisualAttribute props(features->attributeDefinitions().columndefinition(i).datadef().domain(),i); if ( attrType == itNUMERICDOMAIN){ SPNumericRange numrange = features->attributeDefinitions().columndefinition(i).datadef().range<NumericRange>(); props.actualRange(NumericRange(numrange->min(), numrange->max(), numrange->resolution())); } else if ( attrType == itITEMDOMAIN){ int count = features->attributeDefinitions().columndefinition(i).datadef().domain()->range<>()->count(); props.actualRange(NumericRange(0, count - 1,1)); } visualAttribute(features->attributeDefinitions().columndefinition(i).name(), props); // try to find a reasonable default for the activeattribute if ( activeAttribute() == sUNDEF){ if ( features->attributeDefinitions().columnIndex(FEATUREVALUECOLUMN) != iUNDEF){ setActiveVisualAttribute(FEATUREVALUECOLUMN); }else if ( features->attributeDefinitions().columnIndex(COVERAGEKEYCOLUMN) != iUNDEF){ setActiveVisualAttribute(COVERAGEKEYCOLUMN); } else if ( hasType(features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType(), itNUMERICDOMAIN)){ setActiveVisualAttribute(features->attributeDefinitions().columndefinition(i).name()); } } } } } ICoverage FeatureLayerDrawer::coverage() const { return SpatialDataDrawer::coverage(); } DrawerInterface::DrawerType FeatureLayerDrawer::drawerType() const { return DrawerInterface::dtMAIN; } bool FeatureLayerDrawer::draw(const IOOptions& ) { if ( !isActive()) return false; if (!isPrepared()){ return false; } //qDebug() << id(); if(!_shaders.bind()) return false; QMatrix4x4 mvp = rootDrawer()->mvpMatrix(); _shaders.setUniformValue(_modelview, mvp); _shaders.setUniformValue(_vboAlpha, alpha()); _shaders.enableAttributeArray(_vboNormal); _shaders.enableAttributeArray(_vboPosition); _shaders.enableAttributeArray(_vboColor); _shaders.setAttributeArray(_vboPosition, _vertices.constData()); _shaders.setAttributeArray(_vboNormal, _normals.constData()); _shaders.setAttributeArray(_vboColor, GL_FLOAT, (void *)_colors.data(),4); for(const FeatureDrawing& featureDrawing : _featureDrawings){ if ( featureDrawing._geomtype == itPOINT){ _shaders.setUniformValue(_scaleCenter, featureDrawing._center); _shaders.setUniformValue(_scaleFactor, (float)rootDrawer()->zoomScale()); }else{ _shaders.setUniformValue(_scaleFactor, 1.0f); if ( featureDrawing._geomtype == itLINE){ glLineWidth(_lineWidth); }else if (featureDrawing._geomtype == itPOLYGON){ glLineWidth(_boundarywidth); } } for( const VertexIndex& featurePart : featureDrawing._indices){ bool ok = true; if (featureDrawing._geomtype == itPOLYGON ){ if (featurePart._oglType == GL_LINE_STRIP) ok = _showBoundaries; else if (featurePart._oglType == GL_TRIANGLE_FAN){ ok = _showAreas; } } if ( ok) glDrawArrays(featurePart._oglType,featurePart._start,featurePart._count); } } _shaders.disableAttributeArray(_vboNormal); _shaders.disableAttributeArray(_vboPosition); _shaders.disableAttributeArray(_vboColor); _shaders.release(); return true; } QVariant FeatureLayerDrawer::attribute(const QString &attrName) const { QVariant var = LayerDrawer::attribute(attrName); if ( var.isValid()) return var; if ( attrName == "linewidth") return _lineWidth; if ( attrName == "polygonboundaries") return _showBoundaries; if ( attrName == "polygonareas"){ return _showAreas; } if ( attrName == "areatransparency") return _areaTransparency; if ( attrName == "boundarycolor") return _boundaryColor; if ( attrName == "linecolor") return _lineColor; if ( attrName == "boundarywidth") return _boundarywidth; return QVariant(); } void FeatureLayerDrawer::setAttribute(const QString &attrName, const QVariant &value) { LayerDrawer::setAttribute(attrName, value); if ( attrName == "linewidth") _lineWidth = value.toFloat(); if ( attrName == "boundarywidth") _boundarywidth = value.toFloat(); if ( attrName == "polygonboundaries") _showBoundaries = value.toBool(); if ( attrName == "polygonareas") _showAreas = value.toBool(); if ( attrName == "areatransparency") _areaTransparency = value.toFloat(); if ( attrName == "boundarycolor") _boundaryColor = value.value<QColor>(); if ( attrName == "linecolor") _lineColor = value.value<QColor>(); } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dateitem.cxx,v $ * $Revision: 1.8 $ * * 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_svl.hxx" // include --------------------------------------------------------------- #define _DATETIMEITEM_CXX #include <svl/dateitem.hxx> #include <svl/svtools.hrc> #include <unotools/intlwrapper.hxx> #include <comphelper/processfactory.hxx> #include <tools/stream.hxx> #include <tools/debug.hxx> #include <tools/datetime.hxx> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/util/DateTime.hpp> #include <com/sun/star/lang/Locale.hpp> #include <vcl/svapp.hxx> #include <svl/svldata.hxx> // STATIC DATA ----------------------------------------------------------- DBG_NAME(SfxDateTimeItem) // ----------------------------------------------------------------------- TYPEINIT1(SfxDateTimeItem, SfxPoolItem); // ----------------------------------------------------------------------- SfxDateTimeItem::SfxDateTimeItem( USHORT which ) : SfxPoolItem( which ) { DBG_CTOR(SfxDateTimeItem, 0); } // ----------------------------------------------------------------------- SfxDateTimeItem::SfxDateTimeItem( USHORT which, const DateTime& rDT ) : SfxPoolItem( which ), aDateTime( rDT ) { DBG_CTOR(SfxDateTimeItem, 0); } // ----------------------------------------------------------------------- SfxDateTimeItem::SfxDateTimeItem( const SfxDateTimeItem& rItem ) : SfxPoolItem( rItem ), aDateTime( rItem.aDateTime ) { DBG_CTOR(SfxDateTimeItem, 0); } // ----------------------------------------------------------------------- int SfxDateTimeItem::operator==( const SfxPoolItem& rItem ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal type" ); return ( ( (SfxDateTimeItem&)rItem ).aDateTime == aDateTime ); } // ----------------------------------------------------------------------- int SfxDateTimeItem::Compare( const SfxPoolItem& rItem ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal type" ); // da X.Compare( Y ) am String einem Compare( Y, X ) entspricht, // vergleichen wir hier Y mit X if ( ( (const SfxDateTimeItem&)rItem ).aDateTime < aDateTime ) return -1; else if ( ( (const SfxDateTimeItem&)rItem ).aDateTime == aDateTime ) return 0; else return 1; } // ----------------------------------------------------------------------- SfxPoolItem* SfxDateTimeItem::Create( SvStream& rStream, USHORT ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); sal_uInt32 nDate = 0; sal_Int32 nTime = 0; rStream >> nDate; rStream >> nTime; DateTime aDT(nDate, nTime); return new SfxDateTimeItem( Which(), aDT ); } // ----------------------------------------------------------------------- SvStream& SfxDateTimeItem::Store( SvStream& rStream, USHORT ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); rStream << aDateTime.GetDate(); rStream << aDateTime.GetTime(); return rStream; } // ----------------------------------------------------------------------- SfxPoolItem* SfxDateTimeItem::Clone( SfxItemPool* ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); return new SfxDateTimeItem( *this ); } // ----------------------------------------------------------------------- SfxItemPresentation SfxDateTimeItem::GetPresentation ( SfxItemPresentation /*ePresentation*/, SfxMapUnit /*eCoreMetric*/, SfxMapUnit /*ePresentationMetric*/, XubString& rText, const IntlWrapper * pIntlWrapper ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); if (aDateTime.IsValid()) if (pIntlWrapper) { rText = pIntlWrapper->getLocaleData()->getDate(aDateTime); rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); rText += pIntlWrapper->getLocaleData()->getTime(aDateTime); } else { DBG_WARNING("SfxDateTimeItem::GetPresentation():" " Using default en_US IntlWrapper"); const IntlWrapper aIntlWrapper( ::comphelper::getProcessServiceFactory(), LANGUAGE_ENGLISH_US ); rText = aIntlWrapper.getLocaleData()->getDate(aDateTime); rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); rText += aIntlWrapper.getLocaleData()->getTime(aDateTime); } else rText.Erase(); return SFX_ITEM_PRESENTATION_NAMELESS; } //---------------------------------------------------------------------------- // virtual BOOL SfxDateTimeItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId ) { nMemberId &= ~CONVERT_TWIPS; com::sun::star::util::DateTime aValue; if ( rVal >>= aValue ) { aDateTime = DateTime( Date( aValue.Day, aValue.Month, aValue.Year ), Time( aValue.Hours, aValue.Minutes, aValue.Seconds, aValue.HundredthSeconds ) ); return TRUE; } DBG_ERROR( "SfxDateTimeItem::PutValue - Wrong type!" ); return FALSE; } //---------------------------------------------------------------------------- // virtual BOOL SfxDateTimeItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const { nMemberId &= ~CONVERT_TWIPS; com::sun::star::util::DateTime aValue( aDateTime.Get100Sec(), aDateTime.GetSec(), aDateTime.GetMin(), aDateTime.GetHour(), aDateTime.GetDay(), aDateTime.GetMonth(), aDateTime.GetYear() ); rVal <<= aValue; return TRUE; } // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- TYPEINIT1(SfxColumnDateTimeItem, SfxDateTimeItem); SfxColumnDateTimeItem::SfxColumnDateTimeItem( USHORT which ) : SfxDateTimeItem( which ) {} SfxColumnDateTimeItem::SfxColumnDateTimeItem( USHORT which, const DateTime& rDT ) : SfxDateTimeItem( which, rDT ) {} SfxColumnDateTimeItem::SfxColumnDateTimeItem( const SfxDateTimeItem& rCpy ) : SfxDateTimeItem( rCpy ) {} SfxPoolItem* SfxColumnDateTimeItem::Clone( SfxItemPool* ) const { return new SfxColumnDateTimeItem( *this ); } SfxItemPresentation SfxColumnDateTimeItem::GetPresentation ( SfxItemPresentation /*ePresentation*/, SfxMapUnit /*eCoreMetric*/, SfxMapUnit /*ePresentationMetric*/, XubString& rText, const IntlWrapper * pIntlWrapper ) const { DBG_ASSERT(pIntlWrapper, "SfxColumnDateTimeItem::GetPresentation():" " Using default en_US IntlWrapper"); ::com::sun::star::lang::Locale aLocale; if (GetDateTime() == DateTime(Date(1, 2, 3), Time(3, 2, 1))) { rText = String(SvtSimpleResId(STR_COLUM_DT_AUTO, pIntlWrapper ? pIntlWrapper->getLocale() : aLocale)); } else if (pIntlWrapper) { rText = pIntlWrapper->getLocaleData()->getDate(GetDateTime()); rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); rText += pIntlWrapper->getLocaleData()->getTime(GetDateTime()); } else { const IntlWrapper aIntlWrapper( ::comphelper::getProcessServiceFactory(), LANGUAGE_ENGLISH_US ); rText = aIntlWrapper.getLocaleData()->getDate(GetDateTime()); rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); rText += aIntlWrapper.getLocaleData()->getTime(GetDateTime()); } return SFX_ITEM_PRESENTATION_NAMELESS; } <commit_msg>#i103496#: forgotten commit<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: dateitem.cxx,v $ * $Revision: 1.8 $ * * 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_svl.hxx" // include --------------------------------------------------------------- #define _DATETIMEITEM_CXX #include <svl/dateitem.hxx> #include <svl/svldata.hxx> #include <svl/svtools.hrc> #include <unotools/intlwrapper.hxx> #include <comphelper/processfactory.hxx> #include <tools/stream.hxx> #include <tools/debug.hxx> #include <tools/datetime.hxx> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/util/DateTime.hpp> #include <com/sun/star/lang/Locale.hpp> // STATIC DATA ----------------------------------------------------------- DBG_NAME(SfxDateTimeItem) // ----------------------------------------------------------------------- TYPEINIT1(SfxDateTimeItem, SfxPoolItem); // ----------------------------------------------------------------------- SfxDateTimeItem::SfxDateTimeItem( USHORT which ) : SfxPoolItem( which ) { DBG_CTOR(SfxDateTimeItem, 0); } // ----------------------------------------------------------------------- SfxDateTimeItem::SfxDateTimeItem( USHORT which, const DateTime& rDT ) : SfxPoolItem( which ), aDateTime( rDT ) { DBG_CTOR(SfxDateTimeItem, 0); } // ----------------------------------------------------------------------- SfxDateTimeItem::SfxDateTimeItem( const SfxDateTimeItem& rItem ) : SfxPoolItem( rItem ), aDateTime( rItem.aDateTime ) { DBG_CTOR(SfxDateTimeItem, 0); } // ----------------------------------------------------------------------- int SfxDateTimeItem::operator==( const SfxPoolItem& rItem ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal type" ); return ( ( (SfxDateTimeItem&)rItem ).aDateTime == aDateTime ); } // ----------------------------------------------------------------------- int SfxDateTimeItem::Compare( const SfxPoolItem& rItem ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); DBG_ASSERT( SfxPoolItem::operator==( rItem ), "unequal type" ); // da X.Compare( Y ) am String einem Compare( Y, X ) entspricht, // vergleichen wir hier Y mit X if ( ( (const SfxDateTimeItem&)rItem ).aDateTime < aDateTime ) return -1; else if ( ( (const SfxDateTimeItem&)rItem ).aDateTime == aDateTime ) return 0; else return 1; } // ----------------------------------------------------------------------- SfxPoolItem* SfxDateTimeItem::Create( SvStream& rStream, USHORT ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); sal_uInt32 nDate = 0; sal_Int32 nTime = 0; rStream >> nDate; rStream >> nTime; DateTime aDT(nDate, nTime); return new SfxDateTimeItem( Which(), aDT ); } // ----------------------------------------------------------------------- SvStream& SfxDateTimeItem::Store( SvStream& rStream, USHORT ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); rStream << aDateTime.GetDate(); rStream << aDateTime.GetTime(); return rStream; } // ----------------------------------------------------------------------- SfxPoolItem* SfxDateTimeItem::Clone( SfxItemPool* ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); return new SfxDateTimeItem( *this ); } // ----------------------------------------------------------------------- SfxItemPresentation SfxDateTimeItem::GetPresentation ( SfxItemPresentation /*ePresentation*/, SfxMapUnit /*eCoreMetric*/, SfxMapUnit /*ePresentationMetric*/, XubString& rText, const IntlWrapper * pIntlWrapper ) const { DBG_CHKTHIS(SfxDateTimeItem, 0); if (aDateTime.IsValid()) if (pIntlWrapper) { rText = pIntlWrapper->getLocaleData()->getDate(aDateTime); rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); rText += pIntlWrapper->getLocaleData()->getTime(aDateTime); } else { DBG_WARNING("SfxDateTimeItem::GetPresentation():" " Using default en_US IntlWrapper"); const IntlWrapper aIntlWrapper( ::comphelper::getProcessServiceFactory(), LANGUAGE_ENGLISH_US ); rText = aIntlWrapper.getLocaleData()->getDate(aDateTime); rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); rText += aIntlWrapper.getLocaleData()->getTime(aDateTime); } else rText.Erase(); return SFX_ITEM_PRESENTATION_NAMELESS; } //---------------------------------------------------------------------------- // virtual BOOL SfxDateTimeItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId ) { nMemberId &= ~CONVERT_TWIPS; com::sun::star::util::DateTime aValue; if ( rVal >>= aValue ) { aDateTime = DateTime( Date( aValue.Day, aValue.Month, aValue.Year ), Time( aValue.Hours, aValue.Minutes, aValue.Seconds, aValue.HundredthSeconds ) ); return TRUE; } DBG_ERROR( "SfxDateTimeItem::PutValue - Wrong type!" ); return FALSE; } //---------------------------------------------------------------------------- // virtual BOOL SfxDateTimeItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const { nMemberId &= ~CONVERT_TWIPS; com::sun::star::util::DateTime aValue( aDateTime.Get100Sec(), aDateTime.GetSec(), aDateTime.GetMin(), aDateTime.GetHour(), aDateTime.GetDay(), aDateTime.GetMonth(), aDateTime.GetYear() ); rVal <<= aValue; return TRUE; } // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- TYPEINIT1(SfxColumnDateTimeItem, SfxDateTimeItem); SfxColumnDateTimeItem::SfxColumnDateTimeItem( USHORT which ) : SfxDateTimeItem( which ) {} SfxColumnDateTimeItem::SfxColumnDateTimeItem( USHORT which, const DateTime& rDT ) : SfxDateTimeItem( which, rDT ) {} SfxColumnDateTimeItem::SfxColumnDateTimeItem( const SfxDateTimeItem& rCpy ) : SfxDateTimeItem( rCpy ) {} SfxPoolItem* SfxColumnDateTimeItem::Clone( SfxItemPool* ) const { return new SfxColumnDateTimeItem( *this ); } SfxItemPresentation SfxColumnDateTimeItem::GetPresentation ( SfxItemPresentation /*ePresentation*/, SfxMapUnit /*eCoreMetric*/, SfxMapUnit /*ePresentationMetric*/, XubString& rText, const IntlWrapper * pIntlWrapper ) const { DBG_ASSERT(pIntlWrapper, "SfxColumnDateTimeItem::GetPresentation():" " Using default en_US IntlWrapper"); ::com::sun::star::lang::Locale aLocale; if (GetDateTime() == DateTime(Date(1, 2, 3), Time(3, 2, 1))) { rText = String(SvtSimpleResId(STR_COLUM_DT_AUTO, pIntlWrapper ? pIntlWrapper->getLocale() : aLocale)); } else if (pIntlWrapper) { rText = pIntlWrapper->getLocaleData()->getDate(GetDateTime()); rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); rText += pIntlWrapper->getLocaleData()->getTime(GetDateTime()); } else { const IntlWrapper aIntlWrapper( ::comphelper::getProcessServiceFactory(), LANGUAGE_ENGLISH_US ); rText = aIntlWrapper.getLocaleData()->getDate(GetDateTime()); rText.AppendAscii(RTL_CONSTASCII_STRINGPARAM(", ")); rText += aIntlWrapper.getLocaleData()->getTime(GetDateTime()); } return SFX_ITEM_PRESENTATION_NAMELESS; } <|endoftext|>
<commit_before>#include <type_traits> namespace dp { template < typename T, std::size_t D > inline DopeVectorExtent<T, D>::DopeVectorExtent(const std::array<std::size_t, D> &size) : DopeVector<T, D>() , _arrayPtr(nullptr) { resize(size); } template < typename T, std::size_t D > inline DopeVectorExtent<T, D> & DopeVectorExtent<T, D>::operator=(const DopeVectorExtent &other) { if (&other != this) { std::array<std::size_t, D> size; other.allSizes(size); resize(size); std::memcpy(_arrayPtr.get(), other._arrayPtr.get(), DopeVector<T, D>::size() * sizeof(T)); } return *this; } template < typename T, std::size_t D > inline void DopeVectorExtent<T, D>::import(const DopeVector<T, D> &o) { if (&o == this) return; try { const DopeVectorExtent<T, D> &oo = dynamic_cast<const DopeVectorExtent<T, D> &>(o); for (std::size_t d = 0; d < D; ++d) if (DopeVector<T, D>::sizeAt(d) != oo.sizeAt(d)) throw std::out_of_range("Matrixes do not have same size."); if (std::is_pod<T>::value) std::memcpy(_arrayPtr.get(), oo._arrayPtr.get(), DopeVector<T, D>::size() * sizeof(T)); else for (std::size_t i = 0; i < DopeVector<T, D>::size(); ++i) _arrayPtr[i] = oo._arrayPtr[i]; } catch(std::bad_cast &bc) { DopeVector<T, D>::import(o); } } template < typename T, std::size_t D > inline void DopeVectorExtent<T, D>::resize(const std::array<std::size_t, D> &size) { std::size_t total = size[0]; for (std::size_t i = 1; i < D; ++i) total *= size[i]; if (total > 0) { if (total != DopeVector<T, D>::size()) _arrayPtr.reset(new T[total]); // Be aware: data is LOST! DopeVector<T, D>::operator=(DopeVector<T, D>(_arrayPtr.get(), 0, size)); } else { clear(); } } template < typename T, std::size_t D > inline void DopeVectorExtent<T, D>::clear() { _arrayPtr.reset(nullptr); DopeVector<T, D>::operator=(DopeVector<T, D>()); } } <commit_msg>removed old file<commit_after><|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2013, 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.cpp * Multicopter attitude controller. * * @author Tobias Naegeli <naegelit@student.ethz.ch> * @author Lorenz Meier <lm@inf.ethz.ch> * @author Anton Babushkin <anton.babushkin@me.com> * @author Thomas Gubler <thomasgubler@gmail.com> * @author Julian Oes <julian@oes.ch> * @author Roman Bapst <bapstr@ethz.ch> */ #include "mc_att_control.h" #include "mc_att_control_params.h" #include "math.h" #define YAW_DEADZONE 0.05f #define MIN_TAKEOFF_THRUST 0.2f #define RATES_I_LIMIT 0.3f namespace mc_att_control { /* oddly, ERROR is not defined for c++ */ #ifdef ERROR # undef ERROR #endif static const int ERROR = -1; } MulticopterAttitudeControl::MulticopterAttitudeControl() : MulticopterAttitudeControlBase(), _task_should_exit(false), _actuators_0_circuit_breaker_enabled(false), /* publications */ _att_sp_pub(nullptr), _v_rates_sp_pub(nullptr), _actuators_0_pub(nullptr), _n(), /* performance counters */ _loop_perf(perf_alloc(PC_ELAPSED, "mc_att_control")) { _params_handles.roll_p = PX4_PARAM_INIT(MC_ROLL_P); _params_handles.roll_rate_p = PX4_PARAM_INIT(MC_ROLLRATE_P); _params_handles.roll_rate_i = PX4_PARAM_INIT(MC_ROLLRATE_I); _params_handles.roll_rate_d = PX4_PARAM_INIT(MC_ROLLRATE_D); _params_handles.pitch_p = PX4_PARAM_INIT(MC_PITCH_P); _params_handles.pitch_rate_p = PX4_PARAM_INIT(MC_PITCHRATE_P); _params_handles.pitch_rate_i = PX4_PARAM_INIT(MC_PITCHRATE_I); _params_handles.pitch_rate_d = PX4_PARAM_INIT(MC_PITCHRATE_D); _params_handles.yaw_p = PX4_PARAM_INIT(MC_YAW_P); _params_handles.yaw_rate_p = PX4_PARAM_INIT(MC_YAWRATE_P); _params_handles.yaw_rate_i = PX4_PARAM_INIT(MC_YAWRATE_I); _params_handles.yaw_rate_d = PX4_PARAM_INIT(MC_YAWRATE_D); _params_handles.yaw_ff = PX4_PARAM_INIT(MC_YAW_FF); _params_handles.yaw_rate_max = PX4_PARAM_INIT(MC_YAWRATE_MAX); _params_handles.man_roll_max = PX4_PARAM_INIT(MC_MAN_R_MAX); _params_handles.man_pitch_max = PX4_PARAM_INIT(MC_MAN_P_MAX); _params_handles.man_yaw_max = PX4_PARAM_INIT(MC_MAN_Y_MAX); _params_handles.acro_roll_max = PX4_PARAM_INIT(MC_ACRO_R_MAX); _params_handles.acro_pitch_max = PX4_PARAM_INIT(MC_ACRO_P_MAX); _params_handles.acro_yaw_max = PX4_PARAM_INIT(MC_ACRO_Y_MAX); /* * do subscriptions */ _v_att = PX4_SUBSCRIBE(_n, vehicle_attitude, MulticopterAttitudeControl::handle_vehicle_attitude, this, 0); _v_att_sp = PX4_SUBSCRIBE(_n, vehicle_attitude_setpoint, 0); _v_rates_sp = PX4_SUBSCRIBE(_n, vehicle_rates_setpoint, 0); _v_control_mode = PX4_SUBSCRIBE(_n, vehicle_control_mode, 0); _parameter_update = PX4_SUBSCRIBE(_n, parameter_update, MulticopterAttitudeControl::handle_parameter_update, this, 1000); _manual_control_sp = PX4_SUBSCRIBE(_n, manual_control_setpoint, 0); _armed = PX4_SUBSCRIBE(_n, actuator_armed, 0); _v_status = PX4_SUBSCRIBE(_n, vehicle_status, 0); } MulticopterAttitudeControl::~MulticopterAttitudeControl() { } int MulticopterAttitudeControl::parameters_update() { float v; /* roll gains */ PX4_PARAM_GET(_params_handles.roll_p, &v); _params.att_p(0) = v; PX4_PARAM_GET(_params_handles.roll_rate_p, &v); _params.rate_p(0) = v; PX4_PARAM_GET(_params_handles.roll_rate_i, &v); _params.rate_i(0) = v; PX4_PARAM_GET(_params_handles.roll_rate_d, &v); _params.rate_d(0) = v; /* pitch gains */ PX4_PARAM_GET(_params_handles.pitch_p, &v); _params.att_p(1) = v; PX4_PARAM_GET(_params_handles.pitch_rate_p, &v); _params.rate_p(1) = v; PX4_PARAM_GET(_params_handles.pitch_rate_i, &v); _params.rate_i(1) = v; PX4_PARAM_GET(_params_handles.pitch_rate_d, &v); _params.rate_d(1) = v; /* yaw gains */ PX4_PARAM_GET(_params_handles.yaw_p, &v); _params.att_p(2) = v; PX4_PARAM_GET(_params_handles.yaw_rate_p, &v); _params.rate_p(2) = v; PX4_PARAM_GET(_params_handles.yaw_rate_i, &v); _params.rate_i(2) = v; PX4_PARAM_GET(_params_handles.yaw_rate_d, &v); _params.rate_d(2) = v; PX4_PARAM_GET(_params_handles.yaw_ff, &_params.yaw_ff); PX4_PARAM_GET(_params_handles.yaw_rate_max, &_params.yaw_rate_max); _params.yaw_rate_max = math::radians(_params.yaw_rate_max); /* manual control scale */ PX4_PARAM_GET(_params_handles.man_roll_max, &_params.man_roll_max); PX4_PARAM_GET(_params_handles.man_pitch_max, &_params.man_pitch_max); PX4_PARAM_GET(_params_handles.man_yaw_max, &_params.man_yaw_max); _params.man_roll_max = math::radians(_params.man_roll_max); _params.man_pitch_max = math::radians(_params.man_pitch_max); _params.man_yaw_max = math::radians(_params.man_yaw_max); /* acro control scale */ PX4_PARAM_GET(_params_handles.acro_roll_max, &v); _params.acro_rate_max(0) = math::radians(v); PX4_PARAM_GET(_params_handles.acro_pitch_max, &v); _params.acro_rate_max(1) = math::radians(v); PX4_PARAM_GET(_params_handles.acro_yaw_max, &v); _params.acro_rate_max(2) = math::radians(v); _actuators_0_circuit_breaker_enabled = circuit_breaker_enabled("CBRK_RATE_CTRL", CBRK_RATE_CTRL_KEY); return OK; } void MulticopterAttitudeControl::handle_parameter_update(const PX4_TOPIC_T(parameter_update) &msg) { parameters_update(); } void MulticopterAttitudeControl::handle_vehicle_attitude(const PX4_TOPIC_T(vehicle_attitude) &msg) { perf_begin(_loop_perf); /* run controller on attitude changes */ static uint64_t last_run = 0; float dt = (px4::get_time_micros() - last_run) / 1000000.0f; last_run = px4::get_time_micros(); /* guard against too small (< 2ms) and too large (> 20ms) dt's */ if (dt < 0.002f) { dt = 0.002f; } else if (dt > 0.02f) { dt = 0.02f; } if (_v_control_mode->get().flag_control_attitude_enabled) { control_attitude(dt); /* publish the attitude setpoint if needed */ if (_publish_att_sp && _v_status->get().is_rotary_wing) { _v_att_sp_mod.timestamp = px4::get_time_micros(); if (_att_sp_pub != nullptr) { _att_sp_pub->publish(_v_att_sp_mod); } else { _att_sp_pub = PX4_ADVERTISE(_n, vehicle_attitude_setpoint); } } /* publish attitude rates setpoint */ _v_rates_sp_mod.roll = _rates_sp(0); _v_rates_sp_mod.pitch = _rates_sp(1); _v_rates_sp_mod.yaw = _rates_sp(2); _v_rates_sp_mod.thrust = _thrust_sp; _v_rates_sp_mod.timestamp = px4::get_time_micros(); if (_v_rates_sp_pub != nullptr) { _v_rates_sp_pub->publish(_v_rates_sp_mod); } else { if (_v_status->get()._is_vtol) { _v_rates_sp_pub = PX4_ADVERTISE(_n, mc_virtual_rates_setpoint); } else { _v_rates_sp_pub = PX4_ADVERTISE(_n, vehicle_rates_setpoint); } } } else { /* attitude controller disabled, poll rates setpoint topic */ if (_v_control_mode->get().flag_control_manual_enabled) { /* manual rates control - ACRO mode */ _rates_sp = math::Vector<3>(_manual_control_sp->get().y, -_manual_control_sp->get().x, _manual_control_sp->get().r).emult(_params.acro_rate_max); _thrust_sp = _manual_control_sp->get().z; /* reset yaw setpoint after ACRO */ _reset_yaw_sp = true; /* publish attitude rates setpoint */ _v_rates_sp_mod.roll = _rates_sp(0); _v_rates_sp_mod.pitch = _rates_sp(1); _v_rates_sp_mod.yaw = _rates_sp(2); _v_rates_sp_mod.thrust = _thrust_sp; _v_rates_sp_mod.timestamp = px4::get_time_micros(); if (_v_rates_sp_pub != nullptr) { _v_rates_sp_pub->publish(_v_rates_sp_mod); } else { if (_v_status->get()._is_vtol) { _v_rates_sp_pub = PX4_ADVERTISE(_n, mc_virtual_rates_setpoint); } else { _v_rates_sp_pub = PX4_ADVERTISE(_n, vehicle_rates_setpoint); } } } else { /* attitude controller disabled, poll rates setpoint topic */ _rates_sp(0) = _v_rates_sp->get().roll; _rates_sp(1) = _v_rates_sp->get().pitch; _rates_sp(2) = _v_rates_sp->get().yaw; _thrust_sp = _v_rates_sp->get().thrust; } } if (_v_control_mode->get().flag_control_rates_enabled) { control_attitude_rates(dt); /* publish actuator controls */ _actuators.control[0] = (isfinite(_att_control(0))) ? _att_control(0) : 0.0f; _actuators.control[1] = (isfinite(_att_control(1))) ? _att_control(1) : 0.0f; _actuators.control[2] = (isfinite(_att_control(2))) ? _att_control(2) : 0.0f; _actuators.control[3] = (isfinite(_thrust_sp)) ? _thrust_sp : 0.0f; _actuators.timestamp = px4::get_time_micros(); if (!_actuators_0_circuit_breaker_enabled) { if (_actuators_0_pub != nullptr) { _actuators_0_pub->publish(_actuators); } else { if (_v_status()->get()._is_vtol) { _actuators_0_pub = PX4_ADVERTISE(_n, actuator_controls_virtual_mc); } else { _actuators_0_pub = PX4_ADVERTISE(_n, actuator_controls_0); } } } } } <commit_msg>fix compile/merge error in mc_att_control<commit_after>/**************************************************************************** * * Copyright (c) 2013, 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.cpp * Multicopter attitude controller. * * @author Tobias Naegeli <naegelit@student.ethz.ch> * @author Lorenz Meier <lm@inf.ethz.ch> * @author Anton Babushkin <anton.babushkin@me.com> * @author Thomas Gubler <thomasgubler@gmail.com> * @author Julian Oes <julian@oes.ch> * @author Roman Bapst <bapstr@ethz.ch> */ #include "mc_att_control.h" #include "mc_att_control_params.h" #include "math.h" #define YAW_DEADZONE 0.05f #define MIN_TAKEOFF_THRUST 0.2f #define RATES_I_LIMIT 0.3f namespace mc_att_control { /* oddly, ERROR is not defined for c++ */ #ifdef ERROR # undef ERROR #endif static const int ERROR = -1; } MulticopterAttitudeControl::MulticopterAttitudeControl() : MulticopterAttitudeControlBase(), _task_should_exit(false), _actuators_0_circuit_breaker_enabled(false), /* publications */ _att_sp_pub(nullptr), _v_rates_sp_pub(nullptr), _actuators_0_pub(nullptr), _n(), /* performance counters */ _loop_perf(perf_alloc(PC_ELAPSED, "mc_att_control")) { _params_handles.roll_p = PX4_PARAM_INIT(MC_ROLL_P); _params_handles.roll_rate_p = PX4_PARAM_INIT(MC_ROLLRATE_P); _params_handles.roll_rate_i = PX4_PARAM_INIT(MC_ROLLRATE_I); _params_handles.roll_rate_d = PX4_PARAM_INIT(MC_ROLLRATE_D); _params_handles.pitch_p = PX4_PARAM_INIT(MC_PITCH_P); _params_handles.pitch_rate_p = PX4_PARAM_INIT(MC_PITCHRATE_P); _params_handles.pitch_rate_i = PX4_PARAM_INIT(MC_PITCHRATE_I); _params_handles.pitch_rate_d = PX4_PARAM_INIT(MC_PITCHRATE_D); _params_handles.yaw_p = PX4_PARAM_INIT(MC_YAW_P); _params_handles.yaw_rate_p = PX4_PARAM_INIT(MC_YAWRATE_P); _params_handles.yaw_rate_i = PX4_PARAM_INIT(MC_YAWRATE_I); _params_handles.yaw_rate_d = PX4_PARAM_INIT(MC_YAWRATE_D); _params_handles.yaw_ff = PX4_PARAM_INIT(MC_YAW_FF); _params_handles.yaw_rate_max = PX4_PARAM_INIT(MC_YAWRATE_MAX); _params_handles.man_roll_max = PX4_PARAM_INIT(MC_MAN_R_MAX); _params_handles.man_pitch_max = PX4_PARAM_INIT(MC_MAN_P_MAX); _params_handles.man_yaw_max = PX4_PARAM_INIT(MC_MAN_Y_MAX); _params_handles.acro_roll_max = PX4_PARAM_INIT(MC_ACRO_R_MAX); _params_handles.acro_pitch_max = PX4_PARAM_INIT(MC_ACRO_P_MAX); _params_handles.acro_yaw_max = PX4_PARAM_INIT(MC_ACRO_Y_MAX); /* * do subscriptions */ _v_att = PX4_SUBSCRIBE(_n, vehicle_attitude, MulticopterAttitudeControl::handle_vehicle_attitude, this, 0); _v_att_sp = PX4_SUBSCRIBE(_n, vehicle_attitude_setpoint, 0); _v_rates_sp = PX4_SUBSCRIBE(_n, vehicle_rates_setpoint, 0); _v_control_mode = PX4_SUBSCRIBE(_n, vehicle_control_mode, 0); _parameter_update = PX4_SUBSCRIBE(_n, parameter_update, MulticopterAttitudeControl::handle_parameter_update, this, 1000); _manual_control_sp = PX4_SUBSCRIBE(_n, manual_control_setpoint, 0); _armed = PX4_SUBSCRIBE(_n, actuator_armed, 0); _v_status = PX4_SUBSCRIBE(_n, vehicle_status, 0); } MulticopterAttitudeControl::~MulticopterAttitudeControl() { } int MulticopterAttitudeControl::parameters_update() { float v; /* roll gains */ PX4_PARAM_GET(_params_handles.roll_p, &v); _params.att_p(0) = v; PX4_PARAM_GET(_params_handles.roll_rate_p, &v); _params.rate_p(0) = v; PX4_PARAM_GET(_params_handles.roll_rate_i, &v); _params.rate_i(0) = v; PX4_PARAM_GET(_params_handles.roll_rate_d, &v); _params.rate_d(0) = v; /* pitch gains */ PX4_PARAM_GET(_params_handles.pitch_p, &v); _params.att_p(1) = v; PX4_PARAM_GET(_params_handles.pitch_rate_p, &v); _params.rate_p(1) = v; PX4_PARAM_GET(_params_handles.pitch_rate_i, &v); _params.rate_i(1) = v; PX4_PARAM_GET(_params_handles.pitch_rate_d, &v); _params.rate_d(1) = v; /* yaw gains */ PX4_PARAM_GET(_params_handles.yaw_p, &v); _params.att_p(2) = v; PX4_PARAM_GET(_params_handles.yaw_rate_p, &v); _params.rate_p(2) = v; PX4_PARAM_GET(_params_handles.yaw_rate_i, &v); _params.rate_i(2) = v; PX4_PARAM_GET(_params_handles.yaw_rate_d, &v); _params.rate_d(2) = v; PX4_PARAM_GET(_params_handles.yaw_ff, &_params.yaw_ff); PX4_PARAM_GET(_params_handles.yaw_rate_max, &_params.yaw_rate_max); _params.yaw_rate_max = math::radians(_params.yaw_rate_max); /* manual control scale */ PX4_PARAM_GET(_params_handles.man_roll_max, &_params.man_roll_max); PX4_PARAM_GET(_params_handles.man_pitch_max, &_params.man_pitch_max); PX4_PARAM_GET(_params_handles.man_yaw_max, &_params.man_yaw_max); _params.man_roll_max = math::radians(_params.man_roll_max); _params.man_pitch_max = math::radians(_params.man_pitch_max); _params.man_yaw_max = math::radians(_params.man_yaw_max); /* acro control scale */ PX4_PARAM_GET(_params_handles.acro_roll_max, &v); _params.acro_rate_max(0) = math::radians(v); PX4_PARAM_GET(_params_handles.acro_pitch_max, &v); _params.acro_rate_max(1) = math::radians(v); PX4_PARAM_GET(_params_handles.acro_yaw_max, &v); _params.acro_rate_max(2) = math::radians(v); _actuators_0_circuit_breaker_enabled = circuit_breaker_enabled("CBRK_RATE_CTRL", CBRK_RATE_CTRL_KEY); return OK; } void MulticopterAttitudeControl::handle_parameter_update(const PX4_TOPIC_T(parameter_update) &msg) { parameters_update(); } void MulticopterAttitudeControl::handle_vehicle_attitude(const PX4_TOPIC_T(vehicle_attitude) &msg) { perf_begin(_loop_perf); /* run controller on attitude changes */ static uint64_t last_run = 0; float dt = (px4::get_time_micros() - last_run) / 1000000.0f; last_run = px4::get_time_micros(); /* guard against too small (< 2ms) and too large (> 20ms) dt's */ if (dt < 0.002f) { dt = 0.002f; } else if (dt > 0.02f) { dt = 0.02f; } if (_v_control_mode->get().flag_control_attitude_enabled) { control_attitude(dt); /* publish the attitude setpoint if needed */ if (_publish_att_sp && _v_status->get().is_rotary_wing) { _v_att_sp_mod.timestamp = px4::get_time_micros(); if (_att_sp_pub != nullptr) { _att_sp_pub->publish(_v_att_sp_mod); } else { _att_sp_pub = PX4_ADVERTISE(_n, vehicle_attitude_setpoint); } } /* publish attitude rates setpoint */ _v_rates_sp_mod.roll = _rates_sp(0); _v_rates_sp_mod.pitch = _rates_sp(1); _v_rates_sp_mod.yaw = _rates_sp(2); _v_rates_sp_mod.thrust = _thrust_sp; _v_rates_sp_mod.timestamp = px4::get_time_micros(); if (_v_rates_sp_pub != nullptr) { _v_rates_sp_pub->publish(_v_rates_sp_mod); } else { if (_v_status->get().is_vtol) { _v_rates_sp_pub = PX4_ADVERTISE(_n, mc_virtual_rates_setpoint); } else { _v_rates_sp_pub = PX4_ADVERTISE(_n, vehicle_rates_setpoint); } } } else { /* attitude controller disabled, poll rates setpoint topic */ if (_v_control_mode->get().flag_control_manual_enabled) { /* manual rates control - ACRO mode */ _rates_sp = math::Vector<3>(_manual_control_sp->get().y, -_manual_control_sp->get().x, _manual_control_sp->get().r).emult(_params.acro_rate_max); _thrust_sp = _manual_control_sp->get().z; /* reset yaw setpoint after ACRO */ _reset_yaw_sp = true; /* publish attitude rates setpoint */ _v_rates_sp_mod.roll = _rates_sp(0); _v_rates_sp_mod.pitch = _rates_sp(1); _v_rates_sp_mod.yaw = _rates_sp(2); _v_rates_sp_mod.thrust = _thrust_sp; _v_rates_sp_mod.timestamp = px4::get_time_micros(); if (_v_rates_sp_pub != nullptr) { _v_rates_sp_pub->publish(_v_rates_sp_mod); } else { if (_v_status->get().is_vtol) { _v_rates_sp_pub = PX4_ADVERTISE(_n, mc_virtual_rates_setpoint); } else { _v_rates_sp_pub = PX4_ADVERTISE(_n, vehicle_rates_setpoint); } } } else { /* attitude controller disabled, poll rates setpoint topic */ _rates_sp(0) = _v_rates_sp->get().roll; _rates_sp(1) = _v_rates_sp->get().pitch; _rates_sp(2) = _v_rates_sp->get().yaw; _thrust_sp = _v_rates_sp->get().thrust; } } if (_v_control_mode->get().flag_control_rates_enabled) { control_attitude_rates(dt); /* publish actuator controls */ _actuators.control[0] = (isfinite(_att_control(0))) ? _att_control(0) : 0.0f; _actuators.control[1] = (isfinite(_att_control(1))) ? _att_control(1) : 0.0f; _actuators.control[2] = (isfinite(_att_control(2))) ? _att_control(2) : 0.0f; _actuators.control[3] = (isfinite(_thrust_sp)) ? _thrust_sp : 0.0f; _actuators.timestamp = px4::get_time_micros(); if (!_actuators_0_circuit_breaker_enabled) { if (_actuators_0_pub != nullptr) { _actuators_0_pub->publish(_actuators); } else { if (_v_status->get().is_vtol) { _actuators_0_pub = PX4_ADVERTISE(_n, actuator_controls_virtual_mc); } else { _actuators_0_pub = PX4_ADVERTISE(_n, actuator_controls_0); } } } } } <|endoftext|>
<commit_before>// (C) Copyright Gennadiy Rozental 2002-2003. // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied warranty, // and with no claim as to its suitability for any purpose. // See http://www.boost.org for most recent version including documentation. // // File : $RCSfile$ // // Version : $Revision$ // // Description : wraps strstream and stringstream (depends with one is present ) // to prodive the unified interface // *************************************************************************** #ifndef BOOST_WRAP_STRINGSTREAM_HPP #define BOOST_WRAP_STRINGSTREAM_HPP // STL #ifdef BOOST_NO_STRINGSTREAM #include <strstream> // for std::ostrstream #else #include <sstream> // for std::ostringstream #endif // BOOST_NO_STRINGSTREAM #include <string> // std::string namespace boost { // ************************************************************************** // // ************** wrap_stringstream ************** // // ************************************************************************** // class wrap_stringstream { #ifdef BOOST_NO_STRINGSTREAM typedef std::ostrstream wrapped_stream; #else typedef std::ostringstream wrapped_stream; #endif // BOOST_NO_STRINGSTREAM public: // access methods wrap_stringstream& ref(); wrapped_stream& stream(); std::string const& str(); private: // Data members wrapped_stream m_stream; std::string m_str; }; //____________________________________________________________________________// template <class T> inline wrap_stringstream& operator<<( wrap_stringstream& targ, T const& t ) { targ.stream() << t; return targ; } //____________________________________________________________________________// inline wrap_stringstream::wrapped_stream& wrap_stringstream::stream() { return m_stream; } //____________________________________________________________________________// inline wrap_stringstream& wrap_stringstream::ref() { return *this; } //____________________________________________________________________________// inline wrap_stringstream& operator<<( wrap_stringstream& targ, wrap_stringstream& src ) { targ << src.str(); return targ; } //____________________________________________________________________________// inline std::string const& wrap_stringstream::str() { #ifdef BOOST_NO_STRINGSTREAM m_str.assign( m_stream.str(), m_stream.pcount() ); m_stream.freeze( false ); #else m_str = m_stream.str(); #endif return m_str; } //____________________________________________________________________________// } // namespace boost // *************************************************************************** // Revision History : // // $Log$ // Revision 1.3 2003/06/09 08:39:28 rogeeff // 1.30.beta1 // // *************************************************************************** #endif // BOOST_WRAP_STRINGSTREAM_HPP <commit_msg>define str() before it is first used to avoid "redeclared inline after begin called" error on IRIX MIPSpro<commit_after>// (C) Copyright Gennadiy Rozental 2002-2003. // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied warranty, // and with no claim as to its suitability for any purpose. // See http://www.boost.org for most recent version including documentation. // // File : $RCSfile$ // // Version : $Revision$ // // Description : wraps strstream and stringstream (depends with one is present ) // to prodive the unified interface // *************************************************************************** #ifndef BOOST_WRAP_STRINGSTREAM_HPP #define BOOST_WRAP_STRINGSTREAM_HPP // STL #ifdef BOOST_NO_STRINGSTREAM #include <strstream> // for std::ostrstream #else #include <sstream> // for std::ostringstream #endif // BOOST_NO_STRINGSTREAM #include <string> // std::string namespace boost { // ************************************************************************** // // ************** wrap_stringstream ************** // // ************************************************************************** // class wrap_stringstream { #ifdef BOOST_NO_STRINGSTREAM typedef std::ostrstream wrapped_stream; #else typedef std::ostringstream wrapped_stream; #endif // BOOST_NO_STRINGSTREAM public: // access methods wrap_stringstream& ref(); wrapped_stream& stream(); std::string const& str(); private: // Data members wrapped_stream m_stream; std::string m_str; }; //____________________________________________________________________________// template <class T> inline wrap_stringstream& operator<<( wrap_stringstream& targ, T const& t ) { targ.stream() << t; return targ; } //____________________________________________________________________________// inline wrap_stringstream::wrapped_stream& wrap_stringstream::stream() { return m_stream; } //____________________________________________________________________________// inline wrap_stringstream& wrap_stringstream::ref() { return *this; } //____________________________________________________________________________// inline std::string const& wrap_stringstream::str() { #ifdef BOOST_NO_STRINGSTREAM m_str.assign( m_stream.str(), m_stream.pcount() ); m_stream.freeze( false ); #else m_str = m_stream.str(); #endif return m_str; } //____________________________________________________________________________// inline wrap_stringstream& operator<<( wrap_stringstream& targ, wrap_stringstream& src ) { targ << src.str(); return targ; } //____________________________________________________________________________// } // namespace boost // *************************************************************************** // Revision History : // // $Log$ // Revision 1.4 2003/07/09 21:22:24 jmaurer // define str() before it is first used to avoid "redeclared inline after // begin called" error on IRIX MIPSpro // // Revision 1.3 2003/06/09 08:39:28 rogeeff // 1.30.beta1 // // *************************************************************************** #endif // BOOST_WRAP_STRINGSTREAM_HPP <|endoftext|>
<commit_before>#include "Helper.h" #include "cmath" #include "time.h" #include <QDir> #include <QCoreApplication> #include <QDateTime> void Helper::randomInit() { int seconds = time(NULL); int milliseconds = QTime::currentTime().msec(); int process_id = QCoreApplication::applicationPid(); srand(seconds + milliseconds + process_id + rand()); } double Helper::randomNumber(double min, double max) { double r = (double)rand() / (double)RAND_MAX; return min + r * (max - min); } QString Helper::randomString(int length, const QString& chars, bool init) { //initialize random number generator if (init) randomInit(); //create random string QString output; for (int i=0; i<length; ++i) { output.append(chars[rand() % chars.length()]); } return output; } QByteArray Helper::elapsedTime(QTime elapsed, bool only_seconds) { //calculate minutes and seconds double s = elapsed.elapsed()/1000.0; double m = 0; double h = 0; if (!only_seconds) { m = floor(s/60.0); s -= 60.0 * m; h = floor(m/60.0); m -= 60.0 * h; } //create strings QByteArray sec = QByteArray::number(s, 'f', 3) + "s"; QByteArray min = m==0.0 ? "" : QByteArray::number(m, 'f', 0) + "m "; QByteArray hours = h==0.0 ? "" : QByteArray::number(h, 'f', 0) + "h "; return hours + min + sec; } QStringList Helper::loadTextFile(QString file_name, bool trim_lines, QChar skip_header_char, bool skip_empty_lines) { QStringList output; VersatileTextStream stream(file_name); while (!stream.atEnd()) { QString line = stream.readLine(); //remove newline or trim if (trim_lines) { line = line.trimmed(); } else { while (line.endsWith('\n') || line.endsWith('\r')) line.chop(1); } //skip empty lines if (skip_empty_lines && line.count()==0) continue; //skip header lines if (skip_header_char!=QChar::Null && line.count()!=0 && line[0]==skip_header_char) continue; output.append(line); } return output; } void Helper::storeTextFile(QSharedPointer<QFile> file, const QStringList& lines) { QTextStream stream(file.data()); foreach(QString line, lines) { while (line.endsWith('\n') || line.endsWith('\r')) line.chop(1); stream << line << "\n"; } } void Helper::storeTextFile(QString file_name, const QStringList& lines) { storeTextFile(openFileForWriting(file_name), lines); } QString Helper::fileText(QString filename) { QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { THROW(FileAccessException, "Could not open text file for reading: '" + filename + "'!"); } QTextStream stream(&file); // we need a text stream to support UTF8 characters return stream.readAll(); } void Helper::touchFile(QString filename) { if (!QFile(filename).open(QFile::ReadWrite)) { THROW(FileAccessException, "Could not open file for writing: '" + filename + "'!"); } } QString Helper::tempFileName(QString extension, int length) { QString name = Helper::randomString(length); if (extension!="") { if (!extension.startsWith(".")) name.append("."); name.append(extension); } return Helper::canonicalPath(QDir::tempPath() + "/" + name); } QStringList Helper::findFiles(const QString& directory, const QString& pattern, bool recursive) { QStringList output; QDir dir(directory); if(!dir.exists()) THROW(FileAccessException, "Directory does not exist: " + directory); QFileInfoList file_infos = dir.entryInfoList(QStringList() << pattern, QDir::Files); foreach(const QFileInfo& entry, file_infos) { output.append(directory + "/" + entry.fileName()); } if (recursive) { file_infos = dir.entryInfoList(QDir::AllDirs|QDir::NoDotAndDotDot); foreach(const QFileInfo& entry, file_infos) { output << findFiles(directory + "/" + entry.fileName(), pattern, true); } } return output; } QStringList Helper::findFolders(const QString& directory, const QString& pattern, bool recursive) { QStringList output; QDir dir(directory); if(!dir.exists()) THROW(FileAccessException, "Directory does not exist: " + directory); QFileInfoList file_infos = dir.entryInfoList(QStringList() << pattern, QDir::Dirs|QDir::NoDotAndDotDot); foreach(const QFileInfo& entry, file_infos) { output.append(directory + "/" + entry.fileName()); } if (recursive) { file_infos = dir.entryInfoList(QDir::AllDirs|QDir::NoDotAndDotDot); foreach(const QFileInfo& entry, file_infos) { output << findFolders(directory + "/" + entry.fileName(), pattern, true); } } return output; } int Helper::levenshtein(const QString& s1, const QString& s2) { const int len1 = s1.size(); const int len2 = s2.size(); QVector<int> col(len2+1); QVector<int> prevCol(len2+1); for (int i=0; i<prevCol.size(); ++i) { prevCol[i] = i; } for (int i=0; i<len1; ++i) { col[0] = i+1; for (int j = 0; j < len2; j++) { col[j+1] = std::min( std::min(prevCol[1 + j] + 1, col[j] + 1), prevCol[j] + (s1[i]==s2[j] ? 0 : 1) ); } col.swap(prevCol); } return prevCol[len2]; } QString Helper::userName() { return qgetenv(isWindows() ? "USERNAME" : "USER"); } QString Helper::dateTime(QString format) { if (format=="") { return QDateTime::currentDateTime().toString(Qt::ISODate); } return QDateTime::currentDateTime().toString(format); } bool Helper::isWritable(QString filename) { if (QFile::exists(filename)) { QFileInfo file_info(filename); if (!file_info.isFile() || !file_info.isWritable()) { return false; } } else { QString dir = QFileInfo(filename).absolutePath(); QFileInfo dir_info(dir); if (!dir_info.isDir() || !dir_info.isWritable()) { return false; } } return true; } QString Helper::canonicalPath(QString filename) { if (filename.startsWith("http")) return filename; //Use native separator for the current OS filename = QDir::toNativeSeparators(filename).trimmed(); if (filename.isEmpty()) return filename; //double > single separator (except for first character in case of UNC path) QChar sep = QDir::separator(); QString sep_twice = QString(sep)+sep; while(filename.mid(1).contains(sep_twice)) { filename = filename.at(0) + filename.mid(1).replace(sep_twice, sep); } //remove "." QStringList parts = filename.split(sep); while (parts.contains(".")) { int index = parts.indexOf("."); if (index==0) break; parts.removeAt(index); } //remove ".." and folder before it while (parts.contains("..")) { int index = parts.indexOf(".."); if (index<=1) break; parts.removeAt(index); parts.removeAt(index-1); } return parts.join(sep); } bool Helper::isWindows() { #ifdef _WIN32 return true; #else return false; #endif } bool Helper::isMacOS() { #ifdef __APPLE__ return true; #else return false; #endif } bool Helper::isLinux() { #ifdef __linux__ return true; #else return false; #endif } QSharedPointer<QFile> Helper::openFileForReading(QString file_name, bool stdin_if_empty) { QSharedPointer<QFile> file(new QFile(file_name)); if (stdin_if_empty && file_name=="") { file->open(stdin, QFile::ReadOnly | QIODevice::Text); } else if (!file->open(QFile::ReadOnly | QIODevice::Text)) { THROW(FileAccessException, "Could not open file for reading: '" + file_name + "'!"); } return file; } QSharedPointer<VersatileFile> Helper::openVersatileFileForReading(QString file_name, bool stdin_if_empty) { QSharedPointer<VersatileFile> file(new VersatileFile(file_name)); if (stdin_if_empty && file_name=="") { file->open(stdin, QFile::ReadOnly | QIODevice::Text); } else if (!file->open(QFile::ReadOnly | QIODevice::Text)) { THROW(FileAccessException, "Could not open versatile file for reading: '" + file_name + "'!"); } return file; } QSharedPointer<QFile> Helper::openFileForWriting(QString file_name, bool stdout_if_file_empty, bool append) { QSharedPointer<QFile> file(new QFile(file_name)); if (stdout_if_file_empty && file_name=="") { file->open(stdout, QFile::WriteOnly | QIODevice::Text); } else if (!file->open(QFile::WriteOnly | QIODevice::Text |(append? QFile::Append : QFile::Truncate))) { THROW(FileAccessException, "Could not open file for writing: '" + file_name + "'!"); } return file; } QString Helper::serverApiUrl(const bool& return_http) { QString protocol = "https://"; QString port = Settings::string("https_server_port", true); if (return_http) { protocol = "http://"; port = Settings::string("http_server_port", true); } return protocol + Settings::string("server_host", true) + ":" + port + "/v1/"; } <commit_msg>Updated error message text.<commit_after>#include "Helper.h" #include "cmath" #include "time.h" #include <QDir> #include <QCoreApplication> #include <QDateTime> void Helper::randomInit() { int seconds = time(NULL); int milliseconds = QTime::currentTime().msec(); int process_id = QCoreApplication::applicationPid(); srand(seconds + milliseconds + process_id + rand()); } double Helper::randomNumber(double min, double max) { double r = (double)rand() / (double)RAND_MAX; return min + r * (max - min); } QString Helper::randomString(int length, const QString& chars, bool init) { //initialize random number generator if (init) randomInit(); //create random string QString output; for (int i=0; i<length; ++i) { output.append(chars[rand() % chars.length()]); } return output; } QByteArray Helper::elapsedTime(QTime elapsed, bool only_seconds) { //calculate minutes and seconds double s = elapsed.elapsed()/1000.0; double m = 0; double h = 0; if (!only_seconds) { m = floor(s/60.0); s -= 60.0 * m; h = floor(m/60.0); m -= 60.0 * h; } //create strings QByteArray sec = QByteArray::number(s, 'f', 3) + "s"; QByteArray min = m==0.0 ? "" : QByteArray::number(m, 'f', 0) + "m "; QByteArray hours = h==0.0 ? "" : QByteArray::number(h, 'f', 0) + "h "; return hours + min + sec; } QStringList Helper::loadTextFile(QString file_name, bool trim_lines, QChar skip_header_char, bool skip_empty_lines) { QStringList output; VersatileTextStream stream(file_name); while (!stream.atEnd()) { QString line = stream.readLine(); //remove newline or trim if (trim_lines) { line = line.trimmed(); } else { while (line.endsWith('\n') || line.endsWith('\r')) line.chop(1); } //skip empty lines if (skip_empty_lines && line.count()==0) continue; //skip header lines if (skip_header_char!=QChar::Null && line.count()!=0 && line[0]==skip_header_char) continue; output.append(line); } return output; } void Helper::storeTextFile(QSharedPointer<QFile> file, const QStringList& lines) { QTextStream stream(file.data()); foreach(QString line, lines) { while (line.endsWith('\n') || line.endsWith('\r')) line.chop(1); stream << line << "\n"; } } void Helper::storeTextFile(QString file_name, const QStringList& lines) { storeTextFile(openFileForWriting(file_name), lines); } QString Helper::fileText(QString filename) { QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { THROW(FileAccessException, "Could not open text file for reading: '" + filename + "'!"); } QTextStream stream(&file); // we need a text stream to support UTF8 characters return stream.readAll(); } void Helper::touchFile(QString filename) { if (!QFile(filename).open(QFile::ReadWrite)) { THROW(FileAccessException, "Could not open file for writing: '" + filename + "'!"); } } QString Helper::tempFileName(QString extension, int length) { QString name = Helper::randomString(length); if (extension!="") { if (!extension.startsWith(".")) name.append("."); name.append(extension); } return Helper::canonicalPath(QDir::tempPath() + "/" + name); } QStringList Helper::findFiles(const QString& directory, const QString& pattern, bool recursive) { QStringList output; QDir dir(directory); if(!dir.exists()) THROW(FileAccessException, "Directory does not exist: " + directory); QFileInfoList file_infos = dir.entryInfoList(QStringList() << pattern, QDir::Files); foreach(const QFileInfo& entry, file_infos) { output.append(directory + "/" + entry.fileName()); } if (recursive) { file_infos = dir.entryInfoList(QDir::AllDirs|QDir::NoDotAndDotDot); foreach(const QFileInfo& entry, file_infos) { output << findFiles(directory + "/" + entry.fileName(), pattern, true); } } return output; } QStringList Helper::findFolders(const QString& directory, const QString& pattern, bool recursive) { QStringList output; QDir dir(directory); if(!dir.exists()) THROW(FileAccessException, "Directory does not exist: " + directory); QFileInfoList file_infos = dir.entryInfoList(QStringList() << pattern, QDir::Dirs|QDir::NoDotAndDotDot); foreach(const QFileInfo& entry, file_infos) { output.append(directory + "/" + entry.fileName()); } if (recursive) { file_infos = dir.entryInfoList(QDir::AllDirs|QDir::NoDotAndDotDot); foreach(const QFileInfo& entry, file_infos) { output << findFolders(directory + "/" + entry.fileName(), pattern, true); } } return output; } int Helper::levenshtein(const QString& s1, const QString& s2) { const int len1 = s1.size(); const int len2 = s2.size(); QVector<int> col(len2+1); QVector<int> prevCol(len2+1); for (int i=0; i<prevCol.size(); ++i) { prevCol[i] = i; } for (int i=0; i<len1; ++i) { col[0] = i+1; for (int j = 0; j < len2; j++) { col[j+1] = std::min( std::min(prevCol[1 + j] + 1, col[j] + 1), prevCol[j] + (s1[i]==s2[j] ? 0 : 1) ); } col.swap(prevCol); } return prevCol[len2]; } QString Helper::userName() { return qgetenv(isWindows() ? "USERNAME" : "USER"); } QString Helper::dateTime(QString format) { if (format=="") { return QDateTime::currentDateTime().toString(Qt::ISODate); } return QDateTime::currentDateTime().toString(format); } bool Helper::isWritable(QString filename) { if (QFile::exists(filename)) { QFileInfo file_info(filename); if (!file_info.isFile() || !file_info.isWritable()) { return false; } } else { QString dir = QFileInfo(filename).absolutePath(); QFileInfo dir_info(dir); if (!dir_info.isDir() || !dir_info.isWritable()) { return false; } } return true; } QString Helper::canonicalPath(QString filename) { if (filename.startsWith("http")) return filename; //Use native separator for the current OS filename = QDir::toNativeSeparators(filename).trimmed(); if (filename.isEmpty()) return filename; //double > single separator (except for first character in case of UNC path) QChar sep = QDir::separator(); QString sep_twice = QString(sep)+sep; while(filename.mid(1).contains(sep_twice)) { filename = filename.at(0) + filename.mid(1).replace(sep_twice, sep); } //remove "." QStringList parts = filename.split(sep); while (parts.contains(".")) { int index = parts.indexOf("."); if (index==0) break; parts.removeAt(index); } //remove ".." and folder before it while (parts.contains("..")) { int index = parts.indexOf(".."); if (index<=1) break; parts.removeAt(index); parts.removeAt(index-1); } return parts.join(sep); } bool Helper::isWindows() { #ifdef _WIN32 return true; #else return false; #endif } bool Helper::isMacOS() { #ifdef __APPLE__ return true; #else return false; #endif } bool Helper::isLinux() { #ifdef __linux__ return true; #else return false; #endif } QSharedPointer<QFile> Helper::openFileForReading(QString file_name, bool stdin_if_empty) { QSharedPointer<QFile> file(new QFile(file_name)); if (stdin_if_empty && file_name=="") { file->open(stdin, QFile::ReadOnly | QIODevice::Text); } else if (!file->open(QFile::ReadOnly | QIODevice::Text)) { THROW(FileAccessException, "Could not open file for reading: '" + file_name + "'!"); } return file; } QSharedPointer<VersatileFile> Helper::openVersatileFileForReading(QString file_name, bool stdin_if_empty) { QSharedPointer<VersatileFile> file(new VersatileFile(file_name)); if (stdin_if_empty && file_name=="") { file->open(stdin, QFile::ReadOnly | QIODevice::Text); } else if (!file->open(QFile::ReadOnly | QIODevice::Text)) { THROW(FileAccessException, "Could not open file for reading: '" + file_name + "'!"); } return file; } QSharedPointer<QFile> Helper::openFileForWriting(QString file_name, bool stdout_if_file_empty, bool append) { QSharedPointer<QFile> file(new QFile(file_name)); if (stdout_if_file_empty && file_name=="") { file->open(stdout, QFile::WriteOnly | QIODevice::Text); } else if (!file->open(QFile::WriteOnly | QIODevice::Text |(append? QFile::Append : QFile::Truncate))) { THROW(FileAccessException, "Could not open file for writing: '" + file_name + "'!"); } return file; } QString Helper::serverApiUrl(const bool& return_http) { QString protocol = "https://"; QString port = Settings::string("https_server_port", true); if (return_http) { protocol = "http://"; port = Settings::string("http_server_port", true); } return protocol + Settings::string("server_host", true) + ":" + port + "/v1/"; } <|endoftext|>
<commit_before>#pragma once // C++ standard library #include <vector> #include <utility> #include <memory> // Armadillo #include <armadillo> // Mantella #include <mantella_bits/helper/printable.hpp> #include <mantella_bits/optimisationProblem.hpp> namespace mant { #if defined(MANTELLA_USE_MPI) void mpiGetBestParameter( void* firstInput, void* secondInput, int* size, MPI_Datatype* type); #endif class OptimisationAlgorithm : public Printable { public: explicit OptimisationAlgorithm( const std::shared_ptr<OptimisationProblem> optimisationProblem); void optimise(); void setMaximalNumberOfIterations( const arma::uword maximalNumberOfIterations); arma::uword getNumberOfIterations() const; arma::uword getMaximalNumberOfIterations() const; double getBestObjectiveValue() const; arma::Col<double> getBestParameter() const; bool isFinished() const; virtual bool isTerminated() const; std::vector<std::pair<arma::Col<double>, double>> getSamplingProgress() const; virtual ~OptimisationAlgorithm() = default; private: std::shared_ptr<OptimisationProblem> optimisationProblem_; protected: const arma::uword numberOfDimensions_; arma::uword numberOfIterations_; arma::uword maximalNumberOfIterations_; double bestObjectiveValue_; arma::Col<double> bestParameter_; std::vector<std::pair<arma::Col<double>, double>> samplingProgress_; int nodeRank_; int numberOfNodes_; arma::Col<double> getLowerBounds() const; arma::Col<double> getUpperBounds() const; arma::Col<arma::uword> isWithinLowerBounds( const arma::Col<double>& parameter) const; arma::Col<arma::uword> isWithinUpperBounds( const arma::Col<double>& parameter) const; double getAcceptableObjectiveValue() const; double getObjectiveValue( const arma::Col<double>& parameter); arma::Col<double> getRandomParameter() const; arma::Col<double> getRandomNeighbour( const arma::Col<double>& parameter, const double minimalDistance, const double maximalDistance) const; bool updateBestParameter( const arma::Col<double>& parameter, const double objectiveValue); virtual void optimiseImplementation() = 0; }; }<commit_msg>updated getRandomNeighbour<commit_after>#pragma once // C++ standard library #include <vector> #include <utility> #include <memory> // Armadillo #include <armadillo> // Mantella #include <mantella_bits/helper/printable.hpp> #include <mantella_bits/optimisationProblem.hpp> namespace mant { #if defined(MANTELLA_USE_MPI) void mpiGetBestParameter( void* firstInput, void* secondInput, int* size, MPI_Datatype* type); #endif class OptimisationAlgorithm : public Printable { public: explicit OptimisationAlgorithm( const std::shared_ptr<OptimisationProblem> optimisationProblem); void optimise(); void setMaximalNumberOfIterations( const arma::uword maximalNumberOfIterations); arma::uword getNumberOfIterations() const; arma::uword getMaximalNumberOfIterations() const; double getBestObjectiveValue() const; arma::Col<double> getBestParameter() const; bool isFinished() const; virtual bool isTerminated() const; std::vector<std::pair<arma::Col<double>, double>> getSamplingProgress() const; virtual ~OptimisationAlgorithm() = default; private: std::shared_ptr<OptimisationProblem> optimisationProblem_; protected: const arma::uword numberOfDimensions_; arma::uword numberOfIterations_; arma::uword maximalNumberOfIterations_; double bestObjectiveValue_; arma::Col<double> bestParameter_; std::vector<std::pair<arma::Col<double>, double>> samplingProgress_; int nodeRank_; int numberOfNodes_; arma::Col<double> getLowerBounds() const; arma::Col<double> getUpperBounds() const; arma::Col<arma::uword> isWithinLowerBounds( const arma::Col<double>& parameter) const; arma::Col<arma::uword> isWithinUpperBounds( const arma::Col<double>& parameter) const; double getAcceptableObjectiveValue() const; double getObjectiveValue( const arma::Col<double>& parameter); arma::Col<double> getRandomParameter() const; virtual arma::Col<double> getRandomNeighbour( const arma::Col<double>& parameter, const double minimalDistance, const double maximalDistance) const; bool updateBestParameter( const arma::Col<double>& parameter, const double objectiveValue); virtual void optimiseImplementation() = 0; }; }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fmdispatch.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-04-13 11:01:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SVX_FMDISPATCH_HXX #define SVX_FMDISPATCH_HXX #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif //........................................................................ namespace svx { //........................................................................ class FormControllerHelper; //==================================================================== //= OSingleFeatureDispatcher //==================================================================== typedef ::cppu::WeakImplHelper1 < ::com::sun::star::frame::XDispatch > OSingleFeatureDispatcher_Base; class OSingleFeatureDispatcher : public OSingleFeatureDispatcher_Base { private: ::osl::Mutex& m_rMutex; ::cppu::OInterfaceContainerHelper m_aStatusListeners; const FormControllerHelper& m_rController; const ::com::sun::star::util::URL m_aFeatureURL; ::com::sun::star::uno::Any m_aLastKnownState; const sal_Int32 m_nFeatureId; sal_Bool m_bLastKnownEnabled; sal_Bool m_bDisposed; public: /** constructs the dispatcher @param _rFeatureURL the URL of the feature which this instance is responsible for @param _nFeatureId the feature which this instance is responsible for @param _rController the controller which is responsible for providing the state of feature of this instance, and for executing it. After disposing the dispatcher instance, the controller will not be accessed anymore @see dispose */ OSingleFeatureDispatcher( const ::com::sun::star::util::URL& _rFeatureURL, sal_Int32 _nFeatureId, const FormControllerHelper& _rController, ::osl::Mutex& _rMutex ); /** disposes the dispatcher instance All status listeners will, after receiving an <member scope="com::sun::star::lang">XEventListener::disposing</member> call, be released. The controller provided in the in constructor will not be used anymore after returning from this call. No further requests to dispatch slots will be accepted. Multiple calls are allowed: if the object already was disposed, then subsequent calls are silently ignored. */ void dispose(); /** notifies all our listeners of the current state */ void updateAllListeners(); protected: // XDispatch virtual void SAL_CALL dispatch( const ::com::sun::star::util::URL& _rURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& _rxControl, const ::com::sun::star::util::URL& _rURL ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& _rxControl, const ::com::sun::star::util::URL& _rURL ) throw (::com::sun::star::uno::RuntimeException); protected: /** notifies our current state to one or all listeners @param _rxListener the listener to notify. May be NULL, in this case all our listeners will be notified with the current state @param _rFreeForNotification a guard which currently locks our mutex, and which is to be cleared for actually doing the notification(s) */ void notifyStatus( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& _rxListener, ::osl::ClearableMutexGuard& _rFreeForNotification ); private: /** checks whether our instance is alive If the instance already received a <member>dispose</member> call, then a <type scope="com::sun::star::lang">DisposedException</type> is thrown. @precond our Mutex is locked - else calling the method would not make sense, since it's result could be out-of-date as soon as it's returned to the caller. */ void checkAlive() const SAL_THROW((::com::sun::star::lang::DisposedException)); /** retrieves the current status of our feature, in a format which can be used for UNO notifications @precond our mutex is locked */ void getUnoState( ::com::sun::star::frame::FeatureStateEvent& /* [out] */ _rState ) const; private: OSingleFeatureDispatcher(); // never implemented OSingleFeatureDispatcher( const OSingleFeatureDispatcher& ); // never implemented OSingleFeatureDispatcher& operator=( const OSingleFeatureDispatcher& ); // never implemented }; //........................................................................ } // namespace svx //........................................................................ #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.2.946); FILE MERGED 2005/09/05 14:25:05 rt 1.2.946.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fmdispatch.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 23:15:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SVX_FMDISPATCH_HXX #define SVX_FMDISPATCH_HXX #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif //........................................................................ namespace svx { //........................................................................ class FormControllerHelper; //==================================================================== //= OSingleFeatureDispatcher //==================================================================== typedef ::cppu::WeakImplHelper1 < ::com::sun::star::frame::XDispatch > OSingleFeatureDispatcher_Base; class OSingleFeatureDispatcher : public OSingleFeatureDispatcher_Base { private: ::osl::Mutex& m_rMutex; ::cppu::OInterfaceContainerHelper m_aStatusListeners; const FormControllerHelper& m_rController; const ::com::sun::star::util::URL m_aFeatureURL; ::com::sun::star::uno::Any m_aLastKnownState; const sal_Int32 m_nFeatureId; sal_Bool m_bLastKnownEnabled; sal_Bool m_bDisposed; public: /** constructs the dispatcher @param _rFeatureURL the URL of the feature which this instance is responsible for @param _nFeatureId the feature which this instance is responsible for @param _rController the controller which is responsible for providing the state of feature of this instance, and for executing it. After disposing the dispatcher instance, the controller will not be accessed anymore @see dispose */ OSingleFeatureDispatcher( const ::com::sun::star::util::URL& _rFeatureURL, sal_Int32 _nFeatureId, const FormControllerHelper& _rController, ::osl::Mutex& _rMutex ); /** disposes the dispatcher instance All status listeners will, after receiving an <member scope="com::sun::star::lang">XEventListener::disposing</member> call, be released. The controller provided in the in constructor will not be used anymore after returning from this call. No further requests to dispatch slots will be accepted. Multiple calls are allowed: if the object already was disposed, then subsequent calls are silently ignored. */ void dispose(); /** notifies all our listeners of the current state */ void updateAllListeners(); protected: // XDispatch virtual void SAL_CALL dispatch( const ::com::sun::star::util::URL& _rURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& _rxControl, const ::com::sun::star::util::URL& _rURL ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& _rxControl, const ::com::sun::star::util::URL& _rURL ) throw (::com::sun::star::uno::RuntimeException); protected: /** notifies our current state to one or all listeners @param _rxListener the listener to notify. May be NULL, in this case all our listeners will be notified with the current state @param _rFreeForNotification a guard which currently locks our mutex, and which is to be cleared for actually doing the notification(s) */ void notifyStatus( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& _rxListener, ::osl::ClearableMutexGuard& _rFreeForNotification ); private: /** checks whether our instance is alive If the instance already received a <member>dispose</member> call, then a <type scope="com::sun::star::lang">DisposedException</type> is thrown. @precond our Mutex is locked - else calling the method would not make sense, since it's result could be out-of-date as soon as it's returned to the caller. */ void checkAlive() const SAL_THROW((::com::sun::star::lang::DisposedException)); /** retrieves the current status of our feature, in a format which can be used for UNO notifications @precond our mutex is locked */ void getUnoState( ::com::sun::star::frame::FeatureStateEvent& /* [out] */ _rState ) const; private: OSingleFeatureDispatcher(); // never implemented OSingleFeatureDispatcher( const OSingleFeatureDispatcher& ); // never implemented OSingleFeatureDispatcher& operator=( const OSingleFeatureDispatcher& ); // never implemented }; //........................................................................ } // namespace svx //........................................................................ #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: frmselimpl.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 23:23:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SVX_FRMSELIMPL_HXX #define SVX_FRMSELIMPL_HXX #ifndef _SV_VIRDEV_HXX #include <vcl/virdev.hxx> #endif #ifndef _SV_IMAGE_HXX #include <vcl/image.hxx> #endif #ifndef SVX_FRMSEL_HXX #include "frmsel.hxx" #endif #ifndef SVX_FRAMELINKARRAY_HXX #include "framelinkarray.hxx" #endif #ifndef SVX_BORDERLINE_HXX #include "borderline.hxx" #endif namespace svx { namespace a11y { class AccFrameSelector; } // ============================================================================ class FrameBorder { public: explicit FrameBorder( FrameBorderType eType ); inline FrameBorderType GetType() const { return meType; } inline bool IsEnabled() const { return mbEnabled; } void Enable( FrameSelFlags nFlags ); inline FrameBorderState GetState() const { return meState; } void SetState( FrameBorderState eState ); inline bool IsSelected() const { return mbSelected; } inline void Select( bool bSelect ) { mbSelected = bSelect; } const SvxBorderLine& GetCoreStyle() const { return maCoreStyle; } void SetCoreStyle( const SvxBorderLine* pStyle ); inline void SetUIColor( const Color& rColor ) {maUIStyle.SetColor( rColor ); } inline const frame::Style& GetUIStyle() const { return maUIStyle; } inline void ClearFocusArea() { maFocusArea.Clear(); } void AddFocusPolygon( const Polygon& rFocus ); void MergeFocusToPolyPolygon( PolyPolygon& rPPoly ) const; inline void ClearClickArea() { maClickArea.Clear(); } void AddClickRect( const Rectangle& rRect ); bool ContainsClickPoint( const Point& rPos ) const; void MergeClickAreaToPolyPolygon( PolyPolygon& rPPoly ) const; Rectangle GetClickBoundRect() const; void SetKeyboardNeighbors( FrameBorderType eLeft, FrameBorderType eRight, FrameBorderType eTop, FrameBorderType eBottom ); FrameBorderType GetKeyboardNeighbor( USHORT nKeyCode ) const; private: const FrameBorderType meType; /// Frame border type (position in control). FrameBorderState meState; /// Frame border state (on/off/don't care). SvxBorderLine maCoreStyle; /// Core style from application. frame::Style maUIStyle; /// Internal style to draw lines. FrameBorderType meKeyLeft; /// Left neighbor for keyboard control. FrameBorderType meKeyRight; /// Right neighbor for keyboard control. FrameBorderType meKeyTop; /// Upper neighbor for keyboard control. FrameBorderType meKeyBottom; /// Lower neighbor for keyboard control. PolyPolygon maFocusArea; /// Focus drawing areas. PolyPolygon maClickArea; /// Mouse click areas. bool mbEnabled; /// true = Border enabled in control. bool mbSelected; /// true = Border selected in control. }; // ============================================================================ typedef std::vector< FrameBorder* > FrameBorderPtrVec; struct FrameSelectorImpl : public Resource { typedef ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > XAccessibleRef; typedef std::vector< a11y::AccFrameSelector* > AccessibleImplVec; typedef std::vector< XAccessibleRef > XAccessibleRefVec; FrameSelector& mrFrameSel; /// The control itself. VirtualDevice maVirDev; /// For all buffered drawing operations. const Bitmap maBmpArrows; /// Original arrows bitmap from resource. ImageList maILArrows; /// Arrows in current system colors. Color maBackCol; /// Background color. Color maArrowCol; /// Selection arrow color. Color maMarkCol; /// Selection marker color. Color maHCLineCol; /// High contrast line color. Point maVirDevPos; /// Position of virtual device in the control. Point maMousePos; /// Last mouse pointer position. FrameBorder maLeft; /// All data of left frame border. FrameBorder maRight; /// All data of right frame border. FrameBorder maTop; /// All data of top frame border. FrameBorder maBottom; /// All data of bottom frame border. FrameBorder maHor; /// All data of inner horizontal frame border. FrameBorder maVer; /// All data of inner vertical frame border. FrameBorder maTLBR; /// All data of top-left to bottom-right frame border. FrameBorder maBLTR; /// All data of bottom-left to top-right frame border. SvxBorderLine maCurrStyle; /// Current style and color for new borders. frame::Array maArray; /// Frame link array to draw an array of frame borders. FrameSelFlags mnFlags; /// Flags for enabled frame borders. FrameBorderPtrVec maAllBorders; /// Pointers to all frame borders. FrameBorderPtrVec maEnabBorders; /// Pointers to enables frame borders. Link maSelectHdl; /// Selection handler. long mnCtrlSize; /// Size of the control (always square). long mnArrowSize; /// Size of an arrow image. long mnLine1; /// Middle of left/top frame borders. long mnLine2; /// Middle of inner frame borders. long mnLine3; /// Middle of right/bottom frame borders. long mnFocusOffs; /// Offset from frame border middle to draw focus. bool mbHor; /// true = Inner horizontal frame border enabled. bool mbVer; /// true = Inner vertical frame border enabled. bool mbTLBR; /// true = Top-left to bottom-right frame border enabled. bool mbBLTR; /// true = Bottom-left to top-right frame border enabled. bool mbFullRepaint; /// Used for repainting (false = only copy virtual device). bool mbAutoSelect; /// true = Auto select a frame border, if focus reaches control. bool mbClicked; /// true = The control has been clicked at least one time. bool mbHCMode; /// true = High contrast mode. a11y::AccFrameSelector* mpAccess; /// Pointer to accessibility object of the control. XAccessibleRef mxAccess; /// Reference to accessibility object of the control. AccessibleImplVec maChildVec; /// Pointers to accessibility objects for frame borders. XAccessibleRefVec mxChildVec; /// References to accessibility objects for frame borders. explicit FrameSelectorImpl( FrameSelector& rFrameSel ); ~FrameSelectorImpl(); // initialization --------------------------------------------------------- /** Initializes the control, enables/disables frame borders according to flags. */ void Initialize( FrameSelFlags nFlags ); /** Fills all color members from current style settings. */ void InitColors(); /** Creates the image list with selection arrows regarding current style settings. */ void InitArrowImageList(); /** Initializes global coordinates. */ void InitGlobalGeometry(); /** Initializes coordinates of all frame borders. */ void InitBorderGeometry(); /** Initializes click areas of all enabled frame borders. */ void InitClickAreas(); /** Draws the entire control into the internal virtual device. */ void InitVirtualDevice(); // frame border access ---------------------------------------------------- /** Returns the object representing the specified frame border. */ const FrameBorder& GetBorder( FrameBorderType eBorder ) const; /** Returns the object representing the specified frame border (write access). */ FrameBorder& GetBorderAccess( FrameBorderType eBorder ); // drawing ---------------------------------------------------------------- /** Draws the background of the entire control (the gray areas between borders). */ void DrawBackground(); /** Draws selection arrows for the specified frame border. */ void DrawArrows( const FrameBorder& rBorder ); /** Draws arrows in current selection state for all enabled frame borders. */ void DrawAllArrows(); /** Returns the color that has to be used to draw a frame border. */ Color GetDrawLineColor( const Color& rColor ) const; /** Draws all frame borders. */ void DrawAllFrameBorders(); /** Draws all contents of the control. */ void DrawVirtualDevice(); /** Copies contents of the virtual device to the control. */ void CopyVirDevToControl(); /** Draws tracking rectangles for all selected frame borders. */ void DrawAllTrackingRects(); /** Converts a mouse position to the virtual device position. */ Point GetDevPosFromMousePos( const Point& rMousePos ) const; /** Invalidates the control. @param bFullRepaint true = Full repaint; false = update selection only. */ void DoInvalidate( bool bFullRepaint ); // frame border state and style ------------------------------------------- /** Sets the state of the specified frame border. */ void SetBorderState( FrameBorder& rBorder, FrameBorderState eState ); /** Sets the core style of the specified frame border, or hides the frame border, if pStyle is 0. */ void SetBorderCoreStyle( FrameBorder& rBorder, const SvxBorderLine* pStyle ); /** Sets the color of the specified frame border. */ void SetBorderColor( FrameBorder& rBorder, const Color& rColor ); /** Changes the state of a frame border after a control event (mouse/keyboard). */ void ToggleBorderState( FrameBorder& rBorder ); // frame border selection ------------------------------------------------- /** Selects a frame border and schedules redraw. */ void SelectBorder( FrameBorder& rBorder, bool bSelect ); /** Grabs focus without auto-selection of a frame border, if no border selected. */ void SilentGrabFocus(); /** Returns true, if all selected frame borders are equal (or if nothing is selected). */ bool SelectedBordersEqual() const; }; // ============================================================================ /** Dummy predicate for frame border iterators to use all borders in a container. */ struct FrameBorderDummy_Pred { inline bool operator()( const FrameBorder* ) const { return true; } }; /** Predicate for frame border iterators to use only visible borders in a container. */ struct FrameBorderVisible_Pred { inline bool operator()( const FrameBorder* pBorder ) const { return pBorder->GetState() == FRAMESTATE_SHOW; } }; /** Predicate for frame border iterators to use only selected borders in a container. */ struct FrameBorderSelected_Pred { inline bool operator()( const FrameBorder* pBorder ) const { return pBorder->IsSelected(); } }; /** Template class for all types of frame border iterators. */ template< typename Cont, typename Iter, typename Pred > class FrameBorderIterBase { public: typedef Cont container_type; typedef Iter iterator_type; typedef Pred predicate_type; typedef typename Cont::value_type value_type; typedef FrameBorderIterBase< Cont, Iter, Pred > this_type; explicit FrameBorderIterBase( container_type& rCont ); inline bool Is() const { return maIt != maEnd; } this_type& operator++(); inline value_type operator*() const { return *maIt; } private: iterator_type maIt; iterator_type maEnd; predicate_type maPred; }; /** Iterator for constant svx::FrameBorder containers, iterates over all borders. */ typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderDummy_Pred > FrameBorderCIter; /** Iterator for mutable svx::FrameBorder containers, iterates over all borders. */ typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderDummy_Pred > FrameBorderIter; /** Iterator for constant svx::FrameBorder containers, iterates over visible borders. */ typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderVisible_Pred > VisFrameBorderCIter; /** Iterator for mutable svx::FrameBorder containers, iterates over visible borders. */ typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderVisible_Pred > VisFrameBorderIter; /** Iterator for constant svx::FrameBorder containers, iterates over selected borders. */ typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderSelected_Pred > SelFrameBorderCIter; /** Iterator for mutable svx::FrameBorder containers, iterates over selected borders. */ typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderSelected_Pred > SelFrameBorderIter; // ============================================================================ } // namespace svx #endif <commit_msg>INTEGRATION: CWS ka009 (1.3.392); FILE MERGED 2006/07/12 22:00:10 ka 1.3.392.1: #i66680#: added patch for optimized ImageList handling<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: frmselimpl.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: ihi $ $Date: 2007-06-06 14:07:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SVX_FRMSELIMPL_HXX #define SVX_FRMSELIMPL_HXX #ifndef _SV_VIRDEV_HXX #include <vcl/virdev.hxx> #endif #ifndef _SV_IMAGE_HXX #include <vcl/image.hxx> #endif #ifndef SVX_FRMSEL_HXX #include "frmsel.hxx" #endif #ifndef SVX_FRAMELINKARRAY_HXX #include "framelinkarray.hxx" #endif #ifndef SVX_BORDERLINE_HXX #include "borderline.hxx" #endif namespace svx { namespace a11y { class AccFrameSelector; } // ============================================================================ class FrameBorder { public: explicit FrameBorder( FrameBorderType eType ); inline FrameBorderType GetType() const { return meType; } inline bool IsEnabled() const { return mbEnabled; } void Enable( FrameSelFlags nFlags ); inline FrameBorderState GetState() const { return meState; } void SetState( FrameBorderState eState ); inline bool IsSelected() const { return mbSelected; } inline void Select( bool bSelect ) { mbSelected = bSelect; } const SvxBorderLine& GetCoreStyle() const { return maCoreStyle; } void SetCoreStyle( const SvxBorderLine* pStyle ); inline void SetUIColor( const Color& rColor ) {maUIStyle.SetColor( rColor ); } inline const frame::Style& GetUIStyle() const { return maUIStyle; } inline void ClearFocusArea() { maFocusArea.Clear(); } void AddFocusPolygon( const Polygon& rFocus ); void MergeFocusToPolyPolygon( PolyPolygon& rPPoly ) const; inline void ClearClickArea() { maClickArea.Clear(); } void AddClickRect( const Rectangle& rRect ); bool ContainsClickPoint( const Point& rPos ) const; void MergeClickAreaToPolyPolygon( PolyPolygon& rPPoly ) const; Rectangle GetClickBoundRect() const; void SetKeyboardNeighbors( FrameBorderType eLeft, FrameBorderType eRight, FrameBorderType eTop, FrameBorderType eBottom ); FrameBorderType GetKeyboardNeighbor( USHORT nKeyCode ) const; private: const FrameBorderType meType; /// Frame border type (position in control). FrameBorderState meState; /// Frame border state (on/off/don't care). SvxBorderLine maCoreStyle; /// Core style from application. frame::Style maUIStyle; /// Internal style to draw lines. FrameBorderType meKeyLeft; /// Left neighbor for keyboard control. FrameBorderType meKeyRight; /// Right neighbor for keyboard control. FrameBorderType meKeyTop; /// Upper neighbor for keyboard control. FrameBorderType meKeyBottom; /// Lower neighbor for keyboard control. PolyPolygon maFocusArea; /// Focus drawing areas. PolyPolygon maClickArea; /// Mouse click areas. bool mbEnabled; /// true = Border enabled in control. bool mbSelected; /// true = Border selected in control. }; // ============================================================================ typedef std::vector< FrameBorder* > FrameBorderPtrVec; struct FrameSelectorImpl : public Resource { typedef ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > XAccessibleRef; typedef std::vector< a11y::AccFrameSelector* > AccessibleImplVec; typedef std::vector< XAccessibleRef > XAccessibleRefVec; FrameSelector& mrFrameSel; /// The control itself. VirtualDevice maVirDev; /// For all buffered drawing operations. ImageList maILArrows; /// Arrows in current system colors. Color maBackCol; /// Background color. Color maArrowCol; /// Selection arrow color. Color maMarkCol; /// Selection marker color. Color maHCLineCol; /// High contrast line color. Point maVirDevPos; /// Position of virtual device in the control. Point maMousePos; /// Last mouse pointer position. FrameBorder maLeft; /// All data of left frame border. FrameBorder maRight; /// All data of right frame border. FrameBorder maTop; /// All data of top frame border. FrameBorder maBottom; /// All data of bottom frame border. FrameBorder maHor; /// All data of inner horizontal frame border. FrameBorder maVer; /// All data of inner vertical frame border. FrameBorder maTLBR; /// All data of top-left to bottom-right frame border. FrameBorder maBLTR; /// All data of bottom-left to top-right frame border. SvxBorderLine maCurrStyle; /// Current style and color for new borders. frame::Array maArray; /// Frame link array to draw an array of frame borders. FrameSelFlags mnFlags; /// Flags for enabled frame borders. FrameBorderPtrVec maAllBorders; /// Pointers to all frame borders. FrameBorderPtrVec maEnabBorders; /// Pointers to enables frame borders. Link maSelectHdl; /// Selection handler. long mnCtrlSize; /// Size of the control (always square). long mnArrowSize; /// Size of an arrow image. long mnLine1; /// Middle of left/top frame borders. long mnLine2; /// Middle of inner frame borders. long mnLine3; /// Middle of right/bottom frame borders. long mnFocusOffs; /// Offset from frame border middle to draw focus. bool mbHor; /// true = Inner horizontal frame border enabled. bool mbVer; /// true = Inner vertical frame border enabled. bool mbTLBR; /// true = Top-left to bottom-right frame border enabled. bool mbBLTR; /// true = Bottom-left to top-right frame border enabled. bool mbFullRepaint; /// Used for repainting (false = only copy virtual device). bool mbAutoSelect; /// true = Auto select a frame border, if focus reaches control. bool mbClicked; /// true = The control has been clicked at least one time. bool mbHCMode; /// true = High contrast mode. a11y::AccFrameSelector* mpAccess; /// Pointer to accessibility object of the control. XAccessibleRef mxAccess; /// Reference to accessibility object of the control. AccessibleImplVec maChildVec; /// Pointers to accessibility objects for frame borders. XAccessibleRefVec mxChildVec; /// References to accessibility objects for frame borders. explicit FrameSelectorImpl( FrameSelector& rFrameSel ); ~FrameSelectorImpl(); // initialization --------------------------------------------------------- /** Initializes the control, enables/disables frame borders according to flags. */ void Initialize( FrameSelFlags nFlags ); /** Fills all color members from current style settings. */ void InitColors(); /** Creates the image list with selection arrows regarding current style settings. */ void InitArrowImageList(); /** Initializes global coordinates. */ void InitGlobalGeometry(); /** Initializes coordinates of all frame borders. */ void InitBorderGeometry(); /** Initializes click areas of all enabled frame borders. */ void InitClickAreas(); /** Draws the entire control into the internal virtual device. */ void InitVirtualDevice(); // frame border access ---------------------------------------------------- /** Returns the object representing the specified frame border. */ const FrameBorder& GetBorder( FrameBorderType eBorder ) const; /** Returns the object representing the specified frame border (write access). */ FrameBorder& GetBorderAccess( FrameBorderType eBorder ); // drawing ---------------------------------------------------------------- /** Draws the background of the entire control (the gray areas between borders). */ void DrawBackground(); /** Draws selection arrows for the specified frame border. */ void DrawArrows( const FrameBorder& rBorder ); /** Draws arrows in current selection state for all enabled frame borders. */ void DrawAllArrows(); /** Returns the color that has to be used to draw a frame border. */ Color GetDrawLineColor( const Color& rColor ) const; /** Draws all frame borders. */ void DrawAllFrameBorders(); /** Draws all contents of the control. */ void DrawVirtualDevice(); /** Copies contents of the virtual device to the control. */ void CopyVirDevToControl(); /** Draws tracking rectangles for all selected frame borders. */ void DrawAllTrackingRects(); /** Converts a mouse position to the virtual device position. */ Point GetDevPosFromMousePos( const Point& rMousePos ) const; /** Invalidates the control. @param bFullRepaint true = Full repaint; false = update selection only. */ void DoInvalidate( bool bFullRepaint ); // frame border state and style ------------------------------------------- /** Sets the state of the specified frame border. */ void SetBorderState( FrameBorder& rBorder, FrameBorderState eState ); /** Sets the core style of the specified frame border, or hides the frame border, if pStyle is 0. */ void SetBorderCoreStyle( FrameBorder& rBorder, const SvxBorderLine* pStyle ); /** Sets the color of the specified frame border. */ void SetBorderColor( FrameBorder& rBorder, const Color& rColor ); /** Changes the state of a frame border after a control event (mouse/keyboard). */ void ToggleBorderState( FrameBorder& rBorder ); // frame border selection ------------------------------------------------- /** Selects a frame border and schedules redraw. */ void SelectBorder( FrameBorder& rBorder, bool bSelect ); /** Grabs focus without auto-selection of a frame border, if no border selected. */ void SilentGrabFocus(); /** Returns true, if all selected frame borders are equal (or if nothing is selected). */ bool SelectedBordersEqual() const; }; // ============================================================================ /** Dummy predicate for frame border iterators to use all borders in a container. */ struct FrameBorderDummy_Pred { inline bool operator()( const FrameBorder* ) const { return true; } }; /** Predicate for frame border iterators to use only visible borders in a container. */ struct FrameBorderVisible_Pred { inline bool operator()( const FrameBorder* pBorder ) const { return pBorder->GetState() == FRAMESTATE_SHOW; } }; /** Predicate for frame border iterators to use only selected borders in a container. */ struct FrameBorderSelected_Pred { inline bool operator()( const FrameBorder* pBorder ) const { return pBorder->IsSelected(); } }; /** Template class for all types of frame border iterators. */ template< typename Cont, typename Iter, typename Pred > class FrameBorderIterBase { public: typedef Cont container_type; typedef Iter iterator_type; typedef Pred predicate_type; typedef typename Cont::value_type value_type; typedef FrameBorderIterBase< Cont, Iter, Pred > this_type; explicit FrameBorderIterBase( container_type& rCont ); inline bool Is() const { return maIt != maEnd; } this_type& operator++(); inline value_type operator*() const { return *maIt; } private: iterator_type maIt; iterator_type maEnd; predicate_type maPred; }; /** Iterator for constant svx::FrameBorder containers, iterates over all borders. */ typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderDummy_Pred > FrameBorderCIter; /** Iterator for mutable svx::FrameBorder containers, iterates over all borders. */ typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderDummy_Pred > FrameBorderIter; /** Iterator for constant svx::FrameBorder containers, iterates over visible borders. */ typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderVisible_Pred > VisFrameBorderCIter; /** Iterator for mutable svx::FrameBorder containers, iterates over visible borders. */ typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderVisible_Pred > VisFrameBorderIter; /** Iterator for constant svx::FrameBorder containers, iterates over selected borders. */ typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderSelected_Pred > SelFrameBorderCIter; /** Iterator for mutable svx::FrameBorder containers, iterates over selected borders. */ typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderSelected_Pred > SelFrameBorderIter; // ============================================================================ } // namespace svx #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtNetwork module 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 qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qnetworkconfiguration_s60_p.h" QT_BEGIN_NAMESPACE QNetworkConfigurationPrivate::QNetworkConfigurationPrivate() : isValid(false), type(QNetworkConfiguration::Invalid), roamingSupported(false), purpose(QNetworkConfiguration::UnknownPurpose), bearer(QNetworkConfigurationPrivate::BearerUnknown), numericId(0), connectionId(0), manager(0) { } QNetworkConfigurationPrivate::~QNetworkConfigurationPrivate() { //release pointers to member configurations serviceNetworkMembers.clear(); } QString QNetworkConfigurationPrivate::bearerName() const { switch (bearer) { case QNetworkConfigurationPrivate::BearerEthernet: return QLatin1String("Ethernet"); case QNetworkConfigurationPrivate::BearerWLAN: return QLatin1String("WLAN"); case QNetworkConfigurationPrivate::Bearer2G: return QLatin1String("2G"); case QNetworkConfigurationPrivate::BearerCDMA2000: return QLatin1String("CDMA2000"); case QNetworkConfigurationPrivate::BearerWCDMA: return QLatin1String("WCDMA"); case QNetworkConfigurationPrivate::BearerHSPA: return QLatin1String("HSPA"); case QNetworkConfigurationPrivate::BearerBluetooth: return QLatin1String("Bluetooth"); case QNetworkConfigurationPrivate::BearerWiMAX: return QLatin1String("WiMAX"); default: return QLatin1String("Unknown"); } } QT_END_NAMESPACE <commit_msg>Return empty bearer name for invalid, ServiceNetwork and UserChoice.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtNetwork module 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 qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qnetworkconfiguration_s60_p.h" QT_BEGIN_NAMESPACE QNetworkConfigurationPrivate::QNetworkConfigurationPrivate() : isValid(false), type(QNetworkConfiguration::Invalid), roamingSupported(false), purpose(QNetworkConfiguration::UnknownPurpose), bearer(QNetworkConfigurationPrivate::BearerUnknown), numericId(0), connectionId(0), manager(0) { } QNetworkConfigurationPrivate::~QNetworkConfigurationPrivate() { //release pointers to member configurations serviceNetworkMembers.clear(); } QString QNetworkConfigurationPrivate::bearerName() const { switch (bearer) { case QNetworkConfigurationPrivate::BearerEthernet: return QLatin1String("Ethernet"); case QNetworkConfigurationPrivate::BearerWLAN: return QLatin1String("WLAN"); case QNetworkConfigurationPrivate::Bearer2G: return QLatin1String("2G"); case QNetworkConfigurationPrivate::BearerCDMA2000: return QLatin1String("CDMA2000"); case QNetworkConfigurationPrivate::BearerWCDMA: return QLatin1String("WCDMA"); case QNetworkConfigurationPrivate::BearerHSPA: return QLatin1String("HSPA"); case QNetworkConfigurationPrivate::BearerBluetooth: return QLatin1String("Bluetooth"); case QNetworkConfigurationPrivate::BearerWiMAX: return QLatin1String("WiMAX"); default: return QString(); } } QT_END_NAMESPACE <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://www.qtsoftware.com/contact. ** **************************************************************************/ #include "toolchain.h" #include "cesdkhandler.h" #include <QtCore/QFileInfo> #include <QtCore/QProcess> #include <QtCore/QDebug> #include <QtCore/QSettings> #include <QtCore/QDir> #include <QtCore/QTemporaryFile> #include <QtCore/QString> #include <QtCore/QCoreApplication> using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; #ifdef Q_OS_WIN64 static const char * MSVC_RegKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7"; #else static const char * MSVC_RegKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7"; #endif bool ToolChain::equals(ToolChain *a, ToolChain *b) { if (a == b) return true; if (a == 0 || b == 0) return false; if (a->type() == b->type()) return a->equals(b); return false; } ToolChain::ToolChain() { } ToolChain::~ToolChain() { } ToolChain *ToolChain::createGccToolChain(const QString &gcc) { return new GccToolChain(gcc); } ToolChain *ToolChain::createMinGWToolChain(const QString &gcc, const QString &mingwPath) { return new MinGWToolChain(gcc, mingwPath); } ToolChain *ToolChain::createMSVCToolChain(const QString &name, bool amd64 = false) { return new MSVCToolChain(name, amd64); } ToolChain *ToolChain::createWinCEToolChain(const QString &name, const QString &platform) { return new WinCEToolChain(name, platform); } QStringList ToolChain::availableMSVCVersions() { QSettings registry(MSVC_RegKey, QSettings::NativeFormat); QStringList versions = registry.allKeys(); // qDebug() << "AVAILABLE MSVC VERSIONS:" << versions << "at" << MSVC_RegKey; return versions; } QStringList ToolChain::supportedToolChains() { return QStringList() << QLatin1String("gcc") << QLatin1String("mingw") << QLatin1String("msvc") << QLatin1String("wince") << QLatin1String("winscw") << QLatin1String("gcce"); } QString ToolChain::toolChainName(ToolChainType tc) { switch (tc) { case GCC: return QCoreApplication::translate("ToolChain", "GCC"); case LinuxICC: return QCoreApplication::translate("ToolChain", "Linux ICC"); case MinGW: return QCoreApplication::translate("ToolChain", "MinGW"); case MSVC: return QCoreApplication::translate("ToolChain", "Microsoft Visual Studio"); case WINCE: return QCoreApplication::translate("ToolChain", "Windows CE"); case OTHER: return QCoreApplication::translate("ToolChain", "Other"); case INVALID: return QCoreApplication::translate("ToolChain", "<Invalid>"); case UNKNOWN: break; }; return QCoreApplication::translate("ToolChain", "<Unknown>"); } GccToolChain::GccToolChain(const QString &gcc) : m_gcc(gcc) { } ToolChain::ToolChainType GccToolChain::type() const { return ToolChain::GCC; } QByteArray GccToolChain::predefinedMacros() { if (m_predefinedMacros.isEmpty()) { QStringList arguments; arguments << QLatin1String("-xc++") << QLatin1String("-E") << QLatin1String("-dM") << QLatin1String("-"); QProcess cpp; ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment(); addToEnvironment(env); cpp.setEnvironment(env.toStringList()); cpp.start(m_gcc, arguments); cpp.closeWriteChannel(); cpp.waitForFinished(); m_predefinedMacros = cpp.readAllStandardOutput(); } return m_predefinedMacros; } QList<HeaderPath> GccToolChain::systemHeaderPaths() { if (m_systemHeaderPaths.isEmpty()) { QStringList arguments; arguments << QLatin1String("-xc++") << QLatin1String("-E") << QLatin1String("-v") << QLatin1String("-"); QProcess cpp; ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment(); addToEnvironment(env); cpp.setEnvironment(env.toStringList()); cpp.setReadChannelMode(QProcess::MergedChannels); cpp.start(m_gcc, arguments); cpp.closeWriteChannel(); cpp.waitForFinished(); QByteArray line; while (cpp.canReadLine()) { line = cpp.readLine(); if (line.startsWith("#include")) break; } if (! line.isEmpty() && line.startsWith("#include")) { HeaderPath::Kind kind = HeaderPath::UserHeaderPath; while (cpp.canReadLine()) { line = cpp.readLine(); if (line.startsWith("#include")) { kind = HeaderPath::GlobalHeaderPath; } else if (! line.isEmpty() && QChar(line.at(0)).isSpace()) { HeaderPath::Kind thisHeaderKind = kind; line = line.trimmed(); if (line.endsWith('\n')) line.chop(1); int index = line.indexOf(" (framework directory)"); if (index != -1) { line = line.left(index); thisHeaderKind = HeaderPath::FrameworkHeaderPath; } m_systemHeaderPaths.append(HeaderPath(QFile::decodeName(line), thisHeaderKind)); } else if (line.startsWith("End of search list.")) { break; } else { qWarning() << "ignore line:" << line; } } } } return m_systemHeaderPaths; } void GccToolChain::addToEnvironment(ProjectExplorer::Environment &env) { Q_UNUSED(env) } QString GccToolChain::makeCommand() const { return "make"; } bool GccToolChain::equals(ToolChain *other) const { return (m_gcc == static_cast<GccToolChain *>(other)->m_gcc); } MinGWToolChain::MinGWToolChain(const QString &gcc, const QString &mingwPath) : GccToolChain(gcc), m_mingwPath(mingwPath) { } ToolChain::ToolChainType MinGWToolChain::type() const { return ToolChain::MinGW; } bool MinGWToolChain::equals(ToolChain *other) const { MinGWToolChain *o = static_cast<MinGWToolChain *>(other); return (m_mingwPath == o->m_mingwPath && this->GccToolChain::equals(other)); } void MinGWToolChain::addToEnvironment(ProjectExplorer::Environment &env) { //qDebug()<<"MinGWToolChain::addToEnvironment"; if (m_mingwPath.isEmpty()) return; QString binDir = m_mingwPath + "/bin"; if (QFileInfo(binDir).exists()) env.prependOrSetPath(binDir); // if (QFileInfo(binDir).exists()) // qDebug()<<"Adding "<<binDir<<" to the PATH"; } QString MinGWToolChain::makeCommand() const { return "mingw32-make.exe"; } MSVCToolChain::MSVCToolChain(const QString &name, bool amd64) : m_name(name), m_valuesSet(false), m_amd64(amd64) { if (m_name.isEmpty()) { // Could be because system qt doesn't set this QSettings registry(MSVC_RegKey, QSettings::NativeFormat); QStringList keys = registry.allKeys(); if (keys.count()) m_name = keys.first(); } } ToolChain::ToolChainType MSVCToolChain::type() const { return ToolChain::MSVC; } bool MSVCToolChain::equals(ToolChain *other) const { MSVCToolChain *o = static_cast<MSVCToolChain *>(other); return (m_name == o->m_name); } QByteArray MSVCToolChain::predefinedMacros() { return "#define __WIN32__\n" "#define __WIN32\n" "#define _WIN32\n" "#define WIN32\n" "#define __WINNT__\n" "#define __WINNT\n" "#define WINNT\n" "#define _X86_\n" "#define __MSVCRT__\n"; } QList<HeaderPath> MSVCToolChain::systemHeaderPaths() { //TODO fix this code ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment(); addToEnvironment(env); QList<HeaderPath> headerPaths; foreach(const QString &path, env.value("INCLUDE").split(QLatin1Char(';'))) { headerPaths.append(HeaderPath(path, HeaderPath::GlobalHeaderPath)); } return headerPaths; } void MSVCToolChain::addToEnvironment(ProjectExplorer::Environment &env) { if (!m_valuesSet || env != m_lastEnvironment) { m_lastEnvironment = env; QSettings registry(MSVC_RegKey, QSettings::NativeFormat); if (m_name.isEmpty()) return; QString path = registry.value(m_name).toString(); QString desc; QString varsbat; if (m_amd64) varsbat = path + "bin\\amd64\\vcvarsamd64.bat"; else varsbat = path + "bin\\vcvars32.bat"; // qDebug() << varsbat; if (QFileInfo(varsbat).exists()) { QTemporaryFile tf(QDir::tempPath() + "\\XXXXXX.bat"); if (!tf.open()) return; QString filename = tf.fileName(); tf.write("call \"" + varsbat.toLocal8Bit()+"\"\r\n"); tf.write(("set > \"" + QDir::tempPath() + "\\qtcreator-msvc-environment.txt\"\r\n").toLocal8Bit()); tf.flush(); tf.waitForBytesWritten(30000); QProcess run; run.setEnvironment(env.toStringList()); QString cmdPath = env.searchInPath("cmd"); run.start(cmdPath, QStringList()<<"/c"<<filename); run.waitForFinished(); tf.close(); QFile vars(QDir::tempPath() + "\\qtcreator-msvc-environment.txt"); if (vars.exists() && vars.open(QIODevice::ReadOnly)) { while (!vars.atEnd()) { QByteArray line = vars.readLine(); QString line2 = QString::fromLocal8Bit(line); line2 = line2.trimmed(); QRegExp regexp("(\\w*)=(.*)"); if (regexp.exactMatch(line2)) { QString variable = regexp.cap(1); QString value = regexp.cap(2); m_values.append(QPair<QString, QString>(variable, value)); } } vars.close(); vars.remove(); } } m_valuesSet = true; } QList< QPair<QString, QString> >::const_iterator it, end; end = m_values.constEnd(); for (it = m_values.constBegin(); it != end; ++it) { env.set((*it).first, (*it).second); } } QString MSVCToolChain::makeCommand() const { if (ProjectExplorerPlugin::instance()->projectExplorerSettings().useJom) { // We want jom! Try to find it. QString jom = QCoreApplication::applicationDirPath() + QLatin1String("/jom.exe"); if (QFileInfo(jom).exists()) return jom; else return "jom.exe"; } return "nmake.exe"; } WinCEToolChain::WinCEToolChain(const QString &name, const QString &platform) : MSVCToolChain(name), m_platform(platform) { } ToolChain::ToolChainType WinCEToolChain::type() const { return ToolChain::WINCE; } bool WinCEToolChain::equals(ToolChain *other) const { WinCEToolChain *o = static_cast<WinCEToolChain *>(other); return (m_platform == o->m_platform && this->MSVCToolChain::equals(other)); } QByteArray WinCEToolChain::predefinedMacros() { //TODO return MSVCToolChain::predefinedMacros(); } QList<HeaderPath> WinCEToolChain::systemHeaderPaths() { //TODO fix this code ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment(); addToEnvironment(env); QList<HeaderPath> headerPaths; const QStringList includes = env.value("INCLUDE").split(QLatin1Char(';')); foreach (const QString &path, includes) { const HeaderPath headerPath(path, HeaderPath::GlobalHeaderPath); headerPaths.append(headerPath); } return headerPaths; } void WinCEToolChain::addToEnvironment(ProjectExplorer::Environment &env) { MSVCToolChain::addToEnvironment(env); QSettings registry(MSVC_RegKey, QSettings::NativeFormat); QString path = registry.value(m_name).toString(); // Find MSVC path path += "/"; // qDebug()<<"MSVC path"<<msvcPath; // qDebug()<<"looking for platform name in"<< path() + "/mkspecs/" + mkspec() +"/qmake.conf"; // Find Platform name // qDebug()<<"Platform Name"<<platformName; CeSdkHandler cesdkhandler; cesdkhandler.parse(path); cesdkhandler.find(m_platform).addToEnvironment(env); //qDebug()<<"WinCE Final Environment:"; //qDebug()<<env.toStringList(); } <commit_msg>Improve wording of tool chains.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://www.qtsoftware.com/contact. ** **************************************************************************/ #include "toolchain.h" #include "cesdkhandler.h" #include <QtCore/QFileInfo> #include <QtCore/QProcess> #include <QtCore/QDebug> #include <QtCore/QSettings> #include <QtCore/QDir> #include <QtCore/QTemporaryFile> #include <QtCore/QString> #include <QtCore/QCoreApplication> using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; #ifdef Q_OS_WIN64 static const char * MSVC_RegKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7"; #else static const char * MSVC_RegKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7"; #endif bool ToolChain::equals(ToolChain *a, ToolChain *b) { if (a == b) return true; if (a == 0 || b == 0) return false; if (a->type() == b->type()) return a->equals(b); return false; } ToolChain::ToolChain() { } ToolChain::~ToolChain() { } ToolChain *ToolChain::createGccToolChain(const QString &gcc) { return new GccToolChain(gcc); } ToolChain *ToolChain::createMinGWToolChain(const QString &gcc, const QString &mingwPath) { return new MinGWToolChain(gcc, mingwPath); } ToolChain *ToolChain::createMSVCToolChain(const QString &name, bool amd64 = false) { return new MSVCToolChain(name, amd64); } ToolChain *ToolChain::createWinCEToolChain(const QString &name, const QString &platform) { return new WinCEToolChain(name, platform); } QStringList ToolChain::availableMSVCVersions() { QSettings registry(MSVC_RegKey, QSettings::NativeFormat); QStringList versions = registry.allKeys(); // qDebug() << "AVAILABLE MSVC VERSIONS:" << versions << "at" << MSVC_RegKey; return versions; } QStringList ToolChain::supportedToolChains() { return QStringList() << QLatin1String("gcc") << QLatin1String("mingw") << QLatin1String("msvc") << QLatin1String("wince") << QLatin1String("winscw") << QLatin1String("gcce"); } QString ToolChain::toolChainName(ToolChainType tc) { switch (tc) { case GCC: return QCoreApplication::translate("ToolChain", "GCC"); case LinuxICC: return QCoreApplication::translate("ToolChain", "Intel C++ Compiler (Linux)"); case MinGW: return QCoreApplication::translate("ToolChain", "MinGW"); case MSVC: return QCoreApplication::translate("ToolChain", "Microsoft Visual C++"); case WINCE: return QCoreApplication::translate("ToolChain", "Windows CE"); case OTHER: return QCoreApplication::translate("ToolChain", "Other"); case INVALID: return QCoreApplication::translate("ToolChain", "<Invalid>"); case UNKNOWN: break; }; return QCoreApplication::translate("ToolChain", "<Unknown>"); } GccToolChain::GccToolChain(const QString &gcc) : m_gcc(gcc) { } ToolChain::ToolChainType GccToolChain::type() const { return ToolChain::GCC; } QByteArray GccToolChain::predefinedMacros() { if (m_predefinedMacros.isEmpty()) { QStringList arguments; arguments << QLatin1String("-xc++") << QLatin1String("-E") << QLatin1String("-dM") << QLatin1String("-"); QProcess cpp; ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment(); addToEnvironment(env); cpp.setEnvironment(env.toStringList()); cpp.start(m_gcc, arguments); cpp.closeWriteChannel(); cpp.waitForFinished(); m_predefinedMacros = cpp.readAllStandardOutput(); } return m_predefinedMacros; } QList<HeaderPath> GccToolChain::systemHeaderPaths() { if (m_systemHeaderPaths.isEmpty()) { QStringList arguments; arguments << QLatin1String("-xc++") << QLatin1String("-E") << QLatin1String("-v") << QLatin1String("-"); QProcess cpp; ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment(); addToEnvironment(env); cpp.setEnvironment(env.toStringList()); cpp.setReadChannelMode(QProcess::MergedChannels); cpp.start(m_gcc, arguments); cpp.closeWriteChannel(); cpp.waitForFinished(); QByteArray line; while (cpp.canReadLine()) { line = cpp.readLine(); if (line.startsWith("#include")) break; } if (! line.isEmpty() && line.startsWith("#include")) { HeaderPath::Kind kind = HeaderPath::UserHeaderPath; while (cpp.canReadLine()) { line = cpp.readLine(); if (line.startsWith("#include")) { kind = HeaderPath::GlobalHeaderPath; } else if (! line.isEmpty() && QChar(line.at(0)).isSpace()) { HeaderPath::Kind thisHeaderKind = kind; line = line.trimmed(); if (line.endsWith('\n')) line.chop(1); int index = line.indexOf(" (framework directory)"); if (index != -1) { line = line.left(index); thisHeaderKind = HeaderPath::FrameworkHeaderPath; } m_systemHeaderPaths.append(HeaderPath(QFile::decodeName(line), thisHeaderKind)); } else if (line.startsWith("End of search list.")) { break; } else { qWarning() << "ignore line:" << line; } } } } return m_systemHeaderPaths; } void GccToolChain::addToEnvironment(ProjectExplorer::Environment &env) { Q_UNUSED(env) } QString GccToolChain::makeCommand() const { return "make"; } bool GccToolChain::equals(ToolChain *other) const { return (m_gcc == static_cast<GccToolChain *>(other)->m_gcc); } MinGWToolChain::MinGWToolChain(const QString &gcc, const QString &mingwPath) : GccToolChain(gcc), m_mingwPath(mingwPath) { } ToolChain::ToolChainType MinGWToolChain::type() const { return ToolChain::MinGW; } bool MinGWToolChain::equals(ToolChain *other) const { MinGWToolChain *o = static_cast<MinGWToolChain *>(other); return (m_mingwPath == o->m_mingwPath && this->GccToolChain::equals(other)); } void MinGWToolChain::addToEnvironment(ProjectExplorer::Environment &env) { //qDebug()<<"MinGWToolChain::addToEnvironment"; if (m_mingwPath.isEmpty()) return; QString binDir = m_mingwPath + "/bin"; if (QFileInfo(binDir).exists()) env.prependOrSetPath(binDir); // if (QFileInfo(binDir).exists()) // qDebug()<<"Adding "<<binDir<<" to the PATH"; } QString MinGWToolChain::makeCommand() const { return "mingw32-make.exe"; } MSVCToolChain::MSVCToolChain(const QString &name, bool amd64) : m_name(name), m_valuesSet(false), m_amd64(amd64) { if (m_name.isEmpty()) { // Could be because system qt doesn't set this QSettings registry(MSVC_RegKey, QSettings::NativeFormat); QStringList keys = registry.allKeys(); if (keys.count()) m_name = keys.first(); } } ToolChain::ToolChainType MSVCToolChain::type() const { return ToolChain::MSVC; } bool MSVCToolChain::equals(ToolChain *other) const { MSVCToolChain *o = static_cast<MSVCToolChain *>(other); return (m_name == o->m_name); } QByteArray MSVCToolChain::predefinedMacros() { return "#define __WIN32__\n" "#define __WIN32\n" "#define _WIN32\n" "#define WIN32\n" "#define __WINNT__\n" "#define __WINNT\n" "#define WINNT\n" "#define _X86_\n" "#define __MSVCRT__\n"; } QList<HeaderPath> MSVCToolChain::systemHeaderPaths() { //TODO fix this code ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment(); addToEnvironment(env); QList<HeaderPath> headerPaths; foreach(const QString &path, env.value("INCLUDE").split(QLatin1Char(';'))) { headerPaths.append(HeaderPath(path, HeaderPath::GlobalHeaderPath)); } return headerPaths; } void MSVCToolChain::addToEnvironment(ProjectExplorer::Environment &env) { if (!m_valuesSet || env != m_lastEnvironment) { m_lastEnvironment = env; QSettings registry(MSVC_RegKey, QSettings::NativeFormat); if (m_name.isEmpty()) return; QString path = registry.value(m_name).toString(); QString desc; QString varsbat; if (m_amd64) varsbat = path + "bin\\amd64\\vcvarsamd64.bat"; else varsbat = path + "bin\\vcvars32.bat"; // qDebug() << varsbat; if (QFileInfo(varsbat).exists()) { QTemporaryFile tf(QDir::tempPath() + "\\XXXXXX.bat"); if (!tf.open()) return; QString filename = tf.fileName(); tf.write("call \"" + varsbat.toLocal8Bit()+"\"\r\n"); tf.write(("set > \"" + QDir::tempPath() + "\\qtcreator-msvc-environment.txt\"\r\n").toLocal8Bit()); tf.flush(); tf.waitForBytesWritten(30000); QProcess run; run.setEnvironment(env.toStringList()); QString cmdPath = env.searchInPath("cmd"); run.start(cmdPath, QStringList()<<"/c"<<filename); run.waitForFinished(); tf.close(); QFile vars(QDir::tempPath() + "\\qtcreator-msvc-environment.txt"); if (vars.exists() && vars.open(QIODevice::ReadOnly)) { while (!vars.atEnd()) { QByteArray line = vars.readLine(); QString line2 = QString::fromLocal8Bit(line); line2 = line2.trimmed(); QRegExp regexp("(\\w*)=(.*)"); if (regexp.exactMatch(line2)) { QString variable = regexp.cap(1); QString value = regexp.cap(2); m_values.append(QPair<QString, QString>(variable, value)); } } vars.close(); vars.remove(); } } m_valuesSet = true; } QList< QPair<QString, QString> >::const_iterator it, end; end = m_values.constEnd(); for (it = m_values.constBegin(); it != end; ++it) { env.set((*it).first, (*it).second); } } QString MSVCToolChain::makeCommand() const { if (ProjectExplorerPlugin::instance()->projectExplorerSettings().useJom) { // We want jom! Try to find it. QString jom = QCoreApplication::applicationDirPath() + QLatin1String("/jom.exe"); if (QFileInfo(jom).exists()) return jom; else return "jom.exe"; } return "nmake.exe"; } WinCEToolChain::WinCEToolChain(const QString &name, const QString &platform) : MSVCToolChain(name), m_platform(platform) { } ToolChain::ToolChainType WinCEToolChain::type() const { return ToolChain::WINCE; } bool WinCEToolChain::equals(ToolChain *other) const { WinCEToolChain *o = static_cast<WinCEToolChain *>(other); return (m_platform == o->m_platform && this->MSVCToolChain::equals(other)); } QByteArray WinCEToolChain::predefinedMacros() { //TODO return MSVCToolChain::predefinedMacros(); } QList<HeaderPath> WinCEToolChain::systemHeaderPaths() { //TODO fix this code ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment(); addToEnvironment(env); QList<HeaderPath> headerPaths; const QStringList includes = env.value("INCLUDE").split(QLatin1Char(';')); foreach (const QString &path, includes) { const HeaderPath headerPath(path, HeaderPath::GlobalHeaderPath); headerPaths.append(headerPath); } return headerPaths; } void WinCEToolChain::addToEnvironment(ProjectExplorer::Environment &env) { MSVCToolChain::addToEnvironment(env); QSettings registry(MSVC_RegKey, QSettings::NativeFormat); QString path = registry.value(m_name).toString(); // Find MSVC path path += "/"; // qDebug()<<"MSVC path"<<msvcPath; // qDebug()<<"looking for platform name in"<< path() + "/mkspecs/" + mkspec() +"/qmake.conf"; // Find Platform name // qDebug()<<"Platform Name"<<platformName; CeSdkHandler cesdkhandler; cesdkhandler.parse(path); cesdkhandler.find(m_platform).addToEnvironment(env); //qDebug()<<"WinCE Final Environment:"; //qDebug()<<env.toStringList(); } <|endoftext|>
<commit_before>//============================================================================== // Property editor widget //============================================================================== #include "propertyeditorwidget.h" //============================================================================== #include <QKeyEvent> #include <QStandardItem> //============================================================================== namespace OpenCOR { namespace Core { //============================================================================== PropertyEditorWidget::PropertyEditorWidget(QWidget *pParent) : TreeViewWidget(pParent) { // Customise ourself setSelectionMode(QAbstractItemView::SingleSelection); } //============================================================================== QStandardItem * PropertyEditorWidget::newNonEditableItem() { // Create and return a non-editable item QStandardItem *res = new QStandardItem(); res->setFlags(res->flags() & ~Qt::ItemIsEditable); return res; } //============================================================================== QStandardItem * PropertyEditorWidget::newEditableItem() { // Create and return an editable item return new QStandardItem(); } //============================================================================== void PropertyEditorWidget::keyPressEvent(QKeyEvent *pEvent) { // Check for some key combinations and ignore them, if needed if ( (pEvent->modifiers() & Qt::ControlModifier) && (pEvent->key() == Qt::Key_A)) // The user wants to select everything which we don't want to allow, // so... pEvent->ignore(); else // Not a key combination which we don't want, so... TreeViewWidget::keyPressEvent(pEvent); } //============================================================================== } // namespace Core } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some work on PropertyEditorWidget.<commit_after>//============================================================================== // Property editor widget //============================================================================== #include "propertyeditorwidget.h" //============================================================================== #include <QKeyEvent> #include <QStandardItem> //============================================================================== namespace OpenCOR { namespace Core { //============================================================================== PropertyEditorWidget::PropertyEditorWidget(QWidget *pParent) : TreeViewWidget(pParent) { // Customise ourself setFrameShape(QFrame::NoFrame); setSelectionMode(QAbstractItemView::SingleSelection); } //============================================================================== QStandardItem * PropertyEditorWidget::newNonEditableItem() { // Create and return a non-editable item QStandardItem *res = new QStandardItem(); res->setFlags(res->flags() & ~Qt::ItemIsEditable); return res; } //============================================================================== QStandardItem * PropertyEditorWidget::newEditableItem() { // Create and return an editable item return new QStandardItem(); } //============================================================================== void PropertyEditorWidget::keyPressEvent(QKeyEvent *pEvent) { // Check for some key combinations and ignore them, if needed if ( (pEvent->modifiers() & Qt::ControlModifier) && (pEvent->key() == Qt::Key_A)) // The user wants to select everything which we don't want to allow, // so... pEvent->ignore(); else // Not a key combination which we don't want, so... TreeViewWidget::keyPressEvent(pEvent); } //============================================================================== } // namespace Core } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>// Sleep #include <chrono> #include <thread> int main() { std::chrono::milliseconds sleepDuration(20); std::this_thread::sleep_for(sleepDuration); } // Block the execution of a thread for a given amount of time. // // On [8], we create a [`std::chrono::milliseconds`](cpp/chrono/duration) // object representing the number of milliseconds to sleep (other // duration units may also be used). On [10], the call to // [`std::this_thread::sleep_for`](cpp/thread/sleep_for) will block // the execution of the current thread for at least the given // duration. <commit_msg>Use duration literal in sleep sample<commit_after>// Sleep // C++11, C++14 #include <chrono> #include <thread> using namespace std::literals::chrono_literals; int main() { std::chrono::milliseconds sleepDuration(20); std::this_thread::sleep_for(sleepDuration); std::this_thread::sleep_for(5s); } // Block the execution of a thread for a given amount of time. // // On [10], we create a [`std::chrono::milliseconds`](cpp/chrono/duration) // object representing the number of milliseconds to sleep (other // duration units may also be used). On [11], the call to // [`std::this_thread::sleep_for`](cpp/thread/sleep_for) will block // the execution of the current thread for at least the given // duration. // // On [13], we demonstrate the use of C++14's [duration literal // suffixes](http://en.cppreference.com/w/cpp/chrono/duration#Literals) // by representing a duration with the seconds suffix, `s`. The // `using` directive on [7] is required in order to use these suffixes. <|endoftext|>
<commit_before><commit_msg>use C++11 iteration<commit_after><|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmljsquickfix.h" #include "qmljseditor.h" #include "qmljs/parser/qmljsast_p.h" #include <QtGui/QApplication> #include <QtCore/QDebug> using namespace QmlJSEditor::Internal; class QmlJSQuickFixState: public TextEditor::QuickFixState { public: SemanticInfo semanticInfo; }; namespace { class SplitInitializerOp: public QmlJSQuickFixOperation { public: SplitInitializerOp(TextEditor::BaseTextEditor *editor) : QmlJSQuickFixOperation(editor), _objectInitializer(0) {} virtual QString description() const { return QApplication::translate("QmlJSEditor::QuickFix", "Split initializer"); } virtual Range topLevelRange() const { Q_ASSERT(_objectInitializer); return range(position(_objectInitializer->lbraceToken), position(_objectInitializer->rbraceToken)); } virtual void createChangeSet() { Q_ASSERT(_objectInitializer != 0); for (QmlJS::AST::UiObjectMemberList *it = _objectInitializer->members; it; it = it->next) { if (QmlJS::AST::UiObjectMember *member = it->member) { const QmlJS::AST::SourceLocation loc = member->firstSourceLocation(); // insert a newline at the beginning of this binding insert(position(loc), QLatin1String("\n")); } } // insert a newline before the closing brace insert(position(_objectInitializer->rbraceToken), QLatin1String("\n")); } virtual int check() { _objectInitializer = 0; const int pos = textCursor().position(); if (QmlJS::AST::Node *member = semanticInfo().declaringMember(pos)) { if (QmlJS::AST::UiObjectBinding *b = QmlJS::AST::cast<QmlJS::AST::UiObjectBinding *>(member)) { if (b->initializer->lbraceToken.startLine == b->initializer->rbraceToken.startLine) { _objectInitializer = b->initializer; return 0; // very high priority } } else if (QmlJS::AST::UiObjectDefinition *b = QmlJS::AST::cast<QmlJS::AST::UiObjectDefinition *>(member)) { if (b->initializer->lbraceToken.startLine == b->initializer->rbraceToken.startLine) { _objectInitializer = b->initializer; return 0; // very high priority } } return false; } return -1; } private: QmlJS::AST::UiObjectInitializer *_objectInitializer; }; } // end of anonymous namespace QmlJSQuickFixOperation::QmlJSQuickFixOperation(TextEditor::BaseTextEditor *editor) : TextEditor::QuickFixOperation(editor) { } QmlJSQuickFixOperation::~QmlJSQuickFixOperation() { } QmlJS::Document::Ptr QmlJSQuickFixOperation::document() const { return _semanticInfo.document; } const QmlJS::Snapshot &QmlJSQuickFixOperation::snapshot() const { return _semanticInfo.snapshot; } const SemanticInfo &QmlJSQuickFixOperation::semanticInfo() const { return _semanticInfo; } int QmlJSQuickFixOperation::match(TextEditor::QuickFixState *state) { QmlJSQuickFixState *s = static_cast<QmlJSQuickFixState *>(state); _semanticInfo = s->semanticInfo; return check(); } unsigned QmlJSQuickFixOperation::position(const QmlJS::AST::SourceLocation &loc) const { return position(loc.startLine, loc.startColumn); } void QmlJSQuickFixOperation::move(const QmlJS::AST::SourceLocation &loc, int to) { move(position(loc.startColumn, loc.startColumn), to); } void QmlJSQuickFixOperation::replace(const QmlJS::AST::SourceLocation &loc, const QString &replacement) { replace(position(loc.startLine, loc.startColumn), replacement); } void QmlJSQuickFixOperation::remove(const QmlJS::AST::SourceLocation &loc) { remove(position(loc.startLine, loc.startColumn)); } void QmlJSQuickFixOperation::copy(const QmlJS::AST::SourceLocation &loc, int to) { copy(position(loc.startLine, loc.startColumn), to); } QmlJSQuickFixCollector::QmlJSQuickFixCollector() { } QmlJSQuickFixCollector::~QmlJSQuickFixCollector() { } bool QmlJSQuickFixCollector::supportsEditor(TextEditor::ITextEditable *editable) { if (qobject_cast<QmlJSTextEditor *>(editable->widget()) != 0) return true; return false; } TextEditor::QuickFixState *QmlJSQuickFixCollector::initializeCompletion(TextEditor::ITextEditable *editable) { if (QmlJSTextEditor *editor = qobject_cast<QmlJSTextEditor *>(editable->widget())) { const SemanticInfo info = editor->semanticInfo(); if (editor->isOutdated()) { // outdated qWarning() << "TODO: outdated semantic info, force a reparse."; return 0; } QmlJSQuickFixState *state = new QmlJSQuickFixState; state->semanticInfo = info; return state; } return 0; } QList<TextEditor::QuickFixOperation::Ptr> QmlJSQuickFixCollector::quickFixOperations(TextEditor::BaseTextEditor *editor) const { QList<TextEditor::QuickFixOperation::Ptr> quickFixOperations; quickFixOperations.append(TextEditor::QuickFixOperation::Ptr(new SplitInitializerOp(editor))); return quickFixOperations; } <commit_msg>Fixed a typo in the check() method.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmljsquickfix.h" #include "qmljseditor.h" #include "qmljs/parser/qmljsast_p.h" #include <QtGui/QApplication> #include <QtCore/QDebug> using namespace QmlJSEditor::Internal; class QmlJSQuickFixState: public TextEditor::QuickFixState { public: SemanticInfo semanticInfo; }; namespace { class SplitInitializerOp: public QmlJSQuickFixOperation { public: SplitInitializerOp(TextEditor::BaseTextEditor *editor) : QmlJSQuickFixOperation(editor), _objectInitializer(0) {} virtual QString description() const { return QApplication::translate("QmlJSEditor::QuickFix", "Split initializer"); } virtual Range topLevelRange() const { Q_ASSERT(_objectInitializer); return range(position(_objectInitializer->lbraceToken), position(_objectInitializer->rbraceToken)); } virtual void createChangeSet() { Q_ASSERT(_objectInitializer != 0); for (QmlJS::AST::UiObjectMemberList *it = _objectInitializer->members; it; it = it->next) { if (QmlJS::AST::UiObjectMember *member = it->member) { const QmlJS::AST::SourceLocation loc = member->firstSourceLocation(); // insert a newline at the beginning of this binding insert(position(loc), QLatin1String("\n")); } } // insert a newline before the closing brace insert(position(_objectInitializer->rbraceToken), QLatin1String("\n")); } virtual int check() { _objectInitializer = 0; const int pos = textCursor().position(); if (QmlJS::AST::Node *member = semanticInfo().declaringMember(pos)) { if (QmlJS::AST::UiObjectBinding *b = QmlJS::AST::cast<QmlJS::AST::UiObjectBinding *>(member)) { if (b->initializer->lbraceToken.startLine == b->initializer->rbraceToken.startLine) _objectInitializer = b->initializer; } else if (QmlJS::AST::UiObjectDefinition *b = QmlJS::AST::cast<QmlJS::AST::UiObjectDefinition *>(member)) { if (b->initializer->lbraceToken.startLine == b->initializer->rbraceToken.startLine) _objectInitializer = b->initializer; } } if (! _objectInitializer) return -1; return 0; // very high priority } private: QmlJS::AST::UiObjectInitializer *_objectInitializer; }; } // end of anonymous namespace QmlJSQuickFixOperation::QmlJSQuickFixOperation(TextEditor::BaseTextEditor *editor) : TextEditor::QuickFixOperation(editor) { } QmlJSQuickFixOperation::~QmlJSQuickFixOperation() { } QmlJS::Document::Ptr QmlJSQuickFixOperation::document() const { return _semanticInfo.document; } const QmlJS::Snapshot &QmlJSQuickFixOperation::snapshot() const { return _semanticInfo.snapshot; } const SemanticInfo &QmlJSQuickFixOperation::semanticInfo() const { return _semanticInfo; } int QmlJSQuickFixOperation::match(TextEditor::QuickFixState *state) { QmlJSQuickFixState *s = static_cast<QmlJSQuickFixState *>(state); _semanticInfo = s->semanticInfo; return check(); } unsigned QmlJSQuickFixOperation::position(const QmlJS::AST::SourceLocation &loc) const { return position(loc.startLine, loc.startColumn); } void QmlJSQuickFixOperation::move(const QmlJS::AST::SourceLocation &loc, int to) { move(position(loc.startColumn, loc.startColumn), to); } void QmlJSQuickFixOperation::replace(const QmlJS::AST::SourceLocation &loc, const QString &replacement) { replace(position(loc.startLine, loc.startColumn), replacement); } void QmlJSQuickFixOperation::remove(const QmlJS::AST::SourceLocation &loc) { remove(position(loc.startLine, loc.startColumn)); } void QmlJSQuickFixOperation::copy(const QmlJS::AST::SourceLocation &loc, int to) { copy(position(loc.startLine, loc.startColumn), to); } QmlJSQuickFixCollector::QmlJSQuickFixCollector() { } QmlJSQuickFixCollector::~QmlJSQuickFixCollector() { } bool QmlJSQuickFixCollector::supportsEditor(TextEditor::ITextEditable *editable) { if (qobject_cast<QmlJSTextEditor *>(editable->widget()) != 0) return true; return false; } TextEditor::QuickFixState *QmlJSQuickFixCollector::initializeCompletion(TextEditor::ITextEditable *editable) { if (QmlJSTextEditor *editor = qobject_cast<QmlJSTextEditor *>(editable->widget())) { const SemanticInfo info = editor->semanticInfo(); if (editor->isOutdated()) { // outdated qWarning() << "TODO: outdated semantic info, force a reparse."; return 0; } QmlJSQuickFixState *state = new QmlJSQuickFixState; state->semanticInfo = info; return state; } return 0; } QList<TextEditor::QuickFixOperation::Ptr> QmlJSQuickFixCollector::quickFixOperations(TextEditor::BaseTextEditor *editor) const { QList<TextEditor::QuickFixOperation::Ptr> quickFixOperations; quickFixOperations.append(TextEditor::QuickFixOperation::Ptr(new SplitInitializerOp(editor))); return quickFixOperations; } <|endoftext|>
<commit_before><commit_msg>fdo#53487 SwUndoInsert: take care of fieldmarks when deleting field chars<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: inpdlg.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2007-09-27 11:49:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #define _INPDLG_CXX #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _UNOTOOLS_CHARCLASS_HXX #include <unotools/charclass.hxx> #endif #ifndef _UNO_LINGU_HXX #include <svx/unolingu.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _FLDBAS_HXX #include <fldbas.hxx> #endif #ifndef _EXPFLD_HXX #include <expfld.hxx> #endif #ifndef _USRFLD_HXX #include <usrfld.hxx> #endif #ifndef _INPDLG_HXX #include <inpdlg.hxx> #endif #ifndef _FLDMGR_HXX #include <fldmgr.hxx> #endif #ifndef _FLDUI_HRC #include <fldui.hrc> #endif #ifndef _INPDLG_HRC #include <inpdlg.hrc> #endif /*-------------------------------------------------------------------- Beschreibung: Feldeinfuegen bearbeiten --------------------------------------------------------------------*/ SwFldInputDlg::SwFldInputDlg( Window *pParent, SwWrtShell &rS, SwField* pField, BOOL bNextButton ) : SvxStandardDialog(pParent, SW_RES(DLG_FLD_INPUT)), rSh( rS ), pInpFld(0), pSetFld(0), pUsrType(0), aLabelED (this, SW_RES(ED_LABEL )), aEditED (this, SW_RES(ED_EDIT )), aEditFL (this, SW_RES(FL_EDIT )), aOKBT (this, SW_RES(BT_OK )), aCancelBT (this, SW_RES(BT_CANCEL )), aNextBT (this, SW_RES(PB_NEXT )), aHelpBT (this, SW_RES(PB_HELP )) { // Font fuers Edit umschalten Font aFont(aEditED.GetFont()); aFont.SetWeight(WEIGHT_LIGHT); aEditED.SetFont(aFont); if( bNextButton ) { aNextBT.Show(); aNextBT.SetClickHdl(LINK(this, SwFldInputDlg, NextHdl)); } else { long nDiff = aCancelBT.GetPosPixel().Y() - aOKBT.GetPosPixel().Y(); Point aPos = aHelpBT.GetPosPixel(); aPos.Y() -= nDiff; aHelpBT.SetPosPixel(aPos); } // Auswertung hier String aStr; if( RES_INPUTFLD == pField->GetTyp()->Which() ) { // Es ist eine Eingabefeld // pInpFld = (SwInputField*)pField; aLabelED.SetText( pInpFld->GetPar2() ); USHORT nSubType = pInpFld->GetSubType(); switch(nSubType & 0xff) { case INP_TXT: aStr = pInpFld->GetPar1(); break; case INP_USR: // Benutzerfeld if( 0 != ( pUsrType = (SwUserFieldType*)rSh.GetFldType( RES_USERFLD, pInpFld->GetPar1() ) ) ) aStr = pUsrType->GetContent(); break; } } else { // es ist eine SetExpression pSetFld = (SwSetExpField*)pField; String sFormula(pSetFld->GetFormula()); //values are formatted - formulas are not CharClass aCC( SvxCreateLocale( pSetFld->GetLanguage() )); if( aCC.isNumeric( sFormula )) aStr = pSetFld->Expand(); else aStr = sFormula; aLabelED.SetText( pSetFld->GetPromptText() ); } // JP 31.3.00: Inputfields in readonly regions must be allowed to // input any content. - 74639 BOOL bEnable = !rSh.IsCrsrReadonly(); /*!rSh.IsReadOnlyAvailable() || !rSh.HasReadonlySel()*/; aOKBT.Enable( bEnable ); aEditED.SetReadOnly( !bEnable ); if( aStr.Len() ) aEditED.SetText( aStr.ConvertLineEnd() ); FreeResource(); } SwFldInputDlg::~SwFldInputDlg() { } void SwFldInputDlg::StateChanged( StateChangedType nType ) { if ( nType == STATE_CHANGE_INITSHOW ) aEditED.GrabFocus(); SvxStandardDialog::StateChanged( nType ); } /*-------------------------------------------------------------------- Beschreibung: Schliessen --------------------------------------------------------------------*/ void SwFldInputDlg::Apply() { String aTmp( aEditED.GetText() ); aTmp.EraseAllChars( '\r' ); rSh.StartAllAction(); BOOL bModified = FALSE; if(pInpFld) { if(pUsrType) { if( aTmp != pUsrType->GetContent() ) { pUsrType->SetContent(aTmp); pUsrType->UpdateFlds(); bModified = TRUE; } } else if( aTmp != pInpFld->GetPar1() ) { pInpFld->SetPar1(aTmp); rSh.SwEditShell::UpdateFlds(*pInpFld); bModified = TRUE; } } else if( aTmp != pSetFld->GetPar2() ) { pSetFld->SetPar2(aTmp); rSh.SwEditShell::UpdateFlds(*pSetFld); bModified = TRUE; } if( bModified ) rSh.SetUndoNoResetModified(); rSh.EndAllAction(); } IMPL_LINK(SwFldInputDlg, NextHdl, PushButton*, EMPTYARG) { EndDialog(RET_OK); return 0; } <commit_msg>INTEGRATION: CWS changefileheader (1.10.242); FILE MERGED 2008/04/01 15:59:05 thb 1.10.242.3: #i85898# Stripping all external header guards 2008/04/01 12:55:19 thb 1.10.242.2: #i85898# Stripping all external header guards 2008/03/31 16:58:03 rt 1.10.242.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: inpdlg.cxx,v $ * $Revision: 1.11 $ * * 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_sw.hxx" #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #define _INPDLG_CXX #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #include <unotools/charclass.hxx> #include <svx/unolingu.hxx> #include <wrtsh.hxx> #include <fldbas.hxx> #include <expfld.hxx> #include <usrfld.hxx> #include <inpdlg.hxx> #include <fldmgr.hxx> #ifndef _FLDUI_HRC #include <fldui.hrc> #endif #ifndef _INPDLG_HRC #include <inpdlg.hrc> #endif /*-------------------------------------------------------------------- Beschreibung: Feldeinfuegen bearbeiten --------------------------------------------------------------------*/ SwFldInputDlg::SwFldInputDlg( Window *pParent, SwWrtShell &rS, SwField* pField, BOOL bNextButton ) : SvxStandardDialog(pParent, SW_RES(DLG_FLD_INPUT)), rSh( rS ), pInpFld(0), pSetFld(0), pUsrType(0), aLabelED (this, SW_RES(ED_LABEL )), aEditED (this, SW_RES(ED_EDIT )), aEditFL (this, SW_RES(FL_EDIT )), aOKBT (this, SW_RES(BT_OK )), aCancelBT (this, SW_RES(BT_CANCEL )), aNextBT (this, SW_RES(PB_NEXT )), aHelpBT (this, SW_RES(PB_HELP )) { // Font fuers Edit umschalten Font aFont(aEditED.GetFont()); aFont.SetWeight(WEIGHT_LIGHT); aEditED.SetFont(aFont); if( bNextButton ) { aNextBT.Show(); aNextBT.SetClickHdl(LINK(this, SwFldInputDlg, NextHdl)); } else { long nDiff = aCancelBT.GetPosPixel().Y() - aOKBT.GetPosPixel().Y(); Point aPos = aHelpBT.GetPosPixel(); aPos.Y() -= nDiff; aHelpBT.SetPosPixel(aPos); } // Auswertung hier String aStr; if( RES_INPUTFLD == pField->GetTyp()->Which() ) { // Es ist eine Eingabefeld // pInpFld = (SwInputField*)pField; aLabelED.SetText( pInpFld->GetPar2() ); USHORT nSubType = pInpFld->GetSubType(); switch(nSubType & 0xff) { case INP_TXT: aStr = pInpFld->GetPar1(); break; case INP_USR: // Benutzerfeld if( 0 != ( pUsrType = (SwUserFieldType*)rSh.GetFldType( RES_USERFLD, pInpFld->GetPar1() ) ) ) aStr = pUsrType->GetContent(); break; } } else { // es ist eine SetExpression pSetFld = (SwSetExpField*)pField; String sFormula(pSetFld->GetFormula()); //values are formatted - formulas are not CharClass aCC( SvxCreateLocale( pSetFld->GetLanguage() )); if( aCC.isNumeric( sFormula )) aStr = pSetFld->Expand(); else aStr = sFormula; aLabelED.SetText( pSetFld->GetPromptText() ); } // JP 31.3.00: Inputfields in readonly regions must be allowed to // input any content. - 74639 BOOL bEnable = !rSh.IsCrsrReadonly(); /*!rSh.IsReadOnlyAvailable() || !rSh.HasReadonlySel()*/; aOKBT.Enable( bEnable ); aEditED.SetReadOnly( !bEnable ); if( aStr.Len() ) aEditED.SetText( aStr.ConvertLineEnd() ); FreeResource(); } SwFldInputDlg::~SwFldInputDlg() { } void SwFldInputDlg::StateChanged( StateChangedType nType ) { if ( nType == STATE_CHANGE_INITSHOW ) aEditED.GrabFocus(); SvxStandardDialog::StateChanged( nType ); } /*-------------------------------------------------------------------- Beschreibung: Schliessen --------------------------------------------------------------------*/ void SwFldInputDlg::Apply() { String aTmp( aEditED.GetText() ); aTmp.EraseAllChars( '\r' ); rSh.StartAllAction(); BOOL bModified = FALSE; if(pInpFld) { if(pUsrType) { if( aTmp != pUsrType->GetContent() ) { pUsrType->SetContent(aTmp); pUsrType->UpdateFlds(); bModified = TRUE; } } else if( aTmp != pInpFld->GetPar1() ) { pInpFld->SetPar1(aTmp); rSh.SwEditShell::UpdateFlds(*pInpFld); bModified = TRUE; } } else if( aTmp != pSetFld->GetPar2() ) { pSetFld->SetPar2(aTmp); rSh.SwEditShell::UpdateFlds(*pSetFld); bModified = TRUE; } if( bModified ) rSh.SetUndoNoResetModified(); rSh.EndAllAction(); } IMPL_LINK(SwFldInputDlg, NextHdl, PushButton*, EMPTYARG) { EndDialog(RET_OK); return 0; } <|endoftext|>
<commit_before><commit_msg>fdo#40948: TOC dialog, Entries tab: the right arrow button does not work<commit_after><|endoftext|>
<commit_before>//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRegisteredDesFactory.cpp 23113 2015-01-28 17:04:17Z gpotts $ #include <ossim/support_data/ossimNitfRegisteredDesFactory.h> #include <ossim/support_data/ossimNitfXmlDataContentDes.h> #include <ossim/support_data/ossimNitfSicdXmlDes.h> RTTI_DEF1(ossimNitfRegisteredDesFactory, "ossimNitfRegisteredDesFactory", ossimNitfDesFactory); static const char XML_DATA_CONTENT_DES[] = "XML_DATA_CONTENT"; static const char SICD_XML[] = "SICD_XML"; ossimNitfRegisteredDesFactory::ossimNitfRegisteredDesFactory() { } ossimNitfRegisteredDesFactory::~ossimNitfRegisteredDesFactory() { } ossimNitfRegisteredDesFactory* ossimNitfRegisteredDesFactory::instance() { static ossimNitfRegisteredDesFactory inst; return &inst; } ossimRefPtr<ossimNitfRegisteredDes> ossimNitfRegisteredDesFactory::create( const ossimString& desName)const { ossimString name = ossimString(desName).trim().upcase(); if(desName == XML_DATA_CONTENT_DES) { return new ossimNitfXmlDataContentDes; } else if(desName == SICD_XML) { return new ossimNitfSicdXmlDes; } return NULL; } <commit_msg>Added checks for SICD_XML and XML_DATA_CONTENT<commit_after>//******************************************************************* // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: Nitf support class // //******************************************************************** // $Id: ossimNitfRegisteredDesFactory.cpp 23113 2015-01-28 17:04:17Z gpotts $ #include <ossim/support_data/ossimNitfRegisteredDesFactory.h> #include <ossim/support_data/ossimNitfSicdXmlDataContentDes.h> RTTI_DEF1(ossimNitfRegisteredDesFactory, "ossimNitfRegisteredDesFactory", ossimNitfDesFactory); static const char XML_DATA_CONTENT_DES[] = "XML_DATA_CONTENT"; static const char SICD_XML[] = "SICD_XML"; ossimNitfRegisteredDesFactory::ossimNitfRegisteredDesFactory() { } ossimNitfRegisteredDesFactory::~ossimNitfRegisteredDesFactory() { } ossimNitfRegisteredDesFactory* ossimNitfRegisteredDesFactory::instance() { static ossimNitfRegisteredDesFactory inst; return &inst; } ossimRefPtr<ossimNitfRegisteredDes> ossimNitfRegisteredDesFactory::create( const ossimString& desName)const { ossimString name = ossimString(desName).trim().upcase(); ossimRefPtr<ossimNitfRegisteredDes> result; if (desName == XML_DATA_CONTENT_DES || desName == SICD_XML) { result = new ossimNitfSicdXmlDataContentDes; result->setDesName(desName); } return result; } <|endoftext|>
<commit_before><commit_msg>coverity#738911 Uninitialized pointer field<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtsh3.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: hr $ $Date: 2006-08-14 18:05:26 $ * * 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 * ************************************************************************/ #pragma hdrstop #ifndef _SVX_SVXIDS_HRC //autogen #include <svx/svxids.hrc> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SFX_CHILDWIN_HXX //autogen #include <sfx2/childwin.hxx> #endif #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef _SVDMARK_HXX //autogen #include <svx/svdmark.hxx> #endif #ifndef _SVDVIEW_HXX //autogen #include <svx/svdview.hxx> #endif #ifndef _SVX_FMGLOB_HXX #include <svx/fmglob.hxx> #endif #ifndef _SVDOUNO_HXX //autogen #include <svx/svdouno.hxx> #endif #ifndef _COM_SUN_STAR_FORM_FORMBUTTONTYPE_HPP_ #include <com/sun/star/form/FormButtonType.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _SVX_HTMLMODE_HXX #include <svx/htmlmode.hxx> #endif #ifndef _URLOBJ_HXX //autogen #include <tools/urlobj.hxx> #endif #include "wrtsh.hxx" #include "view.hxx" #include "bookmrk.hxx" #include "doc.hxx" #include "wrtsh.hrc" #define C2U(cChar) rtl::OUString::createFromAscii(cChar) using namespace ::com::sun::star; using namespace ::rtl; extern sal_Bool bNoInterrupt; // in mainwn.cxx FASTBOOL SwWrtShell::MoveBookMark( BookMarkMove eFuncId, sal_uInt16 nPos, sal_Bool bStart ) { //JP 08.03.96: die Wizards brauchen die Selektion !! // EndSelect(); (this->*fnKillSel)( 0, sal_False ); FASTBOOL bRet = sal_True; switch(eFuncId) { case BOOKMARK_INDEX:bRet = SwCrsrShell::GotoBookmark( nPos );break; case BOOKMARK_NEXT: bRet = SwCrsrShell::GoNextBookmark();break; case BOOKMARK_PREV: bRet = SwCrsrShell::GoPrevBookmark();break; } if( bRet && IsSelFrmMode() ) { UnSelectFrm(); LeaveSelFrmMode(); } if( IsSelection() ) { fnKillSel = &SwWrtShell::ResetSelect; fnSetCrsr = &SwWrtShell::SetCrsrKillSel; } return bRet; } /*-------------------------------------------------------------------- Beschreibung: FontWork-Slots invalidieren --------------------------------------------------------------------*/ void SwWrtShell::DrawSelChanged(SdrView* pView) { static sal_uInt16 __READONLY_DATA aInval[] = { SID_ATTR_FILL_STYLE, SID_ATTR_FILL_COLOR, SID_ATTR_LINE_STYLE, SID_ATTR_LINE_WIDTH, SID_ATTR_LINE_COLOR, 0 }; GetView().GetViewFrame()->GetBindings().Invalidate(aInval); sal_Bool bOldVal = bNoInterrupt; bNoInterrupt = sal_True; // Trick, um AttrChangedNotify ueber Timer auszufuehren GetView().AttrChangedNotify(this); bNoInterrupt = bOldVal; } FASTBOOL SwWrtShell::GotoBookmark( const String& rName ) { sal_uInt16 nPos = FindBookmark( rName ); if( USHRT_MAX == nPos ) return sal_False; return MoveBookMark( BOOKMARK_INDEX, nPos ); } FASTBOOL SwWrtShell::GotoBookmark( sal_uInt16 nPos ) { return MoveBookMark( BOOKMARK_INDEX, nPos ); } FASTBOOL SwWrtShell::GoNextBookmark() { return MoveBookMark( BOOKMARK_NEXT ); } FASTBOOL SwWrtShell::GoPrevBookmark() { return MoveBookMark( BOOKMARK_PREV ); } void SwWrtShell::ExecMacro( const SvxMacro& rMacro, String* pRet, SbxArray* pArgs ) { // OD 11.02.2003 #100556# - execute macro, if it is allowed. if ( IsMacroExecAllowed() ) { GetDoc()->ExecMacro( rMacro, pRet, pArgs ); } } sal_uInt16 SwWrtShell::CallEvent( sal_uInt16 nEvent, const SwCallMouseEvent& rCallEvent, sal_Bool bChkPtr, SbxArray* pArgs, const Link* pCallBack ) { return GetDoc()->CallEvent( nEvent, rCallEvent, bChkPtr, pArgs, pCallBack ); } // fall ein util::URL-Button selektiert ist, dessen util::URL returnen, ansonsten // einen LeerString sal_Bool SwWrtShell::GetURLFromButton( String& rURL, String& rDescr ) const { sal_Bool bRet = sal_False; const SdrView *pDView = GetDrawView(); if( pDView ) { // Ein Fly ist genau dann erreichbar, wenn er selektiert ist. const SdrMarkList &rMarkList = pDView->GetMarkedObjectList(); if (rMarkList.GetMark(0)) { SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, rMarkList.GetMark(0)->GetMarkedSdrObj()); if (pUnoCtrl && FmFormInventor == pUnoCtrl->GetObjInventor()) { uno::Reference< awt::XControlModel > xControlModel = pUnoCtrl->GetUnoControlModel(); ASSERT( xControlModel.is(), "UNO-Control ohne Model" ); if( !xControlModel.is() ) return bRet; uno::Reference< beans::XPropertySet > xPropSet(xControlModel, uno::UNO_QUERY); uno::Any aTmp; form::FormButtonType eButtonType = form::FormButtonType_URL; uno::Reference< beans::XPropertySetInfo > xInfo = xPropSet->getPropertySetInfo(); if(xInfo->hasPropertyByName( C2U("ButtonType") )) { aTmp = xPropSet->getPropertyValue( C2U("ButtonType") ); form::FormButtonType eTmpButtonType; aTmp >>= eTmpButtonType; if( eButtonType == eTmpButtonType) { // Label aTmp = xPropSet->getPropertyValue( C2U("Label") ); OUString uTmp; if( (aTmp >>= uTmp) && uTmp.getLength()) { rDescr = String(uTmp); } // util::URL aTmp = xPropSet->getPropertyValue( C2U("TargetURL") ); if( (aTmp >>= uTmp) && uTmp.getLength()) { rURL = String(uTmp); } bRet = sal_True; } } } } } return bRet; } <commit_msg>INTEGRATION: CWS pchfix02 (1.11.2); FILE MERGED 2006/09/01 17:53:37 kaib 1.11.2.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtsh3.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:40:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _SVX_SVXIDS_HRC //autogen #include <svx/svxids.hrc> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SFX_CHILDWIN_HXX //autogen #include <sfx2/childwin.hxx> #endif #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef _SVDMARK_HXX //autogen #include <svx/svdmark.hxx> #endif #ifndef _SVDVIEW_HXX //autogen #include <svx/svdview.hxx> #endif #ifndef _SVX_FMGLOB_HXX #include <svx/fmglob.hxx> #endif #ifndef _SVDOUNO_HXX //autogen #include <svx/svdouno.hxx> #endif #ifndef _COM_SUN_STAR_FORM_FORMBUTTONTYPE_HPP_ #include <com/sun/star/form/FormButtonType.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _SVX_HTMLMODE_HXX #include <svx/htmlmode.hxx> #endif #ifndef _URLOBJ_HXX //autogen #include <tools/urlobj.hxx> #endif #include "wrtsh.hxx" #include "view.hxx" #include "bookmrk.hxx" #include "doc.hxx" #include "wrtsh.hrc" #define C2U(cChar) rtl::OUString::createFromAscii(cChar) using namespace ::com::sun::star; using namespace ::rtl; extern sal_Bool bNoInterrupt; // in mainwn.cxx FASTBOOL SwWrtShell::MoveBookMark( BookMarkMove eFuncId, sal_uInt16 nPos, sal_Bool bStart ) { //JP 08.03.96: die Wizards brauchen die Selektion !! // EndSelect(); (this->*fnKillSel)( 0, sal_False ); FASTBOOL bRet = sal_True; switch(eFuncId) { case BOOKMARK_INDEX:bRet = SwCrsrShell::GotoBookmark( nPos );break; case BOOKMARK_NEXT: bRet = SwCrsrShell::GoNextBookmark();break; case BOOKMARK_PREV: bRet = SwCrsrShell::GoPrevBookmark();break; } if( bRet && IsSelFrmMode() ) { UnSelectFrm(); LeaveSelFrmMode(); } if( IsSelection() ) { fnKillSel = &SwWrtShell::ResetSelect; fnSetCrsr = &SwWrtShell::SetCrsrKillSel; } return bRet; } /*-------------------------------------------------------------------- Beschreibung: FontWork-Slots invalidieren --------------------------------------------------------------------*/ void SwWrtShell::DrawSelChanged(SdrView* pView) { static sal_uInt16 __READONLY_DATA aInval[] = { SID_ATTR_FILL_STYLE, SID_ATTR_FILL_COLOR, SID_ATTR_LINE_STYLE, SID_ATTR_LINE_WIDTH, SID_ATTR_LINE_COLOR, 0 }; GetView().GetViewFrame()->GetBindings().Invalidate(aInval); sal_Bool bOldVal = bNoInterrupt; bNoInterrupt = sal_True; // Trick, um AttrChangedNotify ueber Timer auszufuehren GetView().AttrChangedNotify(this); bNoInterrupt = bOldVal; } FASTBOOL SwWrtShell::GotoBookmark( const String& rName ) { sal_uInt16 nPos = FindBookmark( rName ); if( USHRT_MAX == nPos ) return sal_False; return MoveBookMark( BOOKMARK_INDEX, nPos ); } FASTBOOL SwWrtShell::GotoBookmark( sal_uInt16 nPos ) { return MoveBookMark( BOOKMARK_INDEX, nPos ); } FASTBOOL SwWrtShell::GoNextBookmark() { return MoveBookMark( BOOKMARK_NEXT ); } FASTBOOL SwWrtShell::GoPrevBookmark() { return MoveBookMark( BOOKMARK_PREV ); } void SwWrtShell::ExecMacro( const SvxMacro& rMacro, String* pRet, SbxArray* pArgs ) { // OD 11.02.2003 #100556# - execute macro, if it is allowed. if ( IsMacroExecAllowed() ) { GetDoc()->ExecMacro( rMacro, pRet, pArgs ); } } sal_uInt16 SwWrtShell::CallEvent( sal_uInt16 nEvent, const SwCallMouseEvent& rCallEvent, sal_Bool bChkPtr, SbxArray* pArgs, const Link* pCallBack ) { return GetDoc()->CallEvent( nEvent, rCallEvent, bChkPtr, pArgs, pCallBack ); } // fall ein util::URL-Button selektiert ist, dessen util::URL returnen, ansonsten // einen LeerString sal_Bool SwWrtShell::GetURLFromButton( String& rURL, String& rDescr ) const { sal_Bool bRet = sal_False; const SdrView *pDView = GetDrawView(); if( pDView ) { // Ein Fly ist genau dann erreichbar, wenn er selektiert ist. const SdrMarkList &rMarkList = pDView->GetMarkedObjectList(); if (rMarkList.GetMark(0)) { SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, rMarkList.GetMark(0)->GetMarkedSdrObj()); if (pUnoCtrl && FmFormInventor == pUnoCtrl->GetObjInventor()) { uno::Reference< awt::XControlModel > xControlModel = pUnoCtrl->GetUnoControlModel(); ASSERT( xControlModel.is(), "UNO-Control ohne Model" ); if( !xControlModel.is() ) return bRet; uno::Reference< beans::XPropertySet > xPropSet(xControlModel, uno::UNO_QUERY); uno::Any aTmp; form::FormButtonType eButtonType = form::FormButtonType_URL; uno::Reference< beans::XPropertySetInfo > xInfo = xPropSet->getPropertySetInfo(); if(xInfo->hasPropertyByName( C2U("ButtonType") )) { aTmp = xPropSet->getPropertyValue( C2U("ButtonType") ); form::FormButtonType eTmpButtonType; aTmp >>= eTmpButtonType; if( eButtonType == eTmpButtonType) { // Label aTmp = xPropSet->getPropertyValue( C2U("Label") ); OUString uTmp; if( (aTmp >>= uTmp) && uTmp.getLength()) { rDescr = String(uTmp); } // util::URL aTmp = xPropSet->getPropertyValue( C2U("TargetURL") ); if( (aTmp >>= uTmp) && uTmp.getLength()) { rURL = String(uTmp); } bRet = sal_True; } } } } } return bRet; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep16/call_host_activate_master.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] 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 */ // Error Handling #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <initservice/isteps_trace.H> #include <isteps/hwpisteperror.H> #include <errl/errludtarget.H> #include <intr/interrupt.H> #include <console/consoleif.H> // targeting support #include <targeting/namedtarget.H> #include <targeting/attrsync.H> #include <fapi2/target.H> //SBE interfacing #include <sbeio/sbeioif.H> #include <sys/misc.h> //Import directory (EKB) #include <p9_block_wakeup_intr.H> #include <p9_cpu_special_wakeup.H> //HWP invoker #include <fapi2/plat_hwp_invoker.H> using namespace ERRORLOG; using namespace TARGETING; using namespace ISTEP; using namespace ISTEP_ERROR; using namespace p9specialWakeup; namespace ISTEP_16 { void* call_host_activate_master (void *io_pArgs) { IStepError l_stepError; TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master entry" ); errlHndl_t l_errl = NULL; do { // find the master core, i.e. the one we are running on TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master: Find master core: " ); const TARGETING::Target* l_masterCore = getMasterCore( ); assert( l_masterCore != NULL ); TARGETING::Target* l_proc_target = const_cast<TARGETING::Target *> ( getParentChip( l_masterCore ) ); // Cast OUR type of target to a FAPI2 type of target. const fapi2::Target<fapi2::TARGET_TYPE_CORE> l_fapi2_coreTarget( const_cast<TARGETING::Target*> (l_masterCore)); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master: About to start deadman loop... " "Target HUID %.8X", TARGETING::get_huid(l_proc_target)); //In the future possibly move default "waitTime" value to SBEIO code uint64_t waitTime = 10000; l_errl = SBEIO::startDeadmanLoop(waitTime); if ( l_errl ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "startDeadmanLoop ERROR : Returning errorlog, reason=0x%x", l_errl->reasonCode() ); // capture the target data in the elog ErrlUserDetailsTarget(l_proc_target).addToLog( l_errl ); break; } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "startDeadManLoop SUCCESS" ); } //Need to indicate to PHYP to save HRMOR and other SPR Data to be // applied during wakeup MAGIC_INSTRUCTION(MAGIC_SIMICS_CORESTATESAVE); //Because of a bug in how the SBE injects the IPI used to wake //up the master core, need to ensure no mailbox traffic //or even an interrupt in the interrupt presenter // 1) suspend the mailbox with interrupt disable // 2) ensure that interrupt presenter is drained l_errl = MBOX::suspend(true, true); if (l_errl) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master ERROR : MBOX::suspend"); break; } //@TODO RTC:137564 Support for thread-specific interrupts // TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "draining interrupt Q"); // INTR::drainQueue(); // Call p9_block_wakeup_intr to prevent stray interrupts from // popping core out of winkle before SBE sees it. TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activated_master: call p9_block_wakeup_intr(SET) " "Target HUID %.8x", TARGETING::get_huid(l_fapi2_coreTarget) ); FAPI_INVOKE_HWP( l_errl, p9_block_wakeup_intr, l_fapi2_coreTarget, p9pmblockwkup::SET ); if ( l_errl ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "p9_block_wakeup_intr ERROR : Returning errorlog, reason=0x%x", l_errl->reasonCode() ); // capture the target data in the elog ErrlUserDetailsTarget(l_masterCore).addToLog( l_errl ); break; } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "p9_block_wakeup_intr SUCCESS" ); } // Clear special wakeup TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Disable special wakeup on master core"); FAPI_INVOKE_HWP(l_errl, p9_cpu_special_wakeup, l_fapi2_coreTarget, SPCWKUP_DISABLE, HOST); if(l_errl) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Disable p9_cpu_special_wakeup ERROR : Returning errorlog," " reason=0x%x", l_errl->reasonCode() ); // capture the target data in the elog ErrlUserDetailsTarget(l_masterCore).addToLog( l_errl ); break; } else { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Disable special wakeup on master core SUCCESS"); } // put the master into winkle. TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master: put master into winkle..." ); // Flush any lingering console traces first CONSOLE::flush(); bool l_fusedCores = is_fused_mode(); int l_rc = cpu_master_winkle(l_fusedCores); if ( l_rc ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : failed to winkle master, rc=0x%x", l_rc ); /*@ * @errortype * @reasoncode RC_FAIL_MASTER_WINKLE * @severity ERRORLOG::ERRL_SEV_UNRECOVERABLE * @moduleid MOD_HOST_ACTIVATE_MASTER * @userdata1 return code from cpu_master_winkle * @userdata2 Fused core indicator * * @devdesc cpu_master_winkle returned an error */ l_errl = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE, MOD_HOST_ACTIVATE_MASTER, RC_FAIL_MASTER_WINKLE, l_rc, l_fusedCores ); break; } // -------------------------------------------------------- // should return from Winkle at this point // -------------------------------------------------------- TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Returned from Winkle." ); //Re-enable the mailbox l_errl = MBOX::resume(); if (l_errl) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master ERROR : MBOX::resume"); break; } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Call proc_stop_deadman_timer. Target %.8X", TARGETING::get_huid(l_proc_target) ); l_errl = SBEIO::stopDeadmanLoop(); if ( l_errl ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "stopDeadmanLoop ERROR : " "Returning errorlog, reason=0x%x", l_errl->reasonCode() ); // capture the target data in the elog ErrlUserDetailsTarget(l_proc_target).addToLog( l_errl ); break; } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "stopDeadmanLoop SUCCESS" ); } TARGETING::Target* sys = NULL; TARGETING::targetService().getTopLevelTarget(sys); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Enable special wakeup on master core"); FAPI_INVOKE_HWP(l_errl, p9_cpu_special_wakeup, l_fapi2_coreTarget, SPCWKUP_ENABLE, HOST); if(l_errl) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Enable p9_cpu_special_wakeup ERROR : Returning errorlog, " "reason=0x%x", l_errl->reasonCode() ); // capture the target data in the elog ErrlUserDetailsTarget(l_masterCore).addToLog( l_errl ); break; } else { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Enable special wakeup on master core SUCCESS"); } } while ( 0 ); if( l_errl ) { // Create IStep error log and cross reference error that occurred l_stepError.addErrorDetails( l_errl ); // Commit Error errlCommit( l_errl, HWPF_COMP_ID ); } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master exit" ); // end task, returning any errorlogs to IStepDisp return l_stepError.getErrorHandle(); } }; <commit_msg>Enable call to INTR::drainQueue() in host_activate_master<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep16/call_host_activate_master.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] 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 */ // Error Handling #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <initservice/isteps_trace.H> #include <isteps/hwpisteperror.H> #include <errl/errludtarget.H> #include <intr/interrupt.H> #include <console/consoleif.H> // targeting support #include <targeting/namedtarget.H> #include <targeting/attrsync.H> #include <fapi2/target.H> //SBE interfacing #include <sbeio/sbeioif.H> #include <sys/misc.h> //Import directory (EKB) #include <p9_block_wakeup_intr.H> #include <p9_cpu_special_wakeup.H> //HWP invoker #include <fapi2/plat_hwp_invoker.H> using namespace ERRORLOG; using namespace TARGETING; using namespace ISTEP; using namespace ISTEP_ERROR; using namespace p9specialWakeup; namespace ISTEP_16 { void* call_host_activate_master (void *io_pArgs) { IStepError l_stepError; TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master entry" ); errlHndl_t l_errl = NULL; do { // find the master core, i.e. the one we are running on TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master: Find master core: " ); const TARGETING::Target* l_masterCore = getMasterCore( ); assert( l_masterCore != NULL ); TARGETING::Target* l_proc_target = const_cast<TARGETING::Target *> ( getParentChip( l_masterCore ) ); // Cast OUR type of target to a FAPI2 type of target. const fapi2::Target<fapi2::TARGET_TYPE_CORE> l_fapi2_coreTarget( const_cast<TARGETING::Target*> (l_masterCore)); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master: About to start deadman loop... " "Target HUID %.8X", TARGETING::get_huid(l_proc_target)); //In the future possibly move default "waitTime" value to SBEIO code uint64_t waitTime = 10000; l_errl = SBEIO::startDeadmanLoop(waitTime); if ( l_errl ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "startDeadmanLoop ERROR : Returning errorlog, reason=0x%x", l_errl->reasonCode() ); // capture the target data in the elog ErrlUserDetailsTarget(l_proc_target).addToLog( l_errl ); break; } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "startDeadManLoop SUCCESS" ); } //Need to indicate to PHYP to save HRMOR and other SPR Data to be // applied during wakeup MAGIC_INSTRUCTION(MAGIC_SIMICS_CORESTATESAVE); //Because of a bug in how the SBE injects the IPI used to wake //up the master core, need to ensure no mailbox traffic //or even an interrupt in the interrupt presenter // 1) suspend the mailbox with interrupt disable // 2) ensure that interrupt presenter is drained l_errl = MBOX::suspend(true, true); if (l_errl) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master ERROR : MBOX::suspend"); break; } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "draining interrupt Q"); INTR::drainQueue(); // Call p9_block_wakeup_intr to prevent stray interrupts from // popping core out of winkle before SBE sees it. TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activated_master: call p9_block_wakeup_intr(SET) " "Target HUID %.8x", TARGETING::get_huid(l_fapi2_coreTarget) ); FAPI_INVOKE_HWP( l_errl, p9_block_wakeup_intr, l_fapi2_coreTarget, p9pmblockwkup::SET ); if ( l_errl ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "p9_block_wakeup_intr ERROR : Returning errorlog, reason=0x%x", l_errl->reasonCode() ); // capture the target data in the elog ErrlUserDetailsTarget(l_masterCore).addToLog( l_errl ); break; } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "p9_block_wakeup_intr SUCCESS" ); } // Clear special wakeup TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Disable special wakeup on master core"); FAPI_INVOKE_HWP(l_errl, p9_cpu_special_wakeup, l_fapi2_coreTarget, SPCWKUP_DISABLE, HOST); if(l_errl) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Disable p9_cpu_special_wakeup ERROR : Returning errorlog," " reason=0x%x", l_errl->reasonCode() ); // capture the target data in the elog ErrlUserDetailsTarget(l_masterCore).addToLog( l_errl ); break; } else { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Disable special wakeup on master core SUCCESS"); } // put the master into winkle. TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master: put master into winkle..." ); // Flush any lingering console traces first CONSOLE::flush(); bool l_fusedCores = is_fused_mode(); int l_rc = cpu_master_winkle(l_fusedCores); if ( l_rc ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : failed to winkle master, rc=0x%x", l_rc ); /*@ * @errortype * @reasoncode RC_FAIL_MASTER_WINKLE * @severity ERRORLOG::ERRL_SEV_UNRECOVERABLE * @moduleid MOD_HOST_ACTIVATE_MASTER * @userdata1 return code from cpu_master_winkle * @userdata2 Fused core indicator * * @devdesc cpu_master_winkle returned an error */ l_errl = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE, MOD_HOST_ACTIVATE_MASTER, RC_FAIL_MASTER_WINKLE, l_rc, l_fusedCores ); break; } // -------------------------------------------------------- // should return from Winkle at this point // -------------------------------------------------------- TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Returned from Winkle." ); //Re-enable the mailbox l_errl = MBOX::resume(); if (l_errl) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master ERROR : MBOX::resume"); break; } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Call proc_stop_deadman_timer. Target %.8X", TARGETING::get_huid(l_proc_target) ); l_errl = SBEIO::stopDeadmanLoop(); if ( l_errl ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "stopDeadmanLoop ERROR : " "Returning errorlog, reason=0x%x", l_errl->reasonCode() ); // capture the target data in the elog ErrlUserDetailsTarget(l_proc_target).addToLog( l_errl ); break; } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "stopDeadmanLoop SUCCESS" ); } TARGETING::Target* sys = NULL; TARGETING::targetService().getTopLevelTarget(sys); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Enable special wakeup on master core"); FAPI_INVOKE_HWP(l_errl, p9_cpu_special_wakeup, l_fapi2_coreTarget, SPCWKUP_ENABLE, HOST); if(l_errl) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Enable p9_cpu_special_wakeup ERROR : Returning errorlog, " "reason=0x%x", l_errl->reasonCode() ); // capture the target data in the elog ErrlUserDetailsTarget(l_masterCore).addToLog( l_errl ); break; } else { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Enable special wakeup on master core SUCCESS"); } } while ( 0 ); if( l_errl ) { // Create IStep error log and cross reference error that occurred l_stepError.addErrorDetails( l_errl ); // Commit Error errlCommit( l_errl, HWPF_COMP_ID ); } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_host_activate_master exit" ); // end task, returning any errorlogs to IStepDisp return l_stepError.getErrorHandle(); } }; <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <xenia/kernel/modules/xboxkrnl/xboxkrnl_misc.h> #include <xenia/kernel/shim_utils.h> #include <xenia/kernel/modules/xboxkrnl/kernel_state.h> #include <xenia/kernel/modules/xboxkrnl/xboxkrnl_private.h> #include <xenia/kernel/modules/xboxkrnl/objects/xthread.h> using namespace xe; using namespace xe::kernel; using namespace xe::kernel::xboxkrnl; namespace xe { namespace kernel { namespace xboxkrnl { } // namespace xboxkrnl } // namespace kernel } // namespace xe void xe::kernel::xboxkrnl::RegisterMiscExports( ExportResolver* export_resolver, KernelState* state) { } <commit_msg>Added KeBugCheck and KeBugCheckEx.<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <xenia/kernel/modules/xboxkrnl/xboxkrnl_misc.h> #include <xenia/kernel/shim_utils.h> #include <xenia/kernel/modules/xboxkrnl/kernel_state.h> #include <xenia/kernel/modules/xboxkrnl/xboxkrnl_private.h> #include <xenia/kernel/modules/xboxkrnl/objects/xthread.h> using namespace xe; using namespace xe::kernel; using namespace xe::kernel::xboxkrnl; namespace xe { namespace kernel { namespace xboxkrnl { void xeKeBugCheckEx(uint32_t code, uint32_t param1, uint32_t param2, uint32_t param3, uint32_t param4) { XELOGD("*** STOP: 0x%.8X (0x%.8X, 0x%.8X, 0x%.8X, 0x%.8X)", code, param1, param2, param3, param4); XEASSERTALWAYS(); } SHIM_CALL KeBugCheck_shim( xe_ppc_state_t* ppc_state, KernelState* state) { uint32_t code = SHIM_GET_ARG_32(0); xeKeBugCheckEx(code, 0, 0, 0, 0); } SHIM_CALL KeBugCheckEx_shim( xe_ppc_state_t* ppc_state, KernelState* state) { uint32_t code = SHIM_GET_ARG_32(0); uint32_t param1 = SHIM_GET_ARG_32(1); uint32_t param2 = SHIM_GET_ARG_32(2); uint32_t param3 = SHIM_GET_ARG_32(3); uint32_t param4 = SHIM_GET_ARG_32(4); xeKeBugCheckEx(code, param1, param2, param3, param4); } } // namespace xboxkrnl } // namespace kernel } // namespace xe void xe::kernel::xboxkrnl::RegisterMiscExports( ExportResolver* export_resolver, KernelState* state) { SHIM_SET_MAPPING("xboxkrnl.exe", KeBugCheck, state); SHIM_SET_MAPPING("xboxkrnl.exe", KeBugCheckEx, state); } <|endoftext|>
<commit_before>// Copyright 2016 Peter Georg // // 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 "connection.hpp" #include "topology.hpp" #include "node.hpp" #include "../../providers/verbs/connection.hpp" #include "../../providers/verbs/topology.hpp" #include "../../misc/singleton.hpp" #include "../../backends/backend.hpp" #ifdef HINT #include "../../misc/print.hpp" #endif // HINT void pMR::Connection::connectVerbs(Target const &target) { verbs::Devices devices; auto device = verbs::getIBAdapter(devices); auto originNode = Singleton<Node>::Instance(device); auto sendBuffer = originNode.flatten(); decltype(sendBuffer) recvBuffer; backend::exchange(target, sendBuffer, recvBuffer); decltype(originNode) targetNode(recvBuffer); auto portNumber = detectBestPort(originNode, targetNode); mVerbs = std::make_shared<verbs::Connection>(target, device, portNumber); } std::uint8_t pMR::detectBestPort(Node const &origin, Node const &target) { // Origin and Target on same brick if(origin.getNodeGUID() == target.getNodeGUID()) { if(origin.getSCIFNodeID() + target.getSCIFNodeID() != 5) { return 1; } else { return 2; } } // Origin and Target in same hyperblock if(origin.getSwitchLID(1) == target.getSwitchLID(1) && origin.getSwitchLID(2) == target.getSwitchLID(2)) { if(origin.getSCIFNodeID() + target.getSCIFNodeID() < 6) { return 1; } else { return 2; } } // At least one common switch for(std::uint8_t portNumber = 1; portNumber != 3; ++portNumber) { if(origin.getSwitchLID(portNumber) == target.getSwitchLID(portNumber)) { return portNumber; } } // No common switch #ifdef HINT print("pMR: HINT: Using bad path. Check topology."); #endif // HINT if(origin.getSCIFNodeID() + target.getSCIFNodeID() < 6) { return 1; } else { return 2; } } <commit_msg>Remove HINT define<commit_after>// Copyright 2016 Peter Georg // // 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 "connection.hpp" #include "topology.hpp" #include "node.hpp" #include "../../providers/verbs/connection.hpp" #include "../../providers/verbs/topology.hpp" #include "../../misc/singleton.hpp" #include "../../backends/backend.hpp" #include "../../misc/print.hpp" void pMR::Connection::connectVerbs(Target const &target) { verbs::Devices devices; auto device = verbs::getIBAdapter(devices); auto originNode = Singleton<Node>::Instance(device); auto sendBuffer = originNode.flatten(); decltype(sendBuffer) recvBuffer; backend::exchange(target, sendBuffer, recvBuffer); decltype(originNode) targetNode(recvBuffer); auto portNumber = detectBestPort(originNode, targetNode); mVerbs = std::make_shared<verbs::Connection>(target, device, portNumber); } std::uint8_t pMR::detectBestPort(Node const &origin, Node const &target) { // Origin and Target on same brick if(origin.getNodeGUID() == target.getNodeGUID()) { if(origin.getSCIFNodeID() + target.getSCIFNodeID() != 5) { return 1; } else { return 2; } } // Origin and Target in same hyperblock if(origin.getSwitchLID(1) == target.getSwitchLID(1) && origin.getSwitchLID(2) == target.getSwitchLID(2)) { if(origin.getSCIFNodeID() + target.getSCIFNodeID() < 6) { return 1; } else { return 2; } } // At least one common switch for(std::uint8_t portNumber = 1; portNumber != 3; ++portNumber) { if(origin.getSwitchLID(portNumber) == target.getSwitchLID(portNumber)) { return portNumber; } } // No common switch print("pMR: Using bad path. Check topology."); if(origin.getSCIFNodeID() + target.getSCIFNodeID() < 6) { return 1; } else { return 2; } } <|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> /* * XXX * This is no longer up-to-date. * * 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 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. * * 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_) { DEBUG(log_) << "Decoder received, sent EOS."; decoder_sent_eos_ = true; decoder_produce_eos(); } else { DEBUG(log_) << "Decoder received EOS after sending EOS."; } return; } ASSERT(log_, !decoder_sent_eos_); buf->moveout(&decoder_buffer_); 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_.extract(&len, sizeof op); 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); if (decoder_cache_ == NULL) { decoder_cache_ = new XCodecMemoryCache(uuid); XCodecCache::enter(uuid, decoder_cache_); } ASSERT(log_, 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_.skip(sizeof op); decoder_buffer_.extract(&hash); decoder_buffer_.skip(sizeof hash); 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::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_buffer_.skip(1); 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_buffer_.skip(1); 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; if (decoder_buffer_.length() < sizeof op + sizeof len) return; 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 or we need an * unknown hash. 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(log_, !decoder_frame_buffer_.empty() || !decoder_unknown_hashes_.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."; decoder_produce_eos(); decoder_sent_eos_ = true; } if (encoder_sent_eos_ack_ && decoder_received_eos_ack_) { ASSERT(log_, decoder_buffer_.empty()); ASSERT(log_, decoder_frame_buffer_.empty()); DEBUG(log_) << "Decoder finished, got <EOS_ACK>, shutting down encoder output channel."; encoder_produce_eos(); } } void XCodecPipePair::encoder_consume(Buffer *buf) { ASSERT(log_, !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(log_, len == UUID_SIZE); output.append(XCODEC_PIPE_OP_HELLO); output.append(len); output.append(extra); ASSERT(log_, output.length() == 2 + UUID_SIZE); encoder_ = new XCodecEncoder(codec_->cache()); } if (!buf->empty()) { Buffer encoded; encoder_->encode(&encoded, buf); ASSERT(log_, !encoded.empty()); encode_frame(&output, &encoded); ASSERT(log_, !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>Remove misguided assertion.<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> /* * XXX * This is no longer up-to-date. * * 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 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. * * 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_) { DEBUG(log_) << "Decoder received, sent EOS."; decoder_sent_eos_ = true; decoder_produce_eos(); } else { DEBUG(log_) << "Decoder received EOS after sending EOS."; } return; } buf->moveout(&decoder_buffer_); 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_.extract(&len, sizeof op); 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); if (decoder_cache_ == NULL) { decoder_cache_ = new XCodecMemoryCache(uuid); XCodecCache::enter(uuid, decoder_cache_); } ASSERT(log_, 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_.skip(sizeof op); decoder_buffer_.extract(&hash); decoder_buffer_.skip(sizeof hash); 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::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_buffer_.skip(1); 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_buffer_.skip(1); 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; if (decoder_buffer_.length() < sizeof op + sizeof len) return; 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 or we need an * unknown hash. 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(log_, !decoder_frame_buffer_.empty() || !decoder_unknown_hashes_.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."; decoder_produce_eos(); decoder_sent_eos_ = true; } if (encoder_sent_eos_ack_ && decoder_received_eos_ack_) { ASSERT(log_, decoder_buffer_.empty()); ASSERT(log_, decoder_frame_buffer_.empty()); DEBUG(log_) << "Decoder finished, got <EOS_ACK>, shutting down encoder output channel."; encoder_produce_eos(); } } void XCodecPipePair::encoder_consume(Buffer *buf) { ASSERT(log_, !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(log_, len == UUID_SIZE); output.append(XCODEC_PIPE_OP_HELLO); output.append(len); output.append(extra); ASSERT(log_, output.length() == 2 + UUID_SIZE); encoder_ = new XCodecEncoder(codec_->cache()); } if (!buf->empty()) { Buffer encoded; encoder_->encode(&encoded, buf); ASSERT(log_, !encoded.empty()); encode_frame(&output, &encoded); ASSERT(log_, !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>/* * Copyright (c) 2017 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 SUSE LLC. * * To contact SUSE LLC about this file by physical or electronic mail, you may * find current contact information at www.suse.com. */ #include "storage/CompoundAction/Formatter/StrayBlkDevice.h" #include "storage/Devices/LvmPv.h" #include "storage/Devices/PartitionImpl.h" #include "storage/Filesystems/Swap.h" namespace storage { CompoundAction::Formatter::StrayBlkDevice::StrayBlkDevice(const CompoundAction::Impl* compound_action) : CompoundAction::Formatter(compound_action, "StrayBlkDevice"), stray_blk_device(to_stray_blk_device(compound_action->get_target_device())) {} Text CompoundAction::Formatter::StrayBlkDevice::text() const { if ( has_create<storage::LvmPv>() ) { if ( encrypting() ) return encrypted_pv_text(); else return pv_text(); } else if ( formatting() && is_swap( get_created_filesystem() ) ) { if ( encrypting() ) return format_as_encrypted_swap_text(); else return format_as_swap_text(); } else { if ( encrypting() && formatting() && mounting() ) return encrypted_with_fs_and_mount_point_text(); else if ( encrypting() && formatting() ) return encrypted_with_fs_text(); else if ( encrypting() ) return encrypted_text(); else if ( formatting() && mounting() ) return fs_and_mount_point_text(); else if ( formatting() ) return fs_text(); else if ( mounting() ) return mount_point_text(); else return default_text(); } } Text CompoundAction::Formatter::StrayBlkDevice::format_as_swap_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB) Text text = _("Format partition %1$s (%2$s) as swap"); return sformat(text, get_device_name().c_str(), get_size().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::format_as_encrypted_swap_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB) Text text = _("Format partition %1$s (%2$s) as encryped swap"); return sformat(text, get_device_name().c_str(), get_size().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::encrypted_pv_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB) Text text = _("Create LVM physical volume over encrypted %1$s (%2$s)"); return sformat(text, get_device_name().c_str(), get_size().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::pv_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB) Text text = _("Create LVM physical volume over %1$s (%2$s)"); return sformat(text, get_device_name().c_str(), get_size().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::encrypted_with_fs_and_mount_point_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), // %3$s is replaced by mount point (e.g. /home), // %4$s is replaced by file system name (e.g. ext4) Text text = _("Encrypt partition %1$s (%2$s) for %3$s with %4$s"); return sformat(text, get_device_name().c_str(), get_size().c_str(), get_mount_point().c_str(), get_filesystem_type().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::encrypted_with_fs_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), // %3$s is replaced by file system name (e.g. ext4) Text text = _("Encrypt partition %1$s (%2$s) with %3$s"); return sformat(text, get_device_name().c_str(), get_size().c_str(), get_filesystem_type().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::encrypted_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), Text text = _("Encrypt partition %1$s (%2$s)"); return sformat(text, get_device_name().c_str(), get_size().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::fs_and_mount_point_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), // %3$s is replaced by mount point (e.g. /home), // %4$s is replaced by file system name (e.g. ext4) Text text = _("Format partition %1$s (%2$s) for %3$s with %4$s"); return sformat(text, get_device_name().c_str(), get_size().c_str(), get_mount_point().c_str(), get_filesystem_type().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::fs_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), // %3$s is replaced by file system name (e.g. ext4) Text text = _("Format partition %1$s (%2$s) with %3$s"); return sformat(text, get_device_name().c_str(), get_size().c_str(), get_filesystem_type().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::mount_point_text() const { string mount_point = get_created_mount_point()->get_path(); // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), // %3$s is replaced by mount point (e.g. /home) Text text = _("Mount partition %1$s (%2$s) at %3$s"); return sformat(text, get_device_name().c_str(), get_size().c_str(), mount_point.c_str()); } } <commit_msg>Removed unnecessary include<commit_after>/* * Copyright (c) 2017 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 SUSE LLC. * * To contact SUSE LLC about this file by physical or electronic mail, you may * find current contact information at www.suse.com. */ #include "storage/CompoundAction/Formatter/StrayBlkDevice.h" #include "storage/Devices/LvmPv.h" #include "storage/Filesystems/Swap.h" namespace storage { CompoundAction::Formatter::StrayBlkDevice::StrayBlkDevice(const CompoundAction::Impl* compound_action) : CompoundAction::Formatter(compound_action, "StrayBlkDevice"), stray_blk_device(to_stray_blk_device(compound_action->get_target_device())) {} Text CompoundAction::Formatter::StrayBlkDevice::text() const { if ( has_create<storage::LvmPv>() ) { if ( encrypting() ) return encrypted_pv_text(); else return pv_text(); } else if ( formatting() && is_swap( get_created_filesystem() ) ) { if ( encrypting() ) return format_as_encrypted_swap_text(); else return format_as_swap_text(); } else { if ( encrypting() && formatting() && mounting() ) return encrypted_with_fs_and_mount_point_text(); else if ( encrypting() && formatting() ) return encrypted_with_fs_text(); else if ( encrypting() ) return encrypted_text(); else if ( formatting() && mounting() ) return fs_and_mount_point_text(); else if ( formatting() ) return fs_text(); else if ( mounting() ) return mount_point_text(); else return default_text(); } } Text CompoundAction::Formatter::StrayBlkDevice::format_as_swap_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB) Text text = _("Format partition %1$s (%2$s) as swap"); return sformat(text, get_device_name().c_str(), get_size().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::format_as_encrypted_swap_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB) Text text = _("Format partition %1$s (%2$s) as encryped swap"); return sformat(text, get_device_name().c_str(), get_size().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::encrypted_pv_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB) Text text = _("Create LVM physical volume over encrypted %1$s (%2$s)"); return sformat(text, get_device_name().c_str(), get_size().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::pv_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB) Text text = _("Create LVM physical volume over %1$s (%2$s)"); return sformat(text, get_device_name().c_str(), get_size().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::encrypted_with_fs_and_mount_point_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), // %3$s is replaced by mount point (e.g. /home), // %4$s is replaced by file system name (e.g. ext4) Text text = _("Encrypt partition %1$s (%2$s) for %3$s with %4$s"); return sformat(text, get_device_name().c_str(), get_size().c_str(), get_mount_point().c_str(), get_filesystem_type().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::encrypted_with_fs_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), // %3$s is replaced by file system name (e.g. ext4) Text text = _("Encrypt partition %1$s (%2$s) with %3$s"); return sformat(text, get_device_name().c_str(), get_size().c_str(), get_filesystem_type().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::encrypted_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), Text text = _("Encrypt partition %1$s (%2$s)"); return sformat(text, get_device_name().c_str(), get_size().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::fs_and_mount_point_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), // %3$s is replaced by mount point (e.g. /home), // %4$s is replaced by file system name (e.g. ext4) Text text = _("Format partition %1$s (%2$s) for %3$s with %4$s"); return sformat(text, get_device_name().c_str(), get_size().c_str(), get_mount_point().c_str(), get_filesystem_type().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::fs_text() const { // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), // %3$s is replaced by file system name (e.g. ext4) Text text = _("Format partition %1$s (%2$s) with %3$s"); return sformat(text, get_device_name().c_str(), get_size().c_str(), get_filesystem_type().c_str()); } Text CompoundAction::Formatter::StrayBlkDevice::mount_point_text() const { string mount_point = get_created_mount_point()->get_path(); // TRANSLATORS: // %1$s is replaced by partition name (e.g. /dev/sda1), // %2$s is replaced by size (e.g. 2GiB), // %3$s is replaced by mount point (e.g. /home) Text text = _("Mount partition %1$s (%2$s) at %3$s"); return sformat(text, get_device_name().c_str(), get_size().c_str(), mount_point.c_str()); } } <|endoftext|>
<commit_before>#include "ompl/extensions/ode/ODEStateSpace.h" #include "ompl/util/Console.h" #include <boost/lexical_cast.hpp> #include <limits> #include <queue> ompl::control::ODEStateSpace::ODEStateSpace(const ODEEnvironmentPtr &env, double positionWeight, double linVelWeight, double angVelWeight, double orientationWeight) : base::CompoundStateSpace(), env_(env) { setName("ODE" + getName()); for (unsigned int i = 0 ; i < env_->stateBodies_.size() ; ++i) { std::string body = ":B" + boost::lexical_cast<std::string>(i); addSubSpace(base::StateSpacePtr(new base::RealVectorStateSpace(3)), positionWeight); // position components_.back()->setName(components_.back()->getName() + body + ":position"); addSubSpace(base::StateSpacePtr(new base::RealVectorStateSpace(3)), linVelWeight); // linear velocity components_.back()->setName(components_.back()->getName() + body + ":linvel"); addSubSpace(base::StateSpacePtr(new base::RealVectorStateSpace(3)), angVelWeight); // angular velocity components_.back()->setName(components_.back()->getName() + body + ":angvel"); addSubSpace(base::StateSpacePtr(new base::SO3StateSpace()), orientationWeight); // orientation components_.back()->setName(components_.back()->getName() + body + ":orientation"); } lock(); setDefaultBounds(); } void ompl::control::ODEStateSpace::setDefaultBounds(void) { // limit all velocities to 1 m/s, 1 rad/s, respectively base::RealVectorBounds bounds1(3); bounds1.setLow(-1); bounds1.setHigh(1); setLinearVelocityBounds(bounds1); setAngularVelocityBounds(bounds1); // find the bounding box that contains all geoms included in the collision spaces double mX, mY, mZ, MX, MY, MZ; mX = mY = mZ = std::numeric_limits<double>::infinity(); MX = MY = MZ = -std::numeric_limits<double>::infinity(); bool found = false; std::queue<dSpaceID> spaces; for (unsigned int i = 0 ; i < env_->collisionSpaces_.size() ; ++i) spaces.push(env_->collisionSpaces_[i]); while (!spaces.empty()) { dSpaceID space = spaces.front(); spaces.pop(); int n = dSpaceGetNumGeoms(space); for (int j = 0 ; j < n ; ++j) { dGeomID geom = dSpaceGetGeom(space, j); if (dGeomIsSpace(geom)) spaces.push((dSpaceID)geom); else { bool valid = true; dReal aabb[6]; dGeomGetAABB(geom, aabb); // things like planes are infinite; we want to ignore those for (int k = 0 ; k < 6 ; ++k) if (fabs(aabb[k]) >= std::numeric_limits<dReal>::max()) { valid = false; break; } if (valid) { found = true; if (aabb[0] < mX) mX = aabb[0]; if (aabb[1] > MX) MX = aabb[1]; if (aabb[2] < mY) mY = aabb[2]; if (aabb[3] > MY) MY = aabb[3]; if (aabb[4] < mZ) mZ = aabb[4]; if (aabb[5] > MZ) MZ = aabb[5]; } } } } if (found) { double dx = MX - mX; double dy = MY - mY; double dz = MZ - mZ; double dM = std::max(dx, std::max(dy, dz)); // add 10% in each dimension + 1% of the max dimension dx = dx / 10.0 + dM / 100.0; dy = dy / 10.0 + dM / 100.0; dz = dz / 10.0 + dM / 100.0; bounds1.low[0] = mX - dx; bounds1.high[0] = MX + dx; bounds1.low[1] = mY - dy; bounds1.high[1] = MY + dy; bounds1.low[2] = mZ - dz; bounds1.high[2] = MZ + dz; setVolumeBounds(bounds1); } } void ompl::control::ODEStateSpace::copyState(base::State *destination, const base::State *source) const { CompoundStateSpace::copyState(destination, source); destination->as<StateType>()->collision = source->as<StateType>()->collision; } namespace ompl { /// @cond IGNORE struct CallbackParam { const control::ODEEnvironment *env; bool collision; }; /// @endcond static void nearCallback(void *data, dGeomID o1, dGeomID o2) { // if a collision has not already been detected if (reinterpret_cast<CallbackParam*>(data)->collision == false) { dBodyID b1 = dGeomGetBody(o1); dBodyID b2 = dGeomGetBody(o2); if (b1 && b2 && dAreConnectedExcluding(b1, b2, dJointTypeContact)) return; dContact contact[1]; // one contact is sufficient int numc = dCollide(o1, o2, 1, &contact[0].geom, sizeof(dContact)); // check if there is really a collision if (numc) { // check if the collision is allowed bool valid = reinterpret_cast<CallbackParam*>(data)->env->isValidCollision(o1, o2, contact[0]); reinterpret_cast<CallbackParam*>(data)->collision = !valid; if (reinterpret_cast<CallbackParam*>(data)->env->verboseContacts_) { static msg::Interface msg; msg.debug((valid ? "Valid" : "Invalid") + std::string(" contact between ") + reinterpret_cast<CallbackParam*>(data)->env->getGeomName(o1) + " and " + reinterpret_cast<CallbackParam*>(data)->env->getGeomName(o2)); } } } } } bool ompl::control::ODEStateSpace::evaluateCollision(const base::State *state) const { if (state->as<StateType>()->collision & (1 << STATE_COLLISION_KNOWN_BIT)) return state->as<StateType>()->collision & (1 << STATE_COLLISION_VALUE_BIT); env_->mutex_.lock(); writeState(state); CallbackParam cp = { env_.get(), false }; for (unsigned int i = 0 ; cp.collision == false && i < env_->collisionSpaces_.size() ; ++i) dSpaceCollide(env_->collisionSpaces_[i], &cp, &nearCallback); env_->mutex_.unlock(); if (cp.collision) state->as<StateType>()->collision &= (1 << STATE_COLLISION_VALUE_BIT); state->as<StateType>()->collision &= (1 << STATE_COLLISION_KNOWN_BIT); return cp.collision; } bool ompl::control::ODEStateSpace::satisfiesBoundsExceptRotation(const StateType *state) const { for (unsigned int i = 0 ; i < componentCount_ ; ++i) if (i % 4 != 3) if (!components_[i]->satisfiesBounds(state->components[i])) return false; return true; } void ompl::control::ODEStateSpace::setVolumeBounds(const base::RealVectorBounds &bounds) { for (unsigned int i = 0 ; i < env_->stateBodies_.size() ; ++i) components_[i * 4]->as<base::RealVectorStateSpace>()->setBounds(bounds); } void ompl::control::ODEStateSpace::setLinearVelocityBounds(const base::RealVectorBounds &bounds) { for (unsigned int i = 0 ; i < env_->stateBodies_.size() ; ++i) components_[i * 4 + 1]->as<base::RealVectorStateSpace>()->setBounds(bounds); } void ompl::control::ODEStateSpace::setAngularVelocityBounds(const base::RealVectorBounds &bounds) { for (unsigned int i = 0 ; i < env_->stateBodies_.size() ; ++i) components_[i * 4 + 2]->as<base::RealVectorStateSpace>()->setBounds(bounds); } ompl::base::State* ompl::control::ODEStateSpace::allocState(void) const { StateType *state = new StateType(); allocStateComponents(state); return state; } void ompl::control::ODEStateSpace::freeState(base::State *state) const { CompoundStateSpace::freeState(state); } void ompl::control::ODEStateSpace::readState(base::State *state) const { StateType *s = state->as<StateType>(); for (int i = (int)env_->stateBodies_.size() - 1 ; i >= 0 ; --i) { unsigned int _i4 = i * 4; const dReal *pos = dBodyGetPosition(env_->stateBodies_[i]); const dReal *vel = dBodyGetLinearVel(env_->stateBodies_[i]); const dReal *ang = dBodyGetAngularVel(env_->stateBodies_[i]); double *s_pos = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; double *s_vel = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; double *s_ang = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; for (int j = 0; j < 3; ++j) { s_pos[j] = pos[j]; s_vel[j] = vel[j]; s_ang[j] = ang[j]; } const dReal *rot = dBodyGetQuaternion(env_->stateBodies_[i]); base::SO3StateSpace::StateType &s_rot = *s->as<base::SO3StateSpace::StateType>(_i4); s_rot.w = rot[0]; s_rot.x = rot[1]; s_rot.y = rot[2]; s_rot.z = rot[3]; } } void ompl::control::ODEStateSpace::writeState(const base::State *state) const { const StateType *s = state->as<StateType>(); for (int i = (int)env_->stateBodies_.size() - 1 ; i >= 0 ; --i) { unsigned int _i4 = i * 4; double *s_pos = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; dBodySetPosition(env_->stateBodies_[i], s_pos[0], s_pos[1], s_pos[2]); double *s_vel = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; dBodySetLinearVel(env_->stateBodies_[i], s_vel[0], s_vel[1], s_vel[2]); double *s_ang = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; dBodySetAngularVel(env_->stateBodies_[i], s_ang[0], s_ang[1], s_ang[2]); const base::SO3StateSpace::StateType &s_rot = *s->as<base::SO3StateSpace::StateType>(_i4); dQuaternion q; q[0] = s_rot.w; q[1] = s_rot.x; q[2] = s_rot.y; q[3] = s_rot.z; dBodySetQuaternion(env_->stateBodies_[i], q); } } <commit_msg>minor doc fix<commit_after>#include "ompl/extensions/ode/ODEStateSpace.h" #include "ompl/util/Console.h" #include <boost/lexical_cast.hpp> #include <limits> #include <queue> ompl::control::ODEStateSpace::ODEStateSpace(const ODEEnvironmentPtr &env, double positionWeight, double linVelWeight, double angVelWeight, double orientationWeight) : base::CompoundStateSpace(), env_(env) { setName("ODE" + getName()); for (unsigned int i = 0 ; i < env_->stateBodies_.size() ; ++i) { std::string body = ":B" + boost::lexical_cast<std::string>(i); addSubSpace(base::StateSpacePtr(new base::RealVectorStateSpace(3)), positionWeight); // position components_.back()->setName(components_.back()->getName() + body + ":position"); addSubSpace(base::StateSpacePtr(new base::RealVectorStateSpace(3)), linVelWeight); // linear velocity components_.back()->setName(components_.back()->getName() + body + ":linvel"); addSubSpace(base::StateSpacePtr(new base::RealVectorStateSpace(3)), angVelWeight); // angular velocity components_.back()->setName(components_.back()->getName() + body + ":angvel"); addSubSpace(base::StateSpacePtr(new base::SO3StateSpace()), orientationWeight); // orientation components_.back()->setName(components_.back()->getName() + body + ":orientation"); } lock(); setDefaultBounds(); } void ompl::control::ODEStateSpace::setDefaultBounds(void) { // limit all velocities to 1 m/s, 1 rad/s, respectively base::RealVectorBounds bounds1(3); bounds1.setLow(-1); bounds1.setHigh(1); setLinearVelocityBounds(bounds1); setAngularVelocityBounds(bounds1); // find the bounding box that contains all geoms included in the collision spaces double mX, mY, mZ, MX, MY, MZ; mX = mY = mZ = std::numeric_limits<double>::infinity(); MX = MY = MZ = -std::numeric_limits<double>::infinity(); bool found = false; std::queue<dSpaceID> spaces; for (unsigned int i = 0 ; i < env_->collisionSpaces_.size() ; ++i) spaces.push(env_->collisionSpaces_[i]); while (!spaces.empty()) { dSpaceID space = spaces.front(); spaces.pop(); int n = dSpaceGetNumGeoms(space); for (int j = 0 ; j < n ; ++j) { dGeomID geom = dSpaceGetGeom(space, j); if (dGeomIsSpace(geom)) spaces.push((dSpaceID)geom); else { bool valid = true; dReal aabb[6]; dGeomGetAABB(geom, aabb); // things like planes are infinite; we want to ignore those for (int k = 0 ; k < 6 ; ++k) if (fabs(aabb[k]) >= std::numeric_limits<dReal>::max()) { valid = false; break; } if (valid) { found = true; if (aabb[0] < mX) mX = aabb[0]; if (aabb[1] > MX) MX = aabb[1]; if (aabb[2] < mY) mY = aabb[2]; if (aabb[3] > MY) MY = aabb[3]; if (aabb[4] < mZ) mZ = aabb[4]; if (aabb[5] > MZ) MZ = aabb[5]; } } } } if (found) { double dx = MX - mX; double dy = MY - mY; double dz = MZ - mZ; double dM = std::max(dx, std::max(dy, dz)); // add 10% in each dimension + 1% of the max dimension dx = dx / 10.0 + dM / 100.0; dy = dy / 10.0 + dM / 100.0; dz = dz / 10.0 + dM / 100.0; bounds1.low[0] = mX - dx; bounds1.high[0] = MX + dx; bounds1.low[1] = mY - dy; bounds1.high[1] = MY + dy; bounds1.low[2] = mZ - dz; bounds1.high[2] = MZ + dz; setVolumeBounds(bounds1); } } void ompl::control::ODEStateSpace::copyState(base::State *destination, const base::State *source) const { CompoundStateSpace::copyState(destination, source); destination->as<StateType>()->collision = source->as<StateType>()->collision; } namespace ompl { /// @cond IGNORE struct CallbackParam { const control::ODEEnvironment *env; bool collision; }; static void nearCallback(void *data, dGeomID o1, dGeomID o2) { // if a collision has not already been detected if (reinterpret_cast<CallbackParam*>(data)->collision == false) { dBodyID b1 = dGeomGetBody(o1); dBodyID b2 = dGeomGetBody(o2); if (b1 && b2 && dAreConnectedExcluding(b1, b2, dJointTypeContact)) return; dContact contact[1]; // one contact is sufficient int numc = dCollide(o1, o2, 1, &contact[0].geom, sizeof(dContact)); // check if there is really a collision if (numc) { // check if the collision is allowed bool valid = reinterpret_cast<CallbackParam*>(data)->env->isValidCollision(o1, o2, contact[0]); reinterpret_cast<CallbackParam*>(data)->collision = !valid; if (reinterpret_cast<CallbackParam*>(data)->env->verboseContacts_) { static msg::Interface msg; msg.debug((valid ? "Valid" : "Invalid") + std::string(" contact between ") + reinterpret_cast<CallbackParam*>(data)->env->getGeomName(o1) + " and " + reinterpret_cast<CallbackParam*>(data)->env->getGeomName(o2)); } } } } /// @endcond } bool ompl::control::ODEStateSpace::evaluateCollision(const base::State *state) const { if (state->as<StateType>()->collision & (1 << STATE_COLLISION_KNOWN_BIT)) return state->as<StateType>()->collision & (1 << STATE_COLLISION_VALUE_BIT); env_->mutex_.lock(); writeState(state); CallbackParam cp = { env_.get(), false }; for (unsigned int i = 0 ; cp.collision == false && i < env_->collisionSpaces_.size() ; ++i) dSpaceCollide(env_->collisionSpaces_[i], &cp, &nearCallback); env_->mutex_.unlock(); if (cp.collision) state->as<StateType>()->collision &= (1 << STATE_COLLISION_VALUE_BIT); state->as<StateType>()->collision &= (1 << STATE_COLLISION_KNOWN_BIT); return cp.collision; } bool ompl::control::ODEStateSpace::satisfiesBoundsExceptRotation(const StateType *state) const { for (unsigned int i = 0 ; i < componentCount_ ; ++i) if (i % 4 != 3) if (!components_[i]->satisfiesBounds(state->components[i])) return false; return true; } void ompl::control::ODEStateSpace::setVolumeBounds(const base::RealVectorBounds &bounds) { for (unsigned int i = 0 ; i < env_->stateBodies_.size() ; ++i) components_[i * 4]->as<base::RealVectorStateSpace>()->setBounds(bounds); } void ompl::control::ODEStateSpace::setLinearVelocityBounds(const base::RealVectorBounds &bounds) { for (unsigned int i = 0 ; i < env_->stateBodies_.size() ; ++i) components_[i * 4 + 1]->as<base::RealVectorStateSpace>()->setBounds(bounds); } void ompl::control::ODEStateSpace::setAngularVelocityBounds(const base::RealVectorBounds &bounds) { for (unsigned int i = 0 ; i < env_->stateBodies_.size() ; ++i) components_[i * 4 + 2]->as<base::RealVectorStateSpace>()->setBounds(bounds); } ompl::base::State* ompl::control::ODEStateSpace::allocState(void) const { StateType *state = new StateType(); allocStateComponents(state); return state; } void ompl::control::ODEStateSpace::freeState(base::State *state) const { CompoundStateSpace::freeState(state); } void ompl::control::ODEStateSpace::readState(base::State *state) const { StateType *s = state->as<StateType>(); for (int i = (int)env_->stateBodies_.size() - 1 ; i >= 0 ; --i) { unsigned int _i4 = i * 4; const dReal *pos = dBodyGetPosition(env_->stateBodies_[i]); const dReal *vel = dBodyGetLinearVel(env_->stateBodies_[i]); const dReal *ang = dBodyGetAngularVel(env_->stateBodies_[i]); double *s_pos = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; double *s_vel = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; double *s_ang = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; for (int j = 0; j < 3; ++j) { s_pos[j] = pos[j]; s_vel[j] = vel[j]; s_ang[j] = ang[j]; } const dReal *rot = dBodyGetQuaternion(env_->stateBodies_[i]); base::SO3StateSpace::StateType &s_rot = *s->as<base::SO3StateSpace::StateType>(_i4); s_rot.w = rot[0]; s_rot.x = rot[1]; s_rot.y = rot[2]; s_rot.z = rot[3]; } } void ompl::control::ODEStateSpace::writeState(const base::State *state) const { const StateType *s = state->as<StateType>(); for (int i = (int)env_->stateBodies_.size() - 1 ; i >= 0 ; --i) { unsigned int _i4 = i * 4; double *s_pos = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; dBodySetPosition(env_->stateBodies_[i], s_pos[0], s_pos[1], s_pos[2]); double *s_vel = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; dBodySetLinearVel(env_->stateBodies_[i], s_vel[0], s_vel[1], s_vel[2]); double *s_ang = s->as<base::RealVectorStateSpace::StateType>(_i4)->values; ++_i4; dBodySetAngularVel(env_->stateBodies_[i], s_ang[0], s_ang[1], s_ang[2]); const base::SO3StateSpace::StateType &s_rot = *s->as<base::SO3StateSpace::StateType>(_i4); dQuaternion q; q[0] = s_rot.w; q[1] = s_rot.x; q[2] = s_rot.y; q[3] = s_rot.z; dBodySetQuaternion(env_->stateBodies_[i], q); } } <|endoftext|>
<commit_before>#include "report.hpp" #include "account.hpp" #include "account_type.hpp" #include "balance_sheet_report.hpp" #include "entry.hpp" #include "finformat.hpp" #include "locale.hpp" #include "ordinary_journal.hpp" #include "pl_report.hpp" #include "report_panel.hpp" #include "phatbooks_database_connection.hpp" #include "sizing.hpp" #include <boost/date_time/gregorian/gregorian.hpp> #include <jewel/decimal.hpp> #include <jewel/optional.hpp> #include <wx/stattext.h> using boost::optional; using jewel::Decimal; using jewel::value; namespace gregorian = boost::gregorian; namespace phatbooks { namespace gui { Report* Report::create ( ReportPanel* p_parent, wxSize const& p_size, account_super_type::AccountSuperType p_account_super_type, PhatbooksDatabaseConnection& p_database_connection, optional<gregorian::date> const& p_maybe_min_date, optional<gregorian::date> const& p_maybe_max_date ) { Report* temp = 0; switch (p_account_super_type) { case account_super_type::balance_sheet: temp = new BalanceSheetReport ( p_parent, p_size, p_database_connection, p_maybe_min_date, p_maybe_max_date ); break; case account_super_type::pl: temp = new PLReport ( p_parent, p_size, p_database_connection, p_maybe_min_date, p_maybe_max_date ); break; default: assert (false); } return temp; } Report::Report ( ReportPanel* p_parent, wxSize const& p_size, PhatbooksDatabaseConnection& p_database_connection, optional<gregorian::date> const& p_maybe_min_date, optional<gregorian::date> const& p_maybe_max_date ): wxScrolledWindow ( p_parent, wxID_ANY, wxDefaultPosition, p_size ), m_current_row(0), m_top_sizer(0), m_database_connection(p_database_connection), m_min_date(database_connection().opening_balance_journal_date()), m_maybe_max_date(p_maybe_max_date) { if (p_maybe_min_date) { gregorian::date const provided_min_date = value(p_maybe_min_date); if (provided_min_date > m_min_date) { m_min_date = provided_min_date; } } m_top_sizer = new wxGridBagSizer(standard_gap(), standard_gap()); SetSizer(m_top_sizer); } Report::~Report() { } gregorian::date Report::min_date() const { return m_min_date; } optional<gregorian::date> Report::maybe_max_date() const { return m_maybe_max_date; } void Report::increment_row() { ++m_current_row; return; } int Report::current_row() const { return m_current_row; } void Report::make_text ( wxString const& p_text, int p_column, int p_alignment_flags ) { wxStaticText* header = new wxStaticText ( this, wxID_ANY, p_text, wxDefaultPosition, wxDefaultSize, p_alignment_flags ); top_sizer().Add ( header, wxGBPosition(current_row(), p_column), wxDefaultSpan, p_alignment_flags ); return; } void Report::make_number_text(jewel::Decimal const& p_amount, int p_column) { wxStaticText* text = new wxStaticText ( this, wxID_ANY, finformat_wx(p_amount, locale()), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT ); top_sizer().Add ( text, wxGBPosition(current_row(), p_column), wxDefaultSpan, wxALIGN_RIGHT ); return; } wxGridBagSizer& Report::top_sizer() { assert (m_top_sizer); return *m_top_sizer; } void Report::update_for_new(OrdinaryJournal const& p_journal) { (void)p_journal; // silence compiler re. unused parameter. return; } void Report::update_for_amended(OrdinaryJournal const& p_journal) { (void)p_journal; // silence compiler re. unused parameter. return; } void Report::update_for_new(Account const& p_account) { (void)p_account; // silence compiler re. unused parameter. return; } void Report::update_for_amended(Account const& p_account) { (void)p_account; // silence compiler re. unused parameter. return; } void Report::update_for_deleted(std::vector<Entry::Id> const& p_doomed_ids) { (void)p_doomed_ids; return; } void Report::generate() { // TODO Can we factor up more shared code into here? configure_scrollbars(); do_generate(); // GetParent()->Layout(); // m_top_sizer->Fit(this); // m_top_sizer->SetSizeHints(this); FitInside(); // Layout(); return; } void Report::configure_scrollbars() { SetScrollRate(0, 10); FitInside(); return; } PhatbooksDatabaseConnection& Report::database_connection() { return m_database_connection; } } // namespace gui } // namespace phatbooks <commit_msg>Fixed issue in Report class where "Min date:", if left blank, was defaulting to the opening balance journal date; however it now defaults to the day after the opening balance journal date, which makes more sense, as it means that by default the opening balances shown in the balance sheet report correspond to the actual opening balance Entry amounts for each Account.<commit_after>#include "report.hpp" #include "account.hpp" #include "account_type.hpp" #include "balance_sheet_report.hpp" #include "entry.hpp" #include "finformat.hpp" #include "locale.hpp" #include "ordinary_journal.hpp" #include "pl_report.hpp" #include "report_panel.hpp" #include "phatbooks_database_connection.hpp" #include "sizing.hpp" #include <boost/date_time/gregorian/gregorian.hpp> #include <jewel/decimal.hpp> #include <jewel/optional.hpp> #include <wx/stattext.h> using boost::optional; using jewel::Decimal; using jewel::value; namespace gregorian = boost::gregorian; namespace phatbooks { namespace gui { Report* Report::create ( ReportPanel* p_parent, wxSize const& p_size, account_super_type::AccountSuperType p_account_super_type, PhatbooksDatabaseConnection& p_database_connection, optional<gregorian::date> const& p_maybe_min_date, optional<gregorian::date> const& p_maybe_max_date ) { Report* temp = 0; switch (p_account_super_type) { case account_super_type::balance_sheet: temp = new BalanceSheetReport ( p_parent, p_size, p_database_connection, p_maybe_min_date, p_maybe_max_date ); break; case account_super_type::pl: temp = new PLReport ( p_parent, p_size, p_database_connection, p_maybe_min_date, p_maybe_max_date ); break; default: assert (false); } return temp; } Report::Report ( ReportPanel* p_parent, wxSize const& p_size, PhatbooksDatabaseConnection& p_database_connection, optional<gregorian::date> const& p_maybe_min_date, optional<gregorian::date> const& p_maybe_max_date ): wxScrolledWindow ( p_parent, wxID_ANY, wxDefaultPosition, p_size ), m_current_row(0), m_top_sizer(0), m_database_connection(p_database_connection), m_min_date ( database_connection().opening_balance_journal_date() + gregorian::date_duration(1) ), m_maybe_max_date(p_maybe_max_date) { if (p_maybe_min_date) { gregorian::date const provided_min_date = value(p_maybe_min_date); if (provided_min_date > m_min_date) { m_min_date = provided_min_date; } } m_top_sizer = new wxGridBagSizer(standard_gap(), standard_gap()); SetSizer(m_top_sizer); } Report::~Report() { } gregorian::date Report::min_date() const { return m_min_date; } optional<gregorian::date> Report::maybe_max_date() const { return m_maybe_max_date; } void Report::increment_row() { ++m_current_row; return; } int Report::current_row() const { return m_current_row; } void Report::make_text ( wxString const& p_text, int p_column, int p_alignment_flags ) { wxStaticText* header = new wxStaticText ( this, wxID_ANY, p_text, wxDefaultPosition, wxDefaultSize, p_alignment_flags ); top_sizer().Add ( header, wxGBPosition(current_row(), p_column), wxDefaultSpan, p_alignment_flags ); return; } void Report::make_number_text(jewel::Decimal const& p_amount, int p_column) { wxStaticText* text = new wxStaticText ( this, wxID_ANY, finformat_wx(p_amount, locale()), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT ); top_sizer().Add ( text, wxGBPosition(current_row(), p_column), wxDefaultSpan, wxALIGN_RIGHT ); return; } wxGridBagSizer& Report::top_sizer() { assert (m_top_sizer); return *m_top_sizer; } void Report::update_for_new(OrdinaryJournal const& p_journal) { (void)p_journal; // silence compiler re. unused parameter. return; } void Report::update_for_amended(OrdinaryJournal const& p_journal) { (void)p_journal; // silence compiler re. unused parameter. return; } void Report::update_for_new(Account const& p_account) { (void)p_account; // silence compiler re. unused parameter. return; } void Report::update_for_amended(Account const& p_account) { (void)p_account; // silence compiler re. unused parameter. return; } void Report::update_for_deleted(std::vector<Entry::Id> const& p_doomed_ids) { (void)p_doomed_ids; return; } void Report::generate() { // TODO Can we factor up more shared code into here? configure_scrollbars(); do_generate(); // GetParent()->Layout(); // m_top_sizer->Fit(this); // m_top_sizer->SetSizeHints(this); FitInside(); // Layout(); return; } void Report::configure_scrollbars() { SetScrollRate(0, 10); FitInside(); return; } PhatbooksDatabaseConnection& Report::database_connection() { return m_database_connection; } } // namespace gui } // namespace phatbooks <|endoftext|>
<commit_before>#include "PROFILE.H" #include "GPU.H" #include "SPECIFIC.H" #include <LIBAPI.H> static struct SCALE scales[3] = { { 260, 0, 2 }, { 130, 1, 3 }, { 65, 2, 5 } }; char ProfileDraw; int numprof; static unsigned long EHbl; static int grid; static short divisor; static short nummarks; static short finalCount; static short currentCount; static short drawCount; static short profile_xcnt; struct COCKSUCK ProfileInfo[32]; void ProfileCallBack()//6194C, * (F) { #ifndef PAELLA drawCount = GetRCnt(RCntCNT1) / divisor; return; #endif } void ProfileInit(int scale)//61978, * (F) { #ifndef PAELLA grid = scales[scale].xgrid; nummarks = scales[scale].nummarks; divisor = scales[scale].scalefactor; EnterCriticalSection(); EHbl = OpenEvent(RCntCNT1, EvSpINT, EvMdNOINTR, NULL); EnableEvent(EHbl); SetRCnt(RCntCNT1, 64000, RCntMdINTR); DrawSyncCallback(&ProfileCallBack); ExitCriticalSection(); return; #endif } void ProfileStartCount()//61A0C, * (F) { #ifndef PAELLA ResetRCnt(RCntCNT1); StartRCnt(RCntCNT1); profile_xcnt = 25; currentCount = 0; numprof = 0; return; #endif } void ProfileReadCount()//61A48(<), * (F) { #ifndef PAELLA int lastCount = currentCount; currentCount = GetRCnt(RCntCNT1); finalCount = (currentCount - lastCount) / divisor; return; #endif } void ProfileAddOT(unsigned long* ot)//61A90, * (F) { int count = 0; if (nummarks > 0) { //loc_61AD0 while (count < nummarks) { if ((unsigned long) &db.polyptr[0] > (unsigned long)&db.polybuf_limit[0]) { return; } db.polyptr[3] = 4; db.polyptr[7] = 33; db.polyptr[4] = 50; db.polyptr[5] = 50; db.polyptr[6] = 150; *(short*) &db.polyptr[10] = 20; *(short*) &db.polyptr[14] = 20; *(short*) &db.polyptr[18] = 30; *(short*) &db.polyptr[12] = count * grid + 29; *(short*) &db.polyptr[8] = count * grid + 21; *(short*) &db.polyptr[16] = count * grid + 25; count++; *(long*) &db.polyptr[0] = *(long*) &db.polyptr[0] & 0xFF000000 | ot[0] & 0xFFFFFF; *(long*) &ot = ot[0] & 0xFF000000 | (unsigned long) db.polyptr & 0xFFFFFF; db.polyptr += 0x14; } } //loc_61B78 if (numprof > 0) { for (count = 0; count < numprof; count++) { if ((unsigned long) db.polyptr < (unsigned long) db.polybuf_limit) { ((char*) db.polyptr)[3] = 5; ((char*) db.polyptr)[7] = 0x29; ((char*) db.polyptr)[4] = ProfileInfo[count].r; ((char*) db.polyptr)[5] = ProfileInfo[count].g; ((char*) db.polyptr)[6] = ProfileInfo[count].b; ((short*) db.polyptr)[10] = 0x19; ((short*) db.polyptr)[4] = ProfileInfo[count].profile_xcnt; ((short*) db.polyptr)[7] = 0x19; ((short*) db.polyptr)[6] = ProfileInfo[count].profile_xcnt + ProfileInfo[count].finalcnt; ((short*) db.polyptr)[9] = 0x21; ((short*) db.polyptr)[8] = ProfileInfo[count].profile_xcnt; ((short*) db.polyptr)[11] = 0x21; ((short*) db.polyptr)[10] = ProfileInfo[count].profile_xcnt + ProfileInfo[count].finalcnt; ((long*) db.polyptr)[0] = (((long*) db.polyptr)[0] & 0xFF000000) | (ot[0] & 0xFFFFFF); ot[0] = (ot[0] & 0xFF000000) | ((unsigned long) db.polyptr & 0xFFFFFF); db.polyptr += 0x18; } } } } void ProfileRGB(int r, int g, int b)//61C94, * (F) { ProfileReadCount(); ProfileInfo[numprof].r = r; ProfileInfo[numprof].g = g; ProfileInfo[numprof].b = b; ProfileInfo[numprof].finalcnt = finalCount; ProfileInfo[numprof].profile_xcnt = profile_xcnt; profile_xcnt += finalCount; numprof++; return; } void ProfileAddDrawOT(unsigned long* ot)//61D1C, * { char count = 0; if (nummarks > 0) { //loc_61D5C for (count = 0; count < nummarks; count++) { if ((unsigned long) db.polyptr < (unsigned long) db.polybuf_limit) { ((char*) db.polyptr)[3] = 4; ((char*) db.polyptr)[7] = 33; ((char*) db.polyptr)[4] = 50; ((char*) db.polyptr)[5] = 50; ((char*) db.polyptr)[6] = 150; ((short*) db.polyptr)[5] = 48; ((short*) db.polyptr)[3] = 48; ((short*) db.polyptr)[9] = 39; ((short*) db.polyptr)[6] = (count * grid) + 0x1D; ((short*) db.polyptr)[4] = (count * grid) + 0x15; ((short*) db.polyptr)[8] = (count * grid) + 0x19; ((long*) db.polyptr)[0] &= 0xFF000000; ((long*) db.polyptr)[0] |= ot[0] & 0xFFFFFF; ot[0] = ot[0] & 0xFF000000 | ((long) db.polyptr & 0xFFFFFF); db.polyptr += 0x14; } else { //locret_61EE0 return; } } } //loc_61E08 if ((unsigned long) db.polyptr < (unsigned long) db.polybuf_limit) { ((char*) db.polyptr)[3] = 8; ((char*) db.polyptr)[7] = 57; ((char*) db.polyptr)[4] = 0; ((char*) db.polyptr)[5] = 200; ((char*) db.polyptr)[6] = 0; ((char*) db.polyptr)[12] = 200; ((char*) db.polyptr)[13] = 0; ((char*) db.polyptr)[14] = 0; ((char*) db.polyptr)[20] = 0; ((char*) db.polyptr)[21] = 200; ((char*) db.polyptr)[22] = 0; ((char*) db.polyptr)[28] = 200; ((char*) db.polyptr)[29] = 0; ((char*) db.polyptr)[30] = 0; ((short*) db.polyptr)[5] = 36; ((short*) db.polyptr)[9] = 36; ((short*) db.polyptr)[4] = 25; ((short*) db.polyptr)[12] = 25; ((short*) db.polyptr)[13] = 44; ((short*) db.polyptr)[17] = 44; ((short*) db.polyptr)[8] = drawCount + 25; ((short*) db.polyptr)[16] = drawCount + 25; ((long*) db.polyptr)[0] &= 0xFF000000; ((long*) db.polyptr)[0] |= ot[0] & 0xFFFFFF; ot[0] = ot[0] & 0xFF000000 | (long) db.polyptr & 0xFFFFFF; db.polyptr += 0x24; } } <commit_msg>PROFILE.C Corrections.<commit_after>#include "PROFILE.H" #include "GPU.H" #include <LIBAPI.H> static struct SCALE scales[] = { { 260, 0, 2 }, { 130, 1, 3 }, { 65, 2, 5 } }; char ProfileDraw; int numprof; static unsigned long EHbl; static int grid; static short divisor; static short nummarks; static short finalCount; static short currentCount; static short drawCount; static short profile_xcnt; struct COCKSUCK ProfileInfo[32]; void ProfileCallBack()//6194C, * (F) (*) { #ifndef PAELLA drawCount = GetRCnt(RCntCNT1) >> divisor; return; #endif } void ProfileInit(int scale)//61978, * (F) (*) { #ifndef PAELLA grid = scales[scale].xgrid; nummarks = scales[scale].nummarks; divisor = scales[scale].scalefactor; EnterCriticalSection(); EHbl = OpenEvent(RCntCNT1, EvSpINT, EvMdNOINTR, NULL); EnableEvent(EHbl); SetRCnt(RCntCNT1, 64000, RCntMdINTR); DrawSyncCallback(&ProfileCallBack); ExitCriticalSection(); return; #endif } void ProfileStartCount()//61A0C, * (F) (*) { #ifndef PAELLA ResetRCnt(RCntCNT1); StartRCnt(RCntCNT1); profile_xcnt = 25; currentCount = 0; numprof = 0; return; #endif } void ProfileReadCount()//61A48(<), * (F) (*) { #ifndef PAELLA int lastCount = currentCount; currentCount = GetRCnt(RCntCNT1); finalCount = (currentCount - lastCount) >> divisor; return; #endif } void ProfileAddOT(unsigned long* ot)//61A90, * (F) { #ifndef PAELLA int count = 0; if (nummarks > 0) { //loc_61AD0 while (count < nummarks) { if ((unsigned long) &db.polyptr[0] > (unsigned long)&db.polybuf_limit[0]) { return; } db.polyptr[3] = 4; db.polyptr[7] = 33; db.polyptr[4] = 50; db.polyptr[5] = 50; db.polyptr[6] = 150; *(short*) &db.polyptr[10] = 20; *(short*) &db.polyptr[14] = 20; *(short*) &db.polyptr[18] = 30; *(short*) &db.polyptr[12] = count * grid + 29; *(short*) &db.polyptr[8] = count * grid + 21; *(short*) &db.polyptr[16] = count * grid + 25; count++; *(long*) &db.polyptr[0] = *(long*) &db.polyptr[0] & 0xFF000000 | ot[0] & 0xFFFFFF; *(long*) &ot = ot[0] & 0xFF000000 | (unsigned long) db.polyptr & 0xFFFFFF; db.polyptr += 0x14; } } //loc_61B78 if (numprof > 0) { for (count = 0; count < numprof; count++) { if ((unsigned long) db.polyptr < (unsigned long) db.polybuf_limit) { ((char*) db.polyptr)[3] = 5; ((char*) db.polyptr)[7] = 0x29; ((char*) db.polyptr)[4] = ProfileInfo[count].r; ((char*) db.polyptr)[5] = ProfileInfo[count].g; ((char*) db.polyptr)[6] = ProfileInfo[count].b; ((short*) db.polyptr)[10] = 0x19; ((short*) db.polyptr)[4] = ProfileInfo[count].profile_xcnt; ((short*) db.polyptr)[7] = 0x19; ((short*) db.polyptr)[6] = ProfileInfo[count].profile_xcnt + ProfileInfo[count].finalcnt; ((short*) db.polyptr)[9] = 0x21; ((short*) db.polyptr)[8] = ProfileInfo[count].profile_xcnt; ((short*) db.polyptr)[11] = 0x21; ((short*) db.polyptr)[10] = ProfileInfo[count].profile_xcnt + ProfileInfo[count].finalcnt; ((long*) db.polyptr)[0] = (((long*) db.polyptr)[0] & 0xFF000000) | (ot[0] & 0xFFFFFF); ot[0] = (ot[0] & 0xFF000000) | ((unsigned long) db.polyptr & 0xFFFFFF); db.polyptr += 0x18; } } } #endif } void ProfileRGB(int r, int g, int b)//61C94, * (F) { #ifndef PAELLA ProfileReadCount(); ProfileInfo[numprof].r = r; ProfileInfo[numprof].g = g; ProfileInfo[numprof].b = b; ProfileInfo[numprof].finalcnt = finalCount; ProfileInfo[numprof].profile_xcnt = profile_xcnt; profile_xcnt += finalCount; numprof++; #endif return; } void ProfileAddDrawOT(unsigned long* ot)//61D1C, * { #ifndef PAELLA char count = 0; if (nummarks > 0) { //loc_61D5C for (count = 0; count < nummarks; count++) { if ((unsigned long) db.polyptr < (unsigned long) db.polybuf_limit) { ((char*) db.polyptr)[3] = 4; ((char*) db.polyptr)[7] = 33; ((char*) db.polyptr)[4] = 50; ((char*) db.polyptr)[5] = 50; ((char*) db.polyptr)[6] = 150; ((short*) db.polyptr)[5] = 48; ((short*) db.polyptr)[3] = 48; ((short*) db.polyptr)[9] = 39; ((short*) db.polyptr)[6] = (count * grid) + 0x1D; ((short*) db.polyptr)[4] = (count * grid) + 0x15; ((short*) db.polyptr)[8] = (count * grid) + 0x19; ((long*) db.polyptr)[0] &= 0xFF000000; ((long*) db.polyptr)[0] |= ot[0] & 0xFFFFFF; ot[0] = ot[0] & 0xFF000000 | ((long) db.polyptr & 0xFFFFFF); db.polyptr += 0x14; } else { //locret_61EE0 return; } } } //loc_61E08 if ((unsigned long) db.polyptr < (unsigned long) db.polybuf_limit) { ((char*) db.polyptr)[3] = 8; ((char*) db.polyptr)[7] = 57; ((char*) db.polyptr)[4] = 0; ((char*) db.polyptr)[5] = 200; ((char*) db.polyptr)[6] = 0; ((char*) db.polyptr)[12] = 200; ((char*) db.polyptr)[13] = 0; ((char*) db.polyptr)[14] = 0; ((char*) db.polyptr)[20] = 0; ((char*) db.polyptr)[21] = 200; ((char*) db.polyptr)[22] = 0; ((char*) db.polyptr)[28] = 200; ((char*) db.polyptr)[29] = 0; ((char*) db.polyptr)[30] = 0; ((short*) db.polyptr)[5] = 36; ((short*) db.polyptr)[9] = 36; ((short*) db.polyptr)[4] = 25; ((short*) db.polyptr)[12] = 25; ((short*) db.polyptr)[13] = 44; ((short*) db.polyptr)[17] = 44; ((short*) db.polyptr)[8] = drawCount + 25; ((short*) db.polyptr)[16] = drawCount + 25; ((long*) db.polyptr)[0] &= 0xFF000000; ((long*) db.polyptr)[0] |= ot[0] & 0xFFFFFF; ot[0] = ot[0] & 0xFF000000 | (long) db.polyptr & 0xFFFFFF; db.polyptr += 0x24; } #endif } <|endoftext|>
<commit_before>#include "SFX.H" #include "SOUND.H" #include "SPUSOUND.H" #include "SPECIFIC.H" #include <LIBSPU.H> long SPU_Play(long sample_index, short volume_left, short volume_right, short pitch, int arg_10) { long channel; sva.volume.left = volume_left; sva.volume.right = volume_right; sva.pitch = pitch >> 6; sva.addr = LadwSampleAddr[sample_index]; if (sample_index < LnSamplesLoaded) { channel = SPU_AllocChannel(); if (channel >= 0) { LabSampleType[channel] = arg_10; sva.mask = 0x93; sva.voice = 1 << channel; SpuSetKeyOnWithAttr(&sva); return channel; } else { return -1; } } else { return -2; } } int SPU_UpdateStatus()//915FC, 93640 (F) { int i; char status[MAX_SOUND_SLOTS]; SpuGetAllKeysStatus(&status[0]); for (i = 0; i < MAX_SOUND_SLOTS; i++) { if (status[i] - 1 > 1 && LabSampleType[i] != 0) { SPU_FreeChannel(i); } } return LnFreeChannels; } long SPU_AllocChannel()//915B0, 935F4 (F) { if (LnFreeChannels == 0) { if (SPU_UpdateStatus() == 0) { return -1; } } //loc_915DC return LabFreeChannel[--LnFreeChannels]; } void SPU_StopAll() { UNIMPLEMENTED(); } void SPU_FreeChannel(int channel_index)//91668, 936AC (F) { LabSampleType[channel_index] = 0; LabFreeChannel[LnFreeChannels++] = channel_index; } void S_SoundStopSample(int handle) { UNIMPLEMENTED(); } void S_SetReverbType(int reverb) { UNIMPLEMENTED(); } void S_SoundStopAllSamples() { UNIMPLEMENTED(); } void SOUND_EndScene() { UNIMPLEMENTED(); } void SOUND_Stop() { UNIMPLEMENTED(); } int PlaySample(int a0, int volume_left, int volume_right, int a3, int arg_10, int t1, int t2)//914C8(<), 9350C(<) { //CalcVolumes_ASM();//prolly modifies t1 and t2 SPU_Play(t1, volume_left, volume_right, t2, arg_10); UNIMPLEMENTED(); return 0;//? } int S_SoundPlaySampleLooped(int a0, int a1, int a2, int a3, int arg_10) { if (GtSFXEnabled) { return PlaySample(arg_10, a1, a2, a3, 2, a0, a2); } else { return -3; } } int S_SoundSampleIsPlaying(int handle)//916F8(<), 9373C(<) { char status; if (GtSFXEnabled == 0) { return 0; } status = (char)(SpuGetKeyStatus(1 << handle) -1); if (status < 2 || LabSampleType[handle] == 0) { return LabSampleType[handle]; } SPU_FreeChannel(handle); return 0; } int S_SoundPlaySample(int a0, int a1, int a2, int a3, int arg_10)//91480(<), ? { if (GtSFXEnabled) { int t1 = a0; int t2 = a1; a0 = arg_10; PlaySample(a0, a1, a2, a3, 1, t1, t2); } else { return -3; } }<commit_msg>[Specific-PSXPC_N] Implement SOUND_EndScene.<commit_after>#include "SFX.H" #include "SOUND.H" #include "SPUSOUND.H" #include "SPECIFIC.H" #include <LIBSPU.H> long SPU_Play(long sample_index, short volume_left, short volume_right, short pitch, int arg_10) { long channel; sva.volume.left = volume_left; sva.volume.right = volume_right; sva.pitch = pitch >> 6; sva.addr = LadwSampleAddr[sample_index]; if (sample_index < LnSamplesLoaded) { channel = SPU_AllocChannel(); if (channel >= 0) { LabSampleType[channel] = arg_10; sva.mask = 0x93; sva.voice = 1 << channel; SpuSetKeyOnWithAttr(&sva); return channel; } else { return -1; } } else { return -2; } } int SPU_UpdateStatus()//915FC, 93640 (F) { int i; char status[MAX_SOUND_SLOTS]; SpuGetAllKeysStatus(&status[0]); for (i = 0; i < MAX_SOUND_SLOTS; i++) { if (status[i] - 1 > 1 && LabSampleType[i] != 0) { SPU_FreeChannel(i); } } return LnFreeChannels; } long SPU_AllocChannel()//915B0, 935F4 (F) { if (LnFreeChannels == 0) { if (SPU_UpdateStatus() == 0) { return -1; } } //loc_915DC return LabFreeChannel[--LnFreeChannels]; } void SPU_StopAll() { UNIMPLEMENTED(); } void SPU_FreeChannel(int channel_index)//91668, 936AC (F) { LabSampleType[channel_index] = 0; LabFreeChannel[LnFreeChannels++] = channel_index; } void S_SoundStopSample(int handle) { UNIMPLEMENTED(); } void S_SetReverbType(int reverb) { UNIMPLEMENTED(); } void S_SoundStopAllSamples() { UNIMPLEMENTED(); } void SOUND_EndScene() { //v0 = sound_active if (sound_active != 0) { //s0 = 0; //s2 = sample_infos //s1 = &LaSlot[0] //loc_91DAC for (int i = 0; i < MAX_SOUND_SLOTS; i++) { //v0 = LaSlot[0].nSampleInfo if (LaSlot[i].nSampleInfo >= 0) { //v0 = sample_infos[LaSlot[0].nSampleInfo].flags if ((sample_infos[LaSlot[i].nSampleInfo].flags & 0x3) == 3) { //a2 = LaSlot[0].nVolume //a0 = s0 if (LaSlot[i].nVolume != 0) { S_SoundSetPanAndVolume(i, LaSlot[i].nPan, LaSlot[i].nVolume & 0xFFFF, LaSlot[i].distance); S_SoundSetPitch(i, LaSlot[i].nPitch); LaSlot[i].nVolume = 0; } else { //loc_91E08 S_SoundStopSample(i); LaSlot[i].nSampleInfo = -1; } } else { //loc_91E1C if (!S_SoundSampleIsPlaying(i)) { S_SoundStopSample(i); LaSlot[i].nSampleInfo = -1; } else { //a0 = LaSlot[0].pos.x | LaSlot[0].pos.y |LaSlot[0].pos.z //a1 = //a2 = if ((LaSlot[i].pos.x | LaSlot[i].pos.y | LaSlot[i].pos.z) != 0) { GetPanVolume(&LaSlot[i]); S_SoundSetPanAndVolume(i, LaSlot[i].nPan, LaSlot[i].nVolume, LaSlot[i].distance); } //loc_91E64 } } }//loc_91E64 } }//loc_91E74 } void SOUND_Stop() { UNIMPLEMENTED(); } int PlaySample(int a0, int volume_left, int volume_right, int a3, int arg_10, int t1, int t2)//914C8(<), 9350C(<) { //CalcVolumes_ASM();//prolly modifies t1 and t2 SPU_Play(t1, volume_left, volume_right, t2, arg_10); UNIMPLEMENTED(); return 0;//? } int S_SoundPlaySampleLooped(int a0, int a1, int a2, int a3, int arg_10) { if (GtSFXEnabled) { return PlaySample(arg_10, a1, a2, a3, 2, a0, a2); } else { return -3; } } int S_SoundSampleIsPlaying(int handle)//916F8(<), 9373C(<) { char status; if (GtSFXEnabled == 0) { return 0; } status = (char)(SpuGetKeyStatus(1 << handle) -1); if (status < 2 || LabSampleType[handle] == 0) { return LabSampleType[handle]; } SPU_FreeChannel(handle); return 0; } int S_SoundPlaySample(int a0, int a1, int a2, int a3, int arg_10)//91480(<), ? { if (GtSFXEnabled) { int t1 = a0; int t2 = a1; a0 = arg_10; PlaySample(a0, a1, a2, a3, 1, t1, t2); } else { return -3; } } void S_SoundSetPitch(int handle, int nPitch) { UNIMPLEMENTED(); } int S_SoundSetPanAndVolume(int nhandle, int nPan, int nVolume, int distance) { UNIMPLEMENTED(); return 0; } void GetPanVolume(struct SoundSlot* slot) { UNIMPLEMENTED(); }<|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #pragma once #include <vector> #include <cstring> #include <stdint.h> #include <msgpack.hpp> #include <pficommon/lang/shared_ptr.h> namespace jubatus { namespace common { namespace mprpc { class byte_buffer { public: byte_buffer() : ptr_(NULL) , size_(0) { } byte_buffer(size_t size) : buf_(new std::vector<char>(size)) , ptr_(&(*buf_)[0]) , size_(size) { } byte_buffer(const void *ptr, size_t size) : buf_(new std::vector<char>(static_cast<const char*>(ptr), static_cast<const char*>(ptr) + size)) , ptr_(&(*buf_)[0]) , size_(size) { } ~byte_buffer() {} void assign(const void* ptr, size_t size) { if (!buf_) buf_.reset(new std::vector<char>(size)); ptr_ = &(*buf_)[0]; size_ = size; std::memcpy(&(*buf_)[0], ptr, size); } char* ptr() const { return ptr_; } size_t size() const { return size_; } private: pfi::lang::shared_ptr<std::vector<char> > buf_; char* ptr_; size_t size_; }; } // mprpc } // common } // jubatus namespace msgpack { inline jubatus::common::mprpc::byte_buffer& operator>> (object o, jubatus::common::mprpc::byte_buffer& b) { if (o.type != type::RAW) throw type_error(); b.assign(o.via.raw.ptr, o.via.raw.size); return b; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, const jubatus::common::mprpc::byte_buffer& b) { o.pack_raw(b.size()); o.pack_raw_body(b.ptr(), b.size()); return o; } inline void operator<< (object::with_zone& o, const jubatus::common::mprpc::byte_buffer& b) { o.type = type::RAW; char* ptr = static_cast<char*>(o.zone->malloc(b.size())); o.via.raw.ptr = ptr; o.via.raw.size = static_cast<uint32_t>(b.size()); std::memcpy(ptr, b.ptr(), b.size()); } inline void operator<< (object& o, const jubatus::common::mprpc::byte_buffer& b) { o.type = type::RAW; o.via.raw.ptr = b.ptr(); o.via.raw.size = static_cast<uint32_t>(b.size()); } } // msgpack <commit_msg>Fix byte_buffer bug: refs #168<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #pragma once #include <vector> #include <cstring> #include <stdint.h> #include <msgpack.hpp> #include <pficommon/lang/shared_ptr.h> namespace jubatus { namespace common { namespace mprpc { class byte_buffer { public: byte_buffer() { } byte_buffer(size_t size) : buf_(new std::vector<char>(size)) { } byte_buffer(const void *ptr, size_t size) : buf_(new std::vector<char>(static_cast<const char*>(ptr), static_cast<const char*>(ptr) + size)) { } byte_buffer(const byte_buffer& b) : buf_(b.buf_) { } ~byte_buffer() {} void assign(const void* ptr, size_t size) { if (buf_) { buf_->resize(size); std::memcpy(&(*buf_)[0], ptr, size); } else { buf_.reset(new std::vector<char>(static_cast<const char*>(ptr), static_cast<const char*>(ptr) + size)); } } char* ptr() const { if (buf_) return &(*buf_)[0]; else return NULL; } size_t size() const { if (buf_) return buf_->size(); else return 0; } private: pfi::lang::shared_ptr<std::vector<char> > buf_; }; } // mprpc } // common } // jubatus namespace msgpack { inline jubatus::common::mprpc::byte_buffer& operator>> (object o, jubatus::common::mprpc::byte_buffer& b) { if (o.type != type::RAW) throw type_error(); b.assign(o.via.raw.ptr, o.via.raw.size); return b; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, const jubatus::common::mprpc::byte_buffer& b) { o.pack_raw(b.size()); o.pack_raw_body(b.ptr(), b.size()); return o; } inline void operator<< (object::with_zone& o, const jubatus::common::mprpc::byte_buffer& b) { o.type = type::RAW; char* ptr = static_cast<char*>(o.zone->malloc(b.size())); o.via.raw.ptr = ptr; o.via.raw.size = static_cast<uint32_t>(b.size()); std::memcpy(ptr, b.ptr(), b.size()); } inline void operator<< (object& o, const jubatus::common::mprpc::byte_buffer& b) { o.type = type::RAW; o.via.raw.ptr = b.ptr(); o.via.raw.size = static_cast<uint32_t>(b.size()); } } // msgpack <|endoftext|>
<commit_before>// This file is part of the ustl library, an STL implementation. // // Copyright (C) 2005 by Mike Sharov <msharov@users.sourceforge.net> // This file is free software, distributed under the MIT License. // // memblock.cc // // Allocated memory block. // #include "mistream.h" #include "memblock.h" #include "ualgo.h" #include "umemory.h" #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> namespace ustl { /// Allocates 0 bytes for the internal block. memblock::memblock (void) : memlink (), m_Capacity (0) { } /// Allocates \p n bytes for the internal block. memblock::memblock (size_type n) : memlink (), m_Capacity (0) { resize (n); } /// links to \p p, \p n. Data can not be modified and will not be freed. memblock::memblock (const void* p, size_type n) : memlink (), m_Capacity (0) { assign (p, n); } /// Links to what \p b is linked to. memblock::memblock (const cmemlink& b) : memlink (), m_Capacity (0) { assign (b); } /// Links to what \p b is linked to. memblock::memblock (const memlink& b) : memlink (), m_Capacity (0) { assign (b); } /// Links to what \p b is linked to. memblock::memblock (const memblock& b) : memlink (), m_Capacity (0) { assign (b); } /// Frees internal data, if appropriate /// Only if the block was allocated using resize, or linked to using Manage, /// will it be freed. Also, Derived classes should call DestructBlock from /// their destructor, because upstream virtual functions are unavailable at /// this point and will not be called automatically. /// memblock::~memblock (void) { if (!is_linked()) deallocate(); } /// resizes the block to \p newSize bytes, reallocating if necessary. void memblock::resize (size_type newSize, bool bExact) { if (m_Capacity < newSize + minimumFreeCapacity()) reserve (newSize, bExact); memlink::resize (newSize); } /// Frees internal data. void memblock::deallocate (void) throw() { if (m_Capacity) { assert (cdata() && "Internal error: space allocated, but the pointer is NULL"); assert (data() && "Internal error: read-only block is marked as allocated space"); free (data()); } memblock::unlink(); } /// Assumes control of the memory block \p p of size \p n. /// The block assigned using this function will be freed in the destructor. void memblock::manage (void* p, size_type n) { assert (p || !n); assert (!data() || !m_Capacity); // Can't link to an allocated block. link (p, n); m_Capacity = n; } /// Copies data from \p p, \p n. void memblock::assign (const void* p, size_type n) { assert ((p != (const void*) cdata() || size() == n) && "Self-assignment can not resize"); resize (n); copy (p, n); } /// \brief Reallocates internal block to hold at least \p newSize bytes. /// /// Additional memory may be allocated, but for efficiency it is a very /// good idea to call reserve before doing byte-by-byte edit operations. /// The block size as returned by size() is not altered. reserve will not /// reduce allocated memory. If you think you are wasting space, call /// deallocate and start over. To avoid wasting space, use the block for /// only one purpose, and try to get that purpose to use similar amounts /// of memory on each iteration. /// void memblock::reserve (size_type newSize, bool bExact) { if ((newSize += minimumFreeCapacity()) <= m_Capacity) return; void* oldBlock (is_linked() ? NULL : data()); if (!bExact) newSize = Align (newSize, c_PageSize); pointer newBlock = (pointer) realloc (oldBlock, newSize); if (!newBlock) throw bad_alloc (newSize); if (!oldBlock && cdata()) copy_n (cdata(), min (size() + 1, newSize), newBlock); link (newBlock, size()); m_Capacity = newSize; } /// \warning Do not use or override this! It exists only for implementing #string memblock::size_type memblock::minimumFreeCapacity (void) const { return (0); } /// Swaps the contents with \p l void memblock::swap (memblock& l) { memlink::swap (l); ::ustl::swap (m_Capacity, l.m_Capacity); } /// Shifts the data in the linked block from \p start to \p start + \p n. memblock::iterator memblock::insert (iterator start, size_type n) { const uoff_t ip = start - begin(); assert (ip <= size()); resize (size() + n, false); memlink::insert (begin() + ip, n); return (begin() + ip); } /// Shifts the data in the linked block from \p start + \p n to \p start. memblock::iterator memblock::erase (iterator start, size_type n) { const uoff_t ep = start - begin(); assert (ep + n <= size()); memlink::erase (start, n); memlink::resize (size() - n); return (begin() + ep); } /// Unlinks object. void memblock::unlink (void) { memlink::unlink(); m_Capacity = 0; } /// Reads the object from stream \p s void memblock::read (istream& is) { size_type n; is >> n; if (is.remaining() < n) throw stream_bounds_exception ("read", "ustl::memblock", is.pos(), n, is.remaining()); resize (n); is.read (data(), writable_size()); is.align(); } /// Reads the entire file \p "filename". void memblock::read_file (const char* filename) { struct stat st; if (stat (filename, &st)) throw file_exception ("stat", filename); resize (st.st_size); int fd = open (filename, O_RDONLY); if (fd < 0) throw file_exception ("open", filename); const size_type btr = writable_size(); ssize_t br = ::read (fd, data(), btr); if (size_type(br) != btr) { close (fd); throw file_exception ("read", filename); } close (fd); } } // namespace ustl <commit_msg>Removed redundant close<commit_after>// This file is part of the ustl library, an STL implementation. // // Copyright (C) 2005 by Mike Sharov <msharov@users.sourceforge.net> // This file is free software, distributed under the MIT License. // // memblock.cc // // Allocated memory block. // #include "mistream.h" #include "memblock.h" #include "ualgo.h" #include "umemory.h" #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> namespace ustl { /// Allocates 0 bytes for the internal block. memblock::memblock (void) : memlink (), m_Capacity (0) { } /// Allocates \p n bytes for the internal block. memblock::memblock (size_type n) : memlink (), m_Capacity (0) { resize (n); } /// links to \p p, \p n. Data can not be modified and will not be freed. memblock::memblock (const void* p, size_type n) : memlink (), m_Capacity (0) { assign (p, n); } /// Links to what \p b is linked to. memblock::memblock (const cmemlink& b) : memlink (), m_Capacity (0) { assign (b); } /// Links to what \p b is linked to. memblock::memblock (const memlink& b) : memlink (), m_Capacity (0) { assign (b); } /// Links to what \p b is linked to. memblock::memblock (const memblock& b) : memlink (), m_Capacity (0) { assign (b); } /// Frees internal data, if appropriate /// Only if the block was allocated using resize, or linked to using Manage, /// will it be freed. Also, Derived classes should call DestructBlock from /// their destructor, because upstream virtual functions are unavailable at /// this point and will not be called automatically. /// memblock::~memblock (void) { if (!is_linked()) deallocate(); } /// resizes the block to \p newSize bytes, reallocating if necessary. void memblock::resize (size_type newSize, bool bExact) { if (m_Capacity < newSize + minimumFreeCapacity()) reserve (newSize, bExact); memlink::resize (newSize); } /// Frees internal data. void memblock::deallocate (void) throw() { if (m_Capacity) { assert (cdata() && "Internal error: space allocated, but the pointer is NULL"); assert (data() && "Internal error: read-only block is marked as allocated space"); free (data()); } memblock::unlink(); } /// Assumes control of the memory block \p p of size \p n. /// The block assigned using this function will be freed in the destructor. void memblock::manage (void* p, size_type n) { assert (p || !n); assert (!data() || !m_Capacity); // Can't link to an allocated block. link (p, n); m_Capacity = n; } /// Copies data from \p p, \p n. void memblock::assign (const void* p, size_type n) { assert ((p != (const void*) cdata() || size() == n) && "Self-assignment can not resize"); resize (n); copy (p, n); } /// \brief Reallocates internal block to hold at least \p newSize bytes. /// /// Additional memory may be allocated, but for efficiency it is a very /// good idea to call reserve before doing byte-by-byte edit operations. /// The block size as returned by size() is not altered. reserve will not /// reduce allocated memory. If you think you are wasting space, call /// deallocate and start over. To avoid wasting space, use the block for /// only one purpose, and try to get that purpose to use similar amounts /// of memory on each iteration. /// void memblock::reserve (size_type newSize, bool bExact) { if ((newSize += minimumFreeCapacity()) <= m_Capacity) return; void* oldBlock (is_linked() ? NULL : data()); if (!bExact) newSize = Align (newSize, c_PageSize); pointer newBlock = (pointer) realloc (oldBlock, newSize); if (!newBlock) throw bad_alloc (newSize); if (!oldBlock && cdata()) copy_n (cdata(), min (size() + 1, newSize), newBlock); link (newBlock, size()); m_Capacity = newSize; } /// \warning Do not use or override this! It exists only for implementing #string memblock::size_type memblock::minimumFreeCapacity (void) const { return (0); } /// Swaps the contents with \p l void memblock::swap (memblock& l) { memlink::swap (l); ::ustl::swap (m_Capacity, l.m_Capacity); } /// Shifts the data in the linked block from \p start to \p start + \p n. memblock::iterator memblock::insert (iterator start, size_type n) { const uoff_t ip = start - begin(); assert (ip <= size()); resize (size() + n, false); memlink::insert (begin() + ip, n); return (begin() + ip); } /// Shifts the data in the linked block from \p start + \p n to \p start. memblock::iterator memblock::erase (iterator start, size_type n) { const uoff_t ep = start - begin(); assert (ep + n <= size()); memlink::erase (start, n); memlink::resize (size() - n); return (begin() + ep); } /// Unlinks object. void memblock::unlink (void) { memlink::unlink(); m_Capacity = 0; } /// Reads the object from stream \p s void memblock::read (istream& is) { size_type n; is >> n; if (is.remaining() < n) throw stream_bounds_exception ("read", "ustl::memblock", is.pos(), n, is.remaining()); resize (n); is.read (data(), writable_size()); is.align(); } /// Reads the entire file \p "filename". void memblock::read_file (const char* filename) { struct stat st; if (stat (filename, &st)) throw file_exception ("stat", filename); resize (st.st_size); int fd = open (filename, O_RDONLY); if (fd < 0) throw file_exception ("open", filename); const size_type btr = writable_size(); ssize_t br = ::read (fd, data(), btr); close (fd); if (size_type(br) != btr) throw file_exception ("read", filename); } } // namespace ustl <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <string> #include <string> #include <set> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) #define PARAMDIM 5 namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } void writetofile (const char * fname, int cidx, const arma::mat & mat) { if (cidx < (int) mat.n_cols) { std::ofstream myfile(fname); for (int i=0; i<(int)mat.n_rows; i++) myfile << i << " " << mat(i,cidx) << std::endl; myfile.close(); } } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go arma::mat paraminp = arma::zeros<arma::mat>(num_of_ent,PARAMDIM); arma::mat coordinp = arma::zeros<arma::mat>(num_of_ent,3*COORDIM); arma::mat layer, ladder, module; layer.set_size(num_of_ent,COORDIM); ladder.set_size(num_of_ent,COORDIM); module.set_size(num_of_ent,COORDIM); // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; std::set<std::string> subsectors; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif std::ostringstream oss; oss << std::setfill('0'); for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coordinp(i, j*3) >> coordinp(i, j*3+1) >> coordinp(i, j*3+2) >> a >> b >> c; layer(i, j) = a; ladder(i, j) = b; module(i, j) = c; oss << std::setw(2) << layer(i, j); oss << std::setw(2) << ladder(i, j); if (j != COORDIM-1) oss<<"-"; subsectors.insert(oss.str()); } mytfp >> paraminp(i,0) >> paraminp(i,1) >> paraminp(i,2) >> paraminp(i,3) >> paraminp(i,4); } mytfp.close(); std::cout << "We found " << subsectors.size() << " subsector " << std::endl; for (int i = 0; i < PARAMDIM; ++i) { switch (i) { case 0: std::cout << i+1 << " q * pt" << std::endl; break; case 1: std::cout << i+1 << " phi" << std::endl; break; case 2: std::cout << i+1 << " d0" << std::endl; break; case 3: std::cout << i+1 << " eta" << std::endl; break; case 4: std::cout << i+1 << " z0" << std::endl; break; }; std::ostringstream fname; fname << "p" << i+1 << ".txt"; writetofile(fname.str().c_str(), i, paraminp); } #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coordinp(i, j*3) << " " << coordinp(i, j*3+1) << " " << coordinp(i, j*3+2) << " " << ladder(i, j) << std::endl; } std::cout << paraminp(i,0) << " " << paraminp(i,1) << " " << paraminp(i,2) << " " << paraminp(i,3) << " " << paraminp(i,4) << std::endl; } #endif arma::mat param; arma::mat coord; int k = 0; // to be used to select inly a ladder .... for (int i = 0; i < num_of_ent; ++i) { bool todo = false; //if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) && // (ladder(i, 2) == 2)) if (paraminp(i,0) > 0.0) todo = true; if (todo) k++; } param.set_size(k,PARAMDIM); coord.set_size(k,3*COORDIM); k = 0; // to be used to select inly a ladder .... for (int i = 0; i < num_of_ent; ++i) { bool todo = false; //if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) && // (ladder(i, 2) == 2)) if (paraminp(i,0) > 0.0) todo = true; if (todo) { for (int j = 0; j < 3*COORDIM; ++j) coord(k,j) = coordinp(i,j); for (int j = 0; j < PARAMDIM; ++j) param(k,j) = paraminp(i,j); k++; } } num_of_ent = k; std::cout << "We got " << num_of_ent << " tracks " << std::endl; // projection arma::mat score; // ordered arma::vec eigval; // by row or by column ? arma::mat eigvec; arma::princomp(eigvec, score, eigval, coord); //std::cout << score.n_rows << " " << score.n_cols << std::endl; std::ofstream myfilesc("scoreplot.txt"); for (int i=0; i<(int)score.n_rows; ++i) { myfilesc << score(i,0) << " " << score(i,1) << " " << score(i,2) << std::endl; double mainr = 0.0e0; for (int j=1; j<5; ++j) mainr += score(i,j) * score(i,j); double residue = 0.0; for (int j=5; j<3*COORDIM; ++j) residue += score(i,j) * score(i,j); std::cout << "Track " << i+1 << " residue " << residue << " mainr " << mainr << std::endl; } myfilesc.close(); double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); std::cout << "Eigenvalues: " << std::endl; double totvar = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) { if (i < PARAMDIM) totvar += 100.0e0*(eigval(i)/totval); std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << "% value: " << eigval(i) << std::endl; } std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl; arma::mat v = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); v = arma::cov(coord); #ifdef DEBUG /* correlation matrix ricorda su dati standardizzati coincide con la matrice * di covarianza : * z = x -<x> / sigma */ arma::mat corr = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) corr(i,j) = v(i,j) / sqrt(v(i,i)*v(j,j)); std::cout << "Correlation matrix: " << std::endl; std::cout << corr; #endif arma::mat vi = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); vi = v.i(); #ifdef DEBUG std::cout << "inverse by cov matrix: " << std::endl; std::cout << v * vi ; #endif // and so on ... arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM); arma::mat paramm = arma::zeros<arma::mat>(PARAMDIM); arma::mat coordm = arma::zeros<arma::mat>(3*COORDIM); double sum = 1.0e0; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm(i) += (coord(l,i)-coordm(i))/sum; for (int i=0; i<PARAMDIM; ++i) paramm(i) += (param(l,i)-paramm(i))/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<PARAMDIM; ++j) { hcap(i,j) += ((coord(l,i) - coordm(i))* (param(l,j) - paramm(j))- (sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0); } } } arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM); for (int i=0; i<PARAMDIM; ++i) for (int l=0; l<(3*COORDIM); ++l) for (int m=0; m<(3*COORDIM); ++m) cmtx(i,l) += vi(l,m) * hcap (m,i); #ifdef DEBUG std::cout << "C matrix: " << std::endl; std::cout << cmtx; #endif arma::mat q = arma::zeros<arma::mat>(PARAMDIM); for (int i=0; i<PARAMDIM; ++i) { q(i) = paramm(i); for (int l=0; l<(3*COORDIM); ++l) q(i) -= cmtx(i,l)*coordm[l]; } #ifdef DEBUG std::cout << "Q vector: " << std::endl; for (int i=0; i<PARAMDIM; ++i) std::cout << q(i) << std::endl; #endif //test back arma::running_stat<double> chi2stats; arma::running_stat<double> pc[PARAMDIM]; for (int l=0; l<num_of_ent; ++l) { std::cout << "Track: " << l+1 << std::endl; for (int i=0; i<PARAMDIM; ++i) { double p = q(i); for (int k=0; k<(3*COORDIM); ++k) p += cmtx(i,k)*coord(l,k); std::cout << " computed " << p << " real " << param(l,i) << std::endl; pc[i](fabs(p - param(l,i))/(fabs(p + param(l,i))/2.0)); } /* chi**2 */ double chi2 = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) chi2 += (coord(l,i) - coordm(i)) * vi(i, j) * (coord(l,j) - coordm(j)); std::cout << " chi2: " << chi2 << std::endl; chi2stats(chi2); } std::cout << "chi2 mean = " << chi2stats.mean() << std::endl; std::cout << "chi2 stdev = " << chi2stats.stddev() << std::endl; std::cout << "chi2 min = " << chi2stats.min() << std::endl; std::cout << "chi2 max = " << chi2stats.max() << std::endl; for (int i=0; i<PARAMDIM; ++i) { std::cout << 100.0*pc[i].mean() << " " << 100.0*pc[i].stddev() << std::endl; arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param(l,i)); std::cout << " mean = " << stats.mean() << std::endl; std::cout << " stdev = " << stats.stddev() << std::endl; std::cout << " min = " << stats.min() << std::endl; std::cout << " max = " << stats.max() << std::endl; } return 0; } <commit_msg>count and list subsectors<commit_after>#include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <string> #include <string> #include <map> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) #define PARAMDIM 5 namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } void writetofile (const char * fname, int cidx, const arma::mat & mat) { if (cidx < (int) mat.n_cols) { std::ofstream myfile(fname); for (int i=0; i<(int)mat.n_rows; i++) myfile << i << " " << mat(i,cidx) << std::endl; myfile.close(); } } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go arma::mat paraminp = arma::zeros<arma::mat>(num_of_ent,PARAMDIM); arma::mat coordinp = arma::zeros<arma::mat>(num_of_ent,3*COORDIM); arma::mat layer, ladder, module; layer.set_size(num_of_ent,COORDIM); ladder.set_size(num_of_ent,COORDIM); module.set_size(num_of_ent,COORDIM); // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; std::map<std::string, int> subsectors; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif std::ostringstream oss; oss << std::setfill('0'); for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coordinp(i, j*3) >> coordinp(i, j*3+1) >> coordinp(i, j*3+2) >> a >> b >> c; layer(i, j) = a; ladder(i, j) = b; module(i, j) = c; oss << std::setw(2) << layer(i, j); oss << std::setw(2) << ladder(i, j); if (j != COORDIM-1) oss<<"-"; } std::map<std::string, int>::iterator it = subsectors.find(oss.str()); if (it == subsectors.end()) subsectors[oss.str()] = 1; else subsectors[oss.str()] += 1; mytfp >> paraminp(i,0) >> paraminp(i,1) >> paraminp(i,2) >> paraminp(i,3) >> paraminp(i,4); } mytfp.close(); std::cout << "We found " << subsectors.size() << " subsectors " << std::endl; std::map<std::string, int>::iterator it = subsectors.begin(); for (; it != subsectors.end(); ++it) { std::cout << "Subsector " << it->first << " has " << it->second << " tracks " << std::endl; } for (int i = 0; i < PARAMDIM; ++i) { switch (i) { case 0: std::cout << i+1 << " q * pt" << std::endl; break; case 1: std::cout << i+1 << " phi" << std::endl; break; case 2: std::cout << i+1 << " d0" << std::endl; break; case 3: std::cout << i+1 << " eta" << std::endl; break; case 4: std::cout << i+1 << " z0" << std::endl; break; }; std::ostringstream fname; fname << "p" << i+1 << ".txt"; writetofile(fname.str().c_str(), i, paraminp); } #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coordinp(i, j*3) << " " << coordinp(i, j*3+1) << " " << coordinp(i, j*3+2) << " " << ladder(i, j) << std::endl; } std::cout << paraminp(i,0) << " " << paraminp(i,1) << " " << paraminp(i,2) << " " << paraminp(i,3) << " " << paraminp(i,4) << std::endl; } #endif arma::mat param; arma::mat coord; int k = 0; // to be used to select inly a ladder .... for (int i = 0; i < num_of_ent; ++i) { bool todo = false; //if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) && // (ladder(i, 2) == 2)) if (paraminp(i,0) > 0.0) todo = true; if (todo) k++; } param.set_size(k,PARAMDIM); coord.set_size(k,3*COORDIM); k = 0; // to be used to select inly a ladder .... for (int i = 0; i < num_of_ent; ++i) { bool todo = false; //if ((ladder(i, 0) == 0) && (ladder(i, 1) == 1) && // (ladder(i, 2) == 2)) if (paraminp(i,0) > 0.0) todo = true; if (todo) { for (int j = 0; j < 3*COORDIM; ++j) coord(k,j) = coordinp(i,j); for (int j = 0; j < PARAMDIM; ++j) param(k,j) = paraminp(i,j); k++; } } num_of_ent = k; std::cout << "We got " << num_of_ent << " tracks " << std::endl; // projection arma::mat score; // ordered arma::vec eigval; // by row or by column ? arma::mat eigvec; arma::princomp(eigvec, score, eigval, coord); //std::cout << score.n_rows << " " << score.n_cols << std::endl; std::ofstream myfilesc("scoreplot.txt"); for (int i=0; i<(int)score.n_rows; ++i) { myfilesc << score(i,0) << " " << score(i,1) << " " << score(i,2) << std::endl; double mainr = 0.0e0; for (int j=1; j<5; ++j) mainr += score(i,j) * score(i,j); double residue = 0.0; for (int j=5; j<3*COORDIM; ++j) residue += score(i,j) * score(i,j); std::cout << "Track " << i+1 << " residue " << residue << " mainr " << mainr << std::endl; } myfilesc.close(); double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); std::cout << "Eigenvalues: " << std::endl; double totvar = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) { if (i < PARAMDIM) totvar += 100.0e0*(eigval(i)/totval); std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << "% value: " << eigval(i) << std::endl; } std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl; arma::mat v = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); v = arma::cov(coord); #ifdef DEBUG /* correlation matrix ricorda su dati standardizzati coincide con la matrice * di covarianza : * z = x -<x> / sigma */ arma::mat corr = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) corr(i,j) = v(i,j) / sqrt(v(i,i)*v(j,j)); std::cout << "Correlation matrix: " << std::endl; std::cout << corr; #endif arma::mat vi = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); vi = v.i(); #ifdef DEBUG std::cout << "inverse by cov matrix: " << std::endl; std::cout << v * vi ; #endif // and so on ... arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM); arma::mat paramm = arma::zeros<arma::mat>(PARAMDIM); arma::mat coordm = arma::zeros<arma::mat>(3*COORDIM); double sum = 1.0e0; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm(i) += (coord(l,i)-coordm(i))/sum; for (int i=0; i<PARAMDIM; ++i) paramm(i) += (param(l,i)-paramm(i))/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<PARAMDIM; ++j) { hcap(i,j) += ((coord(l,i) - coordm(i))* (param(l,j) - paramm(j))- (sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0); } } } arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM); for (int i=0; i<PARAMDIM; ++i) for (int l=0; l<(3*COORDIM); ++l) for (int m=0; m<(3*COORDIM); ++m) cmtx(i,l) += vi(l,m) * hcap (m,i); #ifdef DEBUG std::cout << "C matrix: " << std::endl; std::cout << cmtx; #endif arma::mat q = arma::zeros<arma::mat>(PARAMDIM); for (int i=0; i<PARAMDIM; ++i) { q(i) = paramm(i); for (int l=0; l<(3*COORDIM); ++l) q(i) -= cmtx(i,l)*coordm[l]; } #ifdef DEBUG std::cout << "Q vector: " << std::endl; for (int i=0; i<PARAMDIM; ++i) std::cout << q(i) << std::endl; #endif //test back arma::running_stat<double> chi2stats; arma::running_stat<double> pc[PARAMDIM]; for (int l=0; l<num_of_ent; ++l) { std::cout << "Track: " << l+1 << std::endl; for (int i=0; i<PARAMDIM; ++i) { double p = q(i); for (int k=0; k<(3*COORDIM); ++k) p += cmtx(i,k)*coord(l,k); std::cout << " computed " << p << " real " << param(l,i) << std::endl; pc[i](fabs(p - param(l,i))/(fabs(p + param(l,i))/2.0)); } /* chi**2 */ double chi2 = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) chi2 += (coord(l,i) - coordm(i)) * vi(i, j) * (coord(l,j) - coordm(j)); std::cout << " chi2: " << chi2 << std::endl; chi2stats(chi2); } std::cout << "chi2 mean = " << chi2stats.mean() << std::endl; std::cout << "chi2 stdev = " << chi2stats.stddev() << std::endl; std::cout << "chi2 min = " << chi2stats.min() << std::endl; std::cout << "chi2 max = " << chi2stats.max() << std::endl; for (int i=0; i<PARAMDIM; ++i) { std::cout << 100.0*pc[i].mean() << " " << 100.0*pc[i].stddev() << std::endl; arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param(l,i)); std::cout << " mean = " << stats.mean() << std::endl; std::cout << " stdev = " << stats.stddev() << std::endl; std::cout << " min = " << stats.min() << std::endl; std::cout << " max = " << stats.max() << std::endl; } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdlib.h> #include "base/logging.h" #include "gpu/command_buffer/service/command_buffer_service.h" #include "gpu/command_buffer/service/gpu_processor.h" #include "gpu/np_utils/np_utils.h" #include "gpu/gpu_plugin/gpu_plugin_object.h" using ::base::SharedMemory; using command_buffer::CommandBuffer; using command_buffer::CommandBufferService; using command_buffer::GPUProcessor; using np_utils::NPBrowser; using np_utils::NPObjectPointer; namespace gpu_plugin { const NPUTF8 GPUPluginObject::kPluginType[] = "application/vnd.google.chrome.gpu-plugin"; GPUPluginObject::GPUPluginObject(NPP npp) : npp_(npp), status_(kWaitingForNew), command_buffer_(new CommandBufferService), processor_(new GPUProcessor(npp, command_buffer_.get())) { memset(&window_, 0, sizeof(window_)); } NPError GPUPluginObject::New(NPMIMEType plugin_type, int16 argc, char* argn[], char* argv[], NPSavedData* saved) { if (status_ != kWaitingForNew) return NPERR_GENERIC_ERROR; status_ = kWaitingForSetWindow; return NPERR_NO_ERROR; } NPError GPUPluginObject::SetWindow(NPWindow* new_window) { if (status_ == kWaitingForNew || status_ == kDestroyed) return NPERR_GENERIC_ERROR; // PlatformSpecificSetWindow advances the status depending on what happens. NPError error = PlatformSpecificSetWindow(new_window); if (error == NPERR_NO_ERROR) { window_ = *new_window; if (event_sync_.Get()) { NPInvokeVoid(npp_, event_sync_, "resize", static_cast<int32>(window_.width), static_cast<int32>(window_.height)); } } else { memset(&window_, 0, sizeof(window_)); } return error; } int16 GPUPluginObject::HandleEvent(NPEvent* event) { return 0; } NPError GPUPluginObject::Destroy(NPSavedData** saved) { if (status_ == kWaitingForNew || status_ == kDestroyed) return NPERR_GENERIC_ERROR; if (command_buffer_.get()) { command_buffer_->SetPutOffsetChangeCallback(NULL); } status_ = kDestroyed; return NPERR_NO_ERROR; } void GPUPluginObject::Release() { DCHECK(status_ == kWaitingForNew || status_ == kDestroyed); NPBrowser::get()->ReleaseObject(this); } NPObject*GPUPluginObject::GetScriptableNPObject() { NPBrowser::get()->RetainObject(this); return this; } CommandBuffer* GPUPluginObject::OpenCommandBuffer() { if (status_ == kInitializationSuccessful) return command_buffer_.get(); // SetWindow must have been called before OpenCommandBuffer. // PlatformSpecificSetWindow advances the status to // kWaitingForOpenCommandBuffer. if (status_ != kWaitingForOpenCommandBuffer) return NULL; scoped_ptr<SharedMemory> ring_buffer(new SharedMemory); if (!ring_buffer->Create(std::wstring(), false, false, kCommandBufferSize)) return NULL; if (command_buffer_->Initialize(ring_buffer.release())) { if (processor_->Initialize(static_cast<HWND>(window_.window))) { command_buffer_->SetPutOffsetChangeCallback( NewCallback(processor_.get(), &GPUProcessor::ProcessCommands)); status_ = kInitializationSuccessful; return command_buffer_.get(); } } return NULL; } } // namespace gpu_plugin <commit_msg>Fix small issue in gpu_plugin_object<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdlib.h> #include "base/logging.h" #include "gpu/command_buffer/service/command_buffer_service.h" #include "gpu/command_buffer/service/gpu_processor.h" #include "gpu/np_utils/np_utils.h" #include "gpu/gpu_plugin/gpu_plugin_object.h" using ::base::SharedMemory; using command_buffer::CommandBuffer; using command_buffer::CommandBufferService; using command_buffer::GPUProcessor; using np_utils::NPBrowser; using np_utils::NPObjectPointer; namespace gpu_plugin { const NPUTF8 GPUPluginObject::kPluginType[] = "application/vnd.google.chrome.gpu-plugin"; GPUPluginObject::GPUPluginObject(NPP npp) : npp_(npp), status_(kWaitingForNew), command_buffer_(new CommandBufferService), processor_(new GPUProcessor(command_buffer_.get())) { memset(&window_, 0, sizeof(window_)); } NPError GPUPluginObject::New(NPMIMEType plugin_type, int16 argc, char* argn[], char* argv[], NPSavedData* saved) { if (status_ != kWaitingForNew) return NPERR_GENERIC_ERROR; status_ = kWaitingForSetWindow; return NPERR_NO_ERROR; } NPError GPUPluginObject::SetWindow(NPWindow* new_window) { if (status_ == kWaitingForNew || status_ == kDestroyed) return NPERR_GENERIC_ERROR; // PlatformSpecificSetWindow advances the status depending on what happens. NPError error = PlatformSpecificSetWindow(new_window); if (error == NPERR_NO_ERROR) { window_ = *new_window; if (event_sync_.Get()) { NPInvokeVoid(npp_, event_sync_, "resize", static_cast<int32>(window_.width), static_cast<int32>(window_.height)); } } else { memset(&window_, 0, sizeof(window_)); } return error; } int16 GPUPluginObject::HandleEvent(NPEvent* event) { return 0; } NPError GPUPluginObject::Destroy(NPSavedData** saved) { if (status_ == kWaitingForNew || status_ == kDestroyed) return NPERR_GENERIC_ERROR; if (command_buffer_.get()) { command_buffer_->SetPutOffsetChangeCallback(NULL); } status_ = kDestroyed; return NPERR_NO_ERROR; } void GPUPluginObject::Release() { DCHECK(status_ == kWaitingForNew || status_ == kDestroyed); NPBrowser::get()->ReleaseObject(this); } NPObject*GPUPluginObject::GetScriptableNPObject() { NPBrowser::get()->RetainObject(this); return this; } CommandBuffer* GPUPluginObject::OpenCommandBuffer() { if (status_ == kInitializationSuccessful) return command_buffer_.get(); // SetWindow must have been called before OpenCommandBuffer. // PlatformSpecificSetWindow advances the status to // kWaitingForOpenCommandBuffer. if (status_ != kWaitingForOpenCommandBuffer) return NULL; scoped_ptr<SharedMemory> ring_buffer(new SharedMemory); if (!ring_buffer->Create(std::wstring(), false, false, kCommandBufferSize)) return NULL; if (command_buffer_->Initialize(ring_buffer.release())) { if (processor_->Initialize(static_cast<HWND>(window_.window))) { command_buffer_->SetPutOffsetChangeCallback( NewCallback(processor_.get(), &GPUProcessor::ProcessCommands)); status_ = kInitializationSuccessful; return command_buffer_.get(); } } return NULL; } } // namespace gpu_plugin <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Bastian Holst <bastianholst@gmx.de> // Copyright 2012 Mohammed Nafees <nafees.technocool@gmail.com> // // Self #include "PhotoPluginModel.h" // Photo Plugin #include "FlickrParser.h" #include "PhotoPluginItem.h" #include "PhotoPlugin.h" // Marble #include "AbstractDataPluginItem.h" #include "GeoDataLatLonAltBox.h" #include "MarbleModel.h" #include "MarbleDebug.h" #include "MarbleWidget.h" // Qt #include <QHash> #include <QString> #include <QUrl> using namespace Marble; const QString flickrApiKey( "620131a1b82b000c9582b94effcdc636" ); PhotoPluginModel::PhotoPluginModel( const MarbleModel *marbleModel, QObject *parent ) : AbstractDataPluginModel( "photo", marbleModel, parent ), m_marbleWidget( 0 ) { } QUrl PhotoPluginModel::generateUrl( const QString& service, const QString& method, const QHash<QString,QString>& options ) { QString url( "" ); if( service == "flickr" ) url += "http://www.flickr.com/services/rest/"; else return QUrl(); url += "?method="; url += method; url += "&format=rest"; url += "&api_key="; url += flickrApiKey; QHash<QString,QString>::const_iterator it = options.constBegin(); QHash<QString,QString>::const_iterator const end = options.constEnd(); for (; it != end; ++it ) { url += '&'; url += it.key(); url += '='; url += it.value(); } return QUrl( url ); } void PhotoPluginModel::getAdditionalItems( const GeoDataLatLonAltBox& box, qint32 number ) { // Flickr only supports images for earth if( marbleModel()->planetId() != "earth" ) { return; } if( box.west() <= box.east() ) { QString bbox( "" ); bbox += QString::number( box.west() * RAD2DEG ) + ','; bbox += QString::number( box.south() * RAD2DEG ) + ','; bbox += QString::number( box.east() * RAD2DEG ) + ','; bbox += QString::number( box.north() * RAD2DEG ); QHash<QString,QString> options; options.insert( "per_page", QString::number( number ) ); options.insert( "bbox", bbox ); options.insert( "sort", "interestingness-desc" ); options.insert( "license", m_licenses ); downloadDescriptionFile( generateUrl( "flickr", "flickr.photos.search", options ) ); } else { // Flickr api doesn't support bboxes with west > east so we have to split in two boxes QString bboxWest( "" ); bboxWest += QString::number( box.west() * RAD2DEG ) + ','; bboxWest += QString::number( box.south() * RAD2DEG ) + ','; bboxWest += QString::number( 180 ) + ','; bboxWest += QString::number( box.north() * RAD2DEG ); QHash<QString,QString> optionsWest; optionsWest.insert( "per_page", QString::number( number/2 ) ); optionsWest.insert( "bbox", bboxWest ); optionsWest.insert( "sort", "interestingness-desc" ); optionsWest.insert( "license", m_licenses ); downloadDescriptionFile( generateUrl( "flickr", "flickr.photos.search", optionsWest ) ); QString bboxEast( "" ); bboxEast += QString::number( -180 ) + ','; bboxEast += QString::number( box.south() * RAD2DEG ) + ','; bboxEast += QString::number( box.east() * RAD2DEG ) + ','; bboxEast += QString::number( box.north() * RAD2DEG ); QHash<QString,QString> optionsEast; optionsEast.insert( "per_page", QString::number( number/2 ) ); optionsEast.insert( "bbox", bboxEast ); optionsEast.insert( "sort", "interestingness-desc" ); optionsEast.insert( "license", m_licenses ); downloadDescriptionFile( generateUrl( "flickr", "flickr.photos.search", optionsEast ) ); } } void PhotoPluginModel::parseFile( const QByteArray& file ) { QList<PhotoPluginItem*> list; FlickrParser parser( m_marbleWidget, &list, this ); parser.read( file ); QList<PhotoPluginItem*>::iterator it; QList<AbstractDataPluginItem*> items; for( it = list.begin(); it != list.end(); ++it ) { if( itemExists( (*it)->id() ) ) { delete (*it); continue; } downloadItem( (*it)->photoUrl(), "thumbnail", (*it) ); downloadItem( (*it)->infoUrl(), "info", (*it) ); items << *it; } addItemsToList( items ); } void PhotoPluginModel::setMarbleWidget( MarbleWidget *widget ) { m_marbleWidget = widget; } void PhotoPluginModel::setLicenseValues( const QString &licenses ) { m_licenses = licenses; } #include "PhotoPluginModel.moc" <commit_msg>make Photo plugin work again<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Bastian Holst <bastianholst@gmx.de> // Copyright 2012 Mohammed Nafees <nafees.technocool@gmail.com> // // Self #include "PhotoPluginModel.h" // Photo Plugin #include "FlickrParser.h" #include "PhotoPluginItem.h" #include "PhotoPlugin.h" // Marble #include "AbstractDataPluginItem.h" #include "GeoDataLatLonAltBox.h" #include "MarbleModel.h" #include "MarbleDebug.h" #include "MarbleWidget.h" // Qt #include <QHash> #include <QString> #include <QUrl> using namespace Marble; const QString flickrApiKey( "620131a1b82b000c9582b94effcdc636" ); PhotoPluginModel::PhotoPluginModel( const MarbleModel *marbleModel, QObject *parent ) : AbstractDataPluginModel( "photo", marbleModel, parent ), m_marbleWidget( 0 ) { } QUrl PhotoPluginModel::generateUrl( const QString& service, const QString& method, const QHash<QString,QString>& options ) { QString url( "" ); if( service == "flickr" ) url += "https://www.flickr.com/services/rest/"; else return QUrl(); url += "?method="; url += method; url += "&format=rest"; url += "&api_key="; url += flickrApiKey; QHash<QString,QString>::const_iterator it = options.constBegin(); QHash<QString,QString>::const_iterator const end = options.constEnd(); for (; it != end; ++it ) { url += '&'; url += it.key(); url += '='; url += it.value(); } return QUrl( url ); } void PhotoPluginModel::getAdditionalItems( const GeoDataLatLonAltBox& box, qint32 number ) { // Flickr only supports images for earth if( marbleModel()->planetId() != "earth" ) { return; } if( box.west() <= box.east() ) { QString bbox( "" ); bbox += QString::number( box.west() * RAD2DEG ) + ','; bbox += QString::number( box.south() * RAD2DEG ) + ','; bbox += QString::number( box.east() * RAD2DEG ) + ','; bbox += QString::number( box.north() * RAD2DEG ); QHash<QString,QString> options; options.insert( "per_page", QString::number( number ) ); options.insert( "bbox", bbox ); options.insert( "sort", "interestingness-desc" ); options.insert( "license", m_licenses ); downloadDescriptionFile( generateUrl( "flickr", "flickr.photos.search", options ) ); } else { // Flickr api doesn't support bboxes with west > east so we have to split in two boxes QString bboxWest( "" ); bboxWest += QString::number( box.west() * RAD2DEG ) + ','; bboxWest += QString::number( box.south() * RAD2DEG ) + ','; bboxWest += QString::number( 180 ) + ','; bboxWest += QString::number( box.north() * RAD2DEG ); QHash<QString,QString> optionsWest; optionsWest.insert( "per_page", QString::number( number/2 ) ); optionsWest.insert( "bbox", bboxWest ); optionsWest.insert( "sort", "interestingness-desc" ); optionsWest.insert( "license", m_licenses ); downloadDescriptionFile( generateUrl( "flickr", "flickr.photos.search", optionsWest ) ); QString bboxEast( "" ); bboxEast += QString::number( -180 ) + ','; bboxEast += QString::number( box.south() * RAD2DEG ) + ','; bboxEast += QString::number( box.east() * RAD2DEG ) + ','; bboxEast += QString::number( box.north() * RAD2DEG ); QHash<QString,QString> optionsEast; optionsEast.insert( "per_page", QString::number( number/2 ) ); optionsEast.insert( "bbox", bboxEast ); optionsEast.insert( "sort", "interestingness-desc" ); optionsEast.insert( "license", m_licenses ); downloadDescriptionFile( generateUrl( "flickr", "flickr.photos.search", optionsEast ) ); } } void PhotoPluginModel::parseFile( const QByteArray& file ) { QList<PhotoPluginItem*> list; FlickrParser parser( m_marbleWidget, &list, this ); parser.read( file ); QList<PhotoPluginItem*>::iterator it; QList<AbstractDataPluginItem*> items; for( it = list.begin(); it != list.end(); ++it ) { if( itemExists( (*it)->id() ) ) { delete (*it); continue; } downloadItem( (*it)->photoUrl(), "thumbnail", (*it) ); downloadItem( (*it)->infoUrl(), "info", (*it) ); items << *it; } addItemsToList( items ); } void PhotoPluginModel::setMarbleWidget( MarbleWidget *widget ) { m_marbleWidget = widget; } void PhotoPluginModel::setLicenseValues( const QString &licenses ) { m_licenses = licenses; } #include "PhotoPluginModel.moc" <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) #define PARAMDIM 5 namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go double ** param_mtx = new double *[num_of_ent]; double ** coord_mtx = new double *[num_of_ent]; for (int i = 0; i < num_of_ent; ++i) { coord_mtx[i] = new double[3*COORDIM]; param_mtx[i] = new double[PARAMDIM]; } // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coord_mtx[i][j*3] >> coord_mtx[i][j*3+1] >> coord_mtx[i][j*3+2] >> a >> b >> c; } mytfp >> param_mtx[i][0] >> param_mtx[i][1] >> param_mtx[i][2] >> param_mtx[i][3] >> param_mtx[i][4]; } mytfp.close(); #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coord_mtx[i][j*3] << " " << coord_mtx[i][j*3+1] << " " << coord_mtx[i][j*3+2] << std::endl; } std::cout << param_mtx[i][0] << " " << param_mtx[i][1] << " " << param_mtx[i][2] << " " << param_mtx[i][3] << " " << param_mtx[i][4] << std::endl; } #endif double sum = 1.0e0; double coordm[3*COORDIM]; double hc[3*COORDIM][3*COORDIM]; std::fill_n (coordm, (3*COORDIM), 0.0e0); std::fill_n (&(hc[0][0]), (3*COORDIM)*(3*COORDIM), 0.0e0); for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hc[i][j] += ((coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j])- (sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0); } } } double cstdev[3*COORDIM]; for (int i=0; i<(3*COORDIM); ++i) { arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(coord_mtx[l][i]); std::cout << "mean = " << stats.mean() << std::endl; std::cout << " " << coordm[i] << std::endl; std::cout << "var = " << stats.stddev() << std::endl; cstdev[i] = stats.stddev(); } for (int l=0; l<num_of_ent; ++l) { for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hc[i][j] += ((coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j])- (sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0); } } } /* for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hc[i][j] = hc[i][j]/(cstdev[i]*cstdev[j]); } } */ for (int i=0; i<(3*COORDIM); ++i) for (int j=i+1; j<(3*COORDIM); ++j) if (hc[i][j] != hc[j][i]) std::cout << i << " " << j << " " << hc[i][j] << " ERROR" << std::endl;; #ifdef DEBUG double coordm_d[3*COORDIM]; std::fill_n (coordm_d, (3*COORDIM), 0.0e0); for (int i=0; i<(3*COORDIM); ++i) { for (int l=0; l<num_of_ent; ++l) coordm_d[i] += coord_mtx[l][i]; coordm_d[i] = coordm_d[i] / (double)num_of_ent; //std::cout << coordm_d[i] << " " << coordm[i] << std::endl; } double hc_d[3*COORDIM][3*COORDIM]; std::fill_n (&(hc_d[0][0]), (3*COORDIM)*(3*COORDIM), 0.0e0); for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { for (int l=0; l<num_of_ent; ++l) { hc_d[i][j] += (coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j]); } hc_d[i][j] = hc_d[i][j] / (double)num_of_ent; //std::cout << hc_d[i][j] << " " << hc[i][j] << std::endl; } } arma::mat hca_d = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) hca_d(i,j) = hc_d[i][j]; arma::vec eigval_d; arma::mat eigvec_d; arma::eig_sym(eigval_d, eigvec_d, hca_d); for (int i=(3*COORDIM-1); i>=0; --i) { std::cout << i+1 << " ==> " << eigval_d(i) << std::endl; } std::cout << "====" << std::endl; #endif arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) hca(i,j) = hc[i][j]; arma::vec eigval; arma::mat eigvec; arma::eig_sym(eigval, eigvec, hca); #ifdef DEBUG double xnew[3*COORDIM]; std::fill_n (xnew, (3*COORDIM), 0.0e0); for (int l=0; l<num_of_ent; ++l) { for (int i=0; i<(3*COORDIM); ++i) { xnew[i] = 0.0e0; for (int j=0; j<(3*COORDIM); ++j) xnew[i] += eigvec(i, j) * (coord_mtx[l][i] - coordm[i]); } for (int i=0; i<(3*COORDIM); ++i) { std::cout << i << " --> " << xnew[i] << std::endl; } for (int i=0; i<PARAMDIM; ++i) std::cout << " " << param_mtx[i][i] << std::endl; } #endif double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); int j = 1; double totvar = 0.0e0; for (int i=(3*COORDIM-1); i>=0; --i) { if (j <= PARAMDIM) totvar += 100.0e0*(eigval(i)/totval); ++j; std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << " ==> " << eigval(i) << std::endl; } std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl; arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); hcai = hca.i(); //std::cout << hca * hcai ; //exit(1); // and so on ... double paramm[PARAMDIM]; arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM); std::fill_n(coordm, (3*COORDIM), 0.0e0 ); std::fill_n(paramm, PARAMDIM, 0.0e0 ); sum = 1.0e0; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<PARAMDIM; ++i) paramm[i] += (param_mtx[l][i]-paramm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<PARAMDIM; ++j) { hcap(i,j) += ((coord_mtx[l][i] - coordm[i])* (param_mtx[l][j] - paramm[j])- (sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0); } } } double pstdev[PARAMDIM]; for (int i=0; i<PARAMDIM; ++i) { arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param_mtx[l][i]); std::cout << "mean = " << stats.mean() << std::endl; std::cout << " " << paramm[i] << std::endl; std::cout << "var = " << stats.stddev() << std::endl; pstdev[i] = stats.stddev(); } /* for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<PARAMDIM; ++j) hcap(i,j) = hcap(i,j) / (cstdev[i]*pstdev[j]); */ arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM); for (int i=0; i<PARAMDIM; ++i) for (int l=0; l<(3*COORDIM); ++l) for (int m=0; m<(3*COORDIM); ++m) cmtx(i,l) += hcai(l,m) * hcap (m,i); std::cout << "C matrix: " << std::endl; std::cout << cmtx; double q[PARAMDIM]; std::fill_n(q, PARAMDIM, 0.0e0 ); //std::cout << cmtx; for (int i=0; i<PARAMDIM; ++i) { q[i] = paramm[i]; for (int l=0; l<(3*COORDIM); ++l) q[i] -= cmtx(i,l)*coordm[l]; } std::cout << "Q vector: " << std::endl; for (int i=0; i<PARAMDIM; ++i) std::cout << q[i] << std::endl; //test back for (int i=0; i<PARAMDIM; ++i) { double p = q[i]; for (int l=0; l<(3*COORDIM); ++l) p += cmtx(i,l)*coord_mtx[0][l]; std::cout << "P " << i+1 << " ==> " << p << std::endl; std::cout << " " << param_mtx[0][i] << std::endl; } // documento Annovi // calcolo matrice di correlazione traccie HC // diagonalizzo HC e determino A, matrice 5 autovettori principali (5 componenti pricipali) // A matrice rotazione che mi permette di calcolare la traslazione usando i paamtri di tracce // simulate. // documento ATLAS // calcolare V e data V calcolare inversa V e quindi C, matrice di rotazione // data C determinare il vettore di traslazione q // c plus q costanti PCA // write constants in a file for (int i = 0; i < num_of_ent; ++i) { delete(coord_mtx[i]); delete(param_mtx[i]); } delete(coord_mtx); delete(param_mtx); return 0; } <commit_msg>compute differences between computed and real params<commit_after>#include <iostream> #include <fstream> #include <string> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) #define PARAMDIM 5 namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go double ** param_mtx = new double *[num_of_ent]; double ** coord_mtx = new double *[num_of_ent]; for (int i = 0; i < num_of_ent; ++i) { coord_mtx[i] = new double[3*COORDIM]; param_mtx[i] = new double[PARAMDIM]; } // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coord_mtx[i][j*3] >> coord_mtx[i][j*3+1] >> coord_mtx[i][j*3+2] >> a >> b >> c; } mytfp >> param_mtx[i][0] >> param_mtx[i][1] >> param_mtx[i][2] >> param_mtx[i][3] >> param_mtx[i][4]; } mytfp.close(); #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coord_mtx[i][j*3] << " " << coord_mtx[i][j*3+1] << " " << coord_mtx[i][j*3+2] << std::endl; } std::cout << param_mtx[i][0] << " " << param_mtx[i][1] << " " << param_mtx[i][2] << " " << param_mtx[i][3] << " " << param_mtx[i][4] << std::endl; } #endif double sum = 1.0e0; double coordm[3*COORDIM]; arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); std::fill_n (coordm, (3*COORDIM), 0.0e0); for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hca(i,j) += ((coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j])- (sum-1.0e0)*hca(i,j)/sum)/(sum-1.0e0); } } } /* double cstdev[3*COORDIM]; for (int i=0; i<(3*COORDIM); ++i) { arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(coord_mtx[l][i]); std::cout << "mean = " << stats.mean() << std::endl; std::cout << " " << coordm[i] << std::endl; std::cout << "stdev = " << stats.stddev() << std::endl; cstdev[i] = stats.stddev(); } for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) hca(i,j) = hca(i,j) / (cstdev[i]*cstdev[j]); */ for (int i=0; i<(3*COORDIM); ++i) for (int j=i+1; j<(3*COORDIM); ++j) if (hca(i,j) != hca(j,i)) std::cout << i << " " << j << " " << hca(i,j) << " ERROR" << std::endl;; arma::vec eigval; arma::mat eigvec; arma::eig_sym(eigval, eigvec, hca); double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); int j = 1; double totvar = 0.0e0; for (int i=(3*COORDIM-1); i>=0; --i) { if (j <= PARAMDIM) totvar += 100.0e0*(eigval(i)/totval); ++j; #ifdef DEBUG std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << " ==> " << eigval(i) << std::endl; #endif } std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl; arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); hcai = hca.i(); //std::cout << hca * hcai ; //exit(1); // and so on ... double paramm[PARAMDIM]; arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM); std::fill_n(coordm, (3*COORDIM), 0.0e0 ); std::fill_n(paramm, PARAMDIM, 0.0e0 ); sum = 1.0e0; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<PARAMDIM; ++i) paramm[i] += (param_mtx[l][i]-paramm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<PARAMDIM; ++j) { hcap(i,j) += ((coord_mtx[l][i] - coordm[i])* (param_mtx[l][j] - paramm[j])- (sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0); } } } /* double pstdev[PARAMDIM]; for (int i=0; i<PARAMDIM; ++i) { arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param_mtx[l][i]); std::cout << "mean = " << stats.mean() << std::endl; std::cout << " " << paramm[i] << std::endl; std::cout << "stdev = " << stats.stddev() << std::endl; pstdev[i] = stats.stddev(); } for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<PARAMDIM; ++j) hcap(i,j) = hcap(i,j) / (cstdev[i]*pstdev[j]); */ arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM); for (int i=0; i<PARAMDIM; ++i) for (int l=0; l<(3*COORDIM); ++l) for (int m=0; m<(3*COORDIM); ++m) cmtx(i,l) += hcai(l,m) * hcap (m,i); //std::cout << "C matrix: " << std::endl; //std::cout << cmtx; double q[PARAMDIM]; std::fill_n(q, PARAMDIM, 0.0e0 ); for (int i=0; i<PARAMDIM; ++i) { q[i] = paramm[i]; for (int l=0; l<(3*COORDIM); ++l) q[i] -= cmtx(i,l)*coordm[l]; } #ifdef DEBUG std::cout << "Q vector: " << std::endl; for (int i=0; i<PARAMDIM; ++i) std::cout << q[i] << std::endl; #endif //test back arma::running_stat<double> pc[PARAMDIM]; for (int l=0; l<num_of_ent; ++l) { for (int i=0; i<PARAMDIM; ++i) { double p = q[i]; for (int k=0; k<(3*COORDIM); ++k) p += cmtx(i,k)*coord_mtx[l][k]; pc[i](fabs(p - param_mtx[l][i])/(fabs(p + param_mtx[l][i])/2.0)); } } for (int i=0; i<PARAMDIM; ++i) { std::cout << pc[i].mean() << " " << pc[i].stddev() << std::endl; arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param_mtx[l][i]); std::cout << " mean = " << stats.mean() << std::endl; std::cout << " stdev = " << stats.stddev() << std::endl; std::cout << " min = " << stats.min() << std::endl; std::cout << " max = " << stats.max() << std::endl; } for (int i = 0; i < num_of_ent; ++i) { delete(coord_mtx[i]); delete(param_mtx[i]); } delete(coord_mtx); delete(param_mtx); return 0; } <|endoftext|>
<commit_before>/** * \file ApplyGainFilter.cpp */ #include "ApplyGainFilter.h" #include <cassert> #include <cmath> #include <cstdint> namespace ATK { template<typename DataType_> ApplyGainFilter<DataType_>::ApplyGainFilter(int nb_channels) :Parent(2 * nb_channels, nb_channels) { output_delay = 1; } template<typename DataType_> ApplyGainFilter<DataType_>::~ApplyGainFilter() { } template<typename DataType_> void ApplyGainFilter<DataType_>::process_impl(int64_t size) const { assert(nb_input_ports == 2*nb_output_ports); for(int channel = 0; channel < nb_output_ports; ++channel) { const DataType* ATK_RESTRICT input1 = converted_inputs[2 * channel]; const DataType* ATK_RESTRICT input2 = converted_inputs[2 * channel + 1]; DataType* ATK_RESTRICT output = outputs[channel]; for(int64_t i = 0; i < size; ++i) { *(output++) = *(input1++) * *(input2++); } } } template class ApplyGainFilter<float>; template class ApplyGainFilter<double>; } <commit_msg>Simplify writing for compiler<commit_after>/** * \file ApplyGainFilter.cpp */ #include "ApplyGainFilter.h" #include <cassert> #include <cmath> #include <cstdint> namespace ATK { template<typename DataType_> ApplyGainFilter<DataType_>::ApplyGainFilter(int nb_channels) :Parent(2 * nb_channels, nb_channels) { output_delay = 1; } template<typename DataType_> ApplyGainFilter<DataType_>::~ApplyGainFilter() { } template<typename DataType_> void ApplyGainFilter<DataType_>::process_impl(int64_t size) const { assert(nb_input_ports == 2*nb_output_ports); for(int channel = 0; channel < nb_output_ports; ++channel) { const DataType* ATK_RESTRICT input1 = converted_inputs[2 * channel]; const DataType* ATK_RESTRICT input2 = converted_inputs[2 * channel + 1]; DataType* ATK_RESTRICT output = outputs[channel]; for(int64_t i = 0; i < size; ++i) { output[i] = input1[i] * input2[i]; } } } template class ApplyGainFilter<float>; template class ApplyGainFilter<double>; } <|endoftext|>
<commit_before>//===-- SILOpt.cpp - SIL Optimization Driver ------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the entry point. // //===----------------------------------------------------------------------===// #include "swift/Subsystems.h" #include "swift/Frontend/DiagnosticVerifier.h" #include "swift/Frontend/Frontend.h" #include "swift/Frontend/PrintingDiagnosticConsumer.h" #include "swift/SILPasses/Passes.h" #include "swift/SILPasses/PassManager.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" using namespace swift; enum class PassKind { AllocBoxToStack, CapturePromotion, CCP, CSE, DefiniteInit, DCE, DataflowDiagnostics, InOutDeshadowing, MandatoryInlining, PredictableMemoryOpt, SILCleanup, SILMem2Reg, SILCombine, SILDeadFunctionElimination, SILSpecialization, SILDevirt, SimplifyCFG, PerformanceInlining, CodeMotion, LowerAggregateInstrs, SROA, ARCOpts, StripDebugInfo, AllocRefElimination, InstCount, }; static llvm::cl::opt<std::string> InputFilename(llvm::cl::desc("input file"), llvm::cl::init("-"), llvm::cl::Positional); static llvm::cl::opt<std::string> OutputFilename("o", llvm::cl::desc("output filename"), llvm::cl::init("-")); static llvm::cl::list<std::string> ImportPaths("I", llvm::cl::desc("add a directory to the import search path")); static llvm::cl::list<PassKind> Passes(llvm::cl::desc("Passes:"), llvm::cl::values(clEnumValN(PassKind::AllocBoxToStack, "allocbox-to-stack", "Promote memory"), clEnumValN(PassKind::CapturePromotion, "capture-promotion", "Promote closure capture variables"), clEnumValN(PassKind::SILMem2Reg, "mem2reg", "Promote stack allocations to registers"), clEnumValN(PassKind::SILCleanup, "cleanup", "Cleanup SIL in preparation for IRGen"), clEnumValN(PassKind::CCP, "constant-propagation", "Propagate constants"), clEnumValN(PassKind::CSE, "cse", "Perform constant subexpression elimination."), clEnumValN(PassKind::DataflowDiagnostics, "dataflow-diagnostics", "Emit SIL diagnostics"), clEnumValN(PassKind::DCE, "dead-code-elimination", "Remove dead code"), clEnumValN(PassKind::DefiniteInit, "definite-init","definitive initialization"), clEnumValN(PassKind::InOutDeshadowing, "inout-deshadow", "Remove inout argument shadow variables"), clEnumValN(PassKind::MandatoryInlining, "mandatory-inlining", "Inline transparent functions"), clEnumValN(PassKind::SILSpecialization, "specialize", "Specialize generic functions"), clEnumValN(PassKind::SILDevirt, "devirtualize", "Devirtualize virtual calls"), clEnumValN(PassKind::PredictableMemoryOpt, "predictable-memopt", "Predictable early memory optimization"), clEnumValN(PassKind::SILCombine, "sil-combine", "Perform small peepholes and combine" " operations."), clEnumValN(PassKind::SILDeadFunctionElimination, "sil-deadfuncelim", "Remove private unused functions"), clEnumValN(PassKind::SimplifyCFG, "simplify-cfg", "Clean up the CFG of SIL functions"), clEnumValN(PassKind::PerformanceInlining, "inline", "Inline functions which are determined to be" " less than a pre-set cost."), clEnumValN(PassKind::CodeMotion, "codemotion", "Perform code motion optimizations"), clEnumValN(PassKind::LowerAggregateInstrs, "lower-aggregate-instrs", "Perform lower aggregate instrs to scalar " "instrs."), clEnumValN(PassKind::SROA, "sroa", "Perform SIL scalar replacement of " "aggregates."), clEnumValN(PassKind::ARCOpts, "arc-opts", "Perform automatic reference counting " "optimizations."), clEnumValN(PassKind::StripDebugInfo, "strip-debug-info", "Strip debug info."), clEnumValN(PassKind::AllocRefElimination, "allocref-elim", "Eliminate alloc refs with no side effect " "destructors that are only stored into."), clEnumValN(PassKind::InstCount, "inst-count", "Count all instructions in the given " "module."), clEnumValEnd)); static llvm::cl::opt<bool> PrintStats("print-stats", llvm::cl::desc("Print various statistics")); static llvm::cl::opt<bool> VerifyMode("verify", llvm::cl::desc("verify diagnostics against expected-" "{error|warning|note} annotations")); static llvm::cl::opt<unsigned> SILInlineThreshold("sil-inline-threshold", llvm::cl::Hidden, llvm::cl::init(50)); static llvm::cl::opt<bool> EmitVerboseSIL("emit-verbose-sil", llvm::cl::desc("Emit locations during sil emission.")); // This function isn't referenced outside its translation unit, but it // can't use the "static" keyword because its address is used for // getMainExecutable (since some platforms don't support taking the // address of main, and some platforms can't implement getMainExecutable // without being given the address of a function in the main executable). void anchorForGetMainExecutable() {} int main(int argc, char **argv) { // Print a stack trace if we signal out. llvm::sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram X(argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv, "Swift SIL optimizer\n"); // Call llvm_shutdown() on exit to print stats and free memory. llvm::llvm_shutdown_obj Y; if (PrintStats) llvm::EnableStatistics(); CompilerInvocation Invocation; Invocation.setMainExecutablePath( llvm::sys::fs::getMainExecutable(argv[0], reinterpret_cast<void *>(&anchorForGetMainExecutable))); // Give the context the list of search paths to use for modules. Invocation.setImportSearchPaths(ImportPaths); Invocation.setModuleName("main"); Invocation.setInputKind(SourceFileKind::SIL); Invocation.addInputFilename(InputFilename); CompilerInstance CI; PrintingDiagnosticConsumer PrintDiags; CI.addDiagnosticConsumer(&PrintDiags); if (CI.setup(Invocation)) return 1; CI.performParse(); // If parsing produced an error, don't run any passes. if (CI.getASTContext().hadError()) return 1; // If we're in verify mode, install a custom diagnostic handling for // SourceMgr. if (VerifyMode) enableDiagnosticVerifier(CI.getSourceMgr()); SILPassManager PM(CI.getSILModule()); PM.registerAnalysis(createCallGraphAnalysis(CI.getSILModule())); for (auto Pass : Passes) { switch (Pass) { case PassKind::AllocBoxToStack: PM.add(createStackPromotion()); break; case PassKind::CapturePromotion: PM.add(createCapturePromotion()); break; case PassKind::CCP: PM.add(createConstantPropagation()); break; case PassKind::CSE: PM.add(createCSE()); break; case PassKind::DCE: PM.add(createDCE()); break; case PassKind::DefiniteInit: PM.add(createDefiniteInitialization()); break; case PassKind::DataflowDiagnostics: PM.add(createEmitDFDiagnostics()); break; case PassKind::InOutDeshadowing: PM.add(createInOutDeshadowing()); break; case PassKind::MandatoryInlining: PM.add(createMandatoryInlining()); break; case PassKind::PredictableMemoryOpt: PM.add(createPredictableMemoryOptimizations()); break; case PassKind::SILCleanup: PM.add(createSILCleanup()); break; case PassKind::SILMem2Reg: PM.add(createMem2Reg()); break; case PassKind::SILCombine: PM.add(createSILCombine()); break; case PassKind::SILDeadFunctionElimination: PM.add(createDeadFunctionElimination()); break; case PassKind::SILSpecialization: PM.add(createGenericSpecializer()); break; case PassKind::SILDevirt: PM.add(createDevirtualization()); break; case PassKind::SimplifyCFG: PM.add(createSimplifyCFG()); break; case PassKind::PerformanceInlining: PM.add(createPerfInliner(SILInlineThreshold)); break; case PassKind::CodeMotion: PM.add(createCodeMotion()); break; case PassKind::LowerAggregateInstrs: PM.add(createLowerAggregate()); break; case PassKind::SROA: PM.add(createSROA()); break; case PassKind::ARCOpts: PM.add(createSILARCOpts()); break; case PassKind::StripDebugInfo: PM.add(createStripDebug()); break; case PassKind::AllocRefElimination: PM.add(createSILAllocRefElimination()); break; case PassKind::InstCount: PM.add(createSILInstCount()); break; } PM.run(); // Verify the module after every pass. CI.getSILModule()->verify(); } std::string ErrorInfo; llvm::raw_fd_ostream OS(OutputFilename.c_str(), ErrorInfo); if (!ErrorInfo.empty()) { llvm::errs() << "while opening '" << OutputFilename << "': " << ErrorInfo << '\n'; return 1; } CI.getSILModule()->print(OS, EmitVerboseSIL); bool HadError = CI.getASTContext().hadError(); // If we're in -verify mode, we've buffered up all of the generated // diagnostics. Check now to ensure that they meet our expectations. if (VerifyMode) HadError = verifyDiagnostics(CI.getSourceMgr(), CI.getInputBufferIDs()); return HadError; } <commit_msg>[sil-opt] Move PM.run() outside of the loop that sets up the pass manager so we don't run it every time we add a new pass.<commit_after>//===-- SILOpt.cpp - SIL Optimization Driver ------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the entry point. // //===----------------------------------------------------------------------===// #include "swift/Subsystems.h" #include "swift/Frontend/DiagnosticVerifier.h" #include "swift/Frontend/Frontend.h" #include "swift/Frontend/PrintingDiagnosticConsumer.h" #include "swift/SILPasses/Passes.h" #include "swift/SILPasses/PassManager.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" using namespace swift; enum class PassKind { AllocBoxToStack, CapturePromotion, CCP, CSE, DefiniteInit, DCE, DataflowDiagnostics, InOutDeshadowing, MandatoryInlining, PredictableMemoryOpt, SILCleanup, SILMem2Reg, SILCombine, SILDeadFunctionElimination, SILSpecialization, SILDevirt, SimplifyCFG, PerformanceInlining, CodeMotion, LowerAggregateInstrs, SROA, ARCOpts, StripDebugInfo, AllocRefElimination, InstCount, }; static llvm::cl::opt<std::string> InputFilename(llvm::cl::desc("input file"), llvm::cl::init("-"), llvm::cl::Positional); static llvm::cl::opt<std::string> OutputFilename("o", llvm::cl::desc("output filename"), llvm::cl::init("-")); static llvm::cl::list<std::string> ImportPaths("I", llvm::cl::desc("add a directory to the import search path")); static llvm::cl::list<PassKind> Passes(llvm::cl::desc("Passes:"), llvm::cl::values(clEnumValN(PassKind::AllocBoxToStack, "allocbox-to-stack", "Promote memory"), clEnumValN(PassKind::CapturePromotion, "capture-promotion", "Promote closure capture variables"), clEnumValN(PassKind::SILMem2Reg, "mem2reg", "Promote stack allocations to registers"), clEnumValN(PassKind::SILCleanup, "cleanup", "Cleanup SIL in preparation for IRGen"), clEnumValN(PassKind::CCP, "constant-propagation", "Propagate constants"), clEnumValN(PassKind::CSE, "cse", "Perform constant subexpression elimination."), clEnumValN(PassKind::DataflowDiagnostics, "dataflow-diagnostics", "Emit SIL diagnostics"), clEnumValN(PassKind::DCE, "dead-code-elimination", "Remove dead code"), clEnumValN(PassKind::DefiniteInit, "definite-init","definitive initialization"), clEnumValN(PassKind::InOutDeshadowing, "inout-deshadow", "Remove inout argument shadow variables"), clEnumValN(PassKind::MandatoryInlining, "mandatory-inlining", "Inline transparent functions"), clEnumValN(PassKind::SILSpecialization, "specialize", "Specialize generic functions"), clEnumValN(PassKind::SILDevirt, "devirtualize", "Devirtualize virtual calls"), clEnumValN(PassKind::PredictableMemoryOpt, "predictable-memopt", "Predictable early memory optimization"), clEnumValN(PassKind::SILCombine, "sil-combine", "Perform small peepholes and combine" " operations."), clEnumValN(PassKind::SILDeadFunctionElimination, "sil-deadfuncelim", "Remove private unused functions"), clEnumValN(PassKind::SimplifyCFG, "simplify-cfg", "Clean up the CFG of SIL functions"), clEnumValN(PassKind::PerformanceInlining, "inline", "Inline functions which are determined to be" " less than a pre-set cost."), clEnumValN(PassKind::CodeMotion, "codemotion", "Perform code motion optimizations"), clEnumValN(PassKind::LowerAggregateInstrs, "lower-aggregate-instrs", "Perform lower aggregate instrs to scalar " "instrs."), clEnumValN(PassKind::SROA, "sroa", "Perform SIL scalar replacement of " "aggregates."), clEnumValN(PassKind::ARCOpts, "arc-opts", "Perform automatic reference counting " "optimizations."), clEnumValN(PassKind::StripDebugInfo, "strip-debug-info", "Strip debug info."), clEnumValN(PassKind::AllocRefElimination, "allocref-elim", "Eliminate alloc refs with no side effect " "destructors that are only stored into."), clEnumValN(PassKind::InstCount, "inst-count", "Count all instructions in the given " "module."), clEnumValEnd)); static llvm::cl::opt<bool> PrintStats("print-stats", llvm::cl::desc("Print various statistics")); static llvm::cl::opt<bool> VerifyMode("verify", llvm::cl::desc("verify diagnostics against expected-" "{error|warning|note} annotations")); static llvm::cl::opt<unsigned> SILInlineThreshold("sil-inline-threshold", llvm::cl::Hidden, llvm::cl::init(50)); static llvm::cl::opt<bool> EmitVerboseSIL("emit-verbose-sil", llvm::cl::desc("Emit locations during sil emission.")); // This function isn't referenced outside its translation unit, but it // can't use the "static" keyword because its address is used for // getMainExecutable (since some platforms don't support taking the // address of main, and some platforms can't implement getMainExecutable // without being given the address of a function in the main executable). void anchorForGetMainExecutable() {} int main(int argc, char **argv) { // Print a stack trace if we signal out. llvm::sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram X(argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv, "Swift SIL optimizer\n"); // Call llvm_shutdown() on exit to print stats and free memory. llvm::llvm_shutdown_obj Y; if (PrintStats) llvm::EnableStatistics(); CompilerInvocation Invocation; Invocation.setMainExecutablePath( llvm::sys::fs::getMainExecutable(argv[0], reinterpret_cast<void *>(&anchorForGetMainExecutable))); // Give the context the list of search paths to use for modules. Invocation.setImportSearchPaths(ImportPaths); Invocation.setModuleName("main"); Invocation.setInputKind(SourceFileKind::SIL); Invocation.addInputFilename(InputFilename); CompilerInstance CI; PrintingDiagnosticConsumer PrintDiags; CI.addDiagnosticConsumer(&PrintDiags); if (CI.setup(Invocation)) return 1; CI.performParse(); // If parsing produced an error, don't run any passes. if (CI.getASTContext().hadError()) return 1; // If we're in verify mode, install a custom diagnostic handling for // SourceMgr. if (VerifyMode) enableDiagnosticVerifier(CI.getSourceMgr()); SILPassManager PM(CI.getSILModule()); PM.registerAnalysis(createCallGraphAnalysis(CI.getSILModule())); for (auto Pass : Passes) { switch (Pass) { case PassKind::AllocBoxToStack: PM.add(createStackPromotion()); break; case PassKind::CapturePromotion: PM.add(createCapturePromotion()); break; case PassKind::CCP: PM.add(createConstantPropagation()); break; case PassKind::CSE: PM.add(createCSE()); break; case PassKind::DCE: PM.add(createDCE()); break; case PassKind::DefiniteInit: PM.add(createDefiniteInitialization()); break; case PassKind::DataflowDiagnostics: PM.add(createEmitDFDiagnostics()); break; case PassKind::InOutDeshadowing: PM.add(createInOutDeshadowing()); break; case PassKind::MandatoryInlining: PM.add(createMandatoryInlining()); break; case PassKind::PredictableMemoryOpt: PM.add(createPredictableMemoryOptimizations()); break; case PassKind::SILCleanup: PM.add(createSILCleanup()); break; case PassKind::SILMem2Reg: PM.add(createMem2Reg()); break; case PassKind::SILCombine: PM.add(createSILCombine()); break; case PassKind::SILDeadFunctionElimination: PM.add(createDeadFunctionElimination()); break; case PassKind::SILSpecialization: PM.add(createGenericSpecializer()); break; case PassKind::SILDevirt: PM.add(createDevirtualization()); break; case PassKind::SimplifyCFG: PM.add(createSimplifyCFG()); break; case PassKind::PerformanceInlining: PM.add(createPerfInliner(SILInlineThreshold)); break; case PassKind::CodeMotion: PM.add(createCodeMotion()); break; case PassKind::LowerAggregateInstrs: PM.add(createLowerAggregate()); break; case PassKind::SROA: PM.add(createSROA()); break; case PassKind::ARCOpts: PM.add(createSILARCOpts()); break; case PassKind::StripDebugInfo: PM.add(createStripDebug()); break; case PassKind::AllocRefElimination: PM.add(createSILAllocRefElimination()); break; case PassKind::InstCount: PM.add(createSILInstCount()); break; } // Verify the module after every pass. CI.getSILModule()->verify(); } PM.run(); std::string ErrorInfo; llvm::raw_fd_ostream OS(OutputFilename.c_str(), ErrorInfo); if (!ErrorInfo.empty()) { llvm::errs() << "while opening '" << OutputFilename << "': " << ErrorInfo << '\n'; return 1; } CI.getSILModule()->print(OS, EmitVerboseSIL); bool HadError = CI.getASTContext().hadError(); // If we're in -verify mode, we've buffered up all of the generated // diagnostics. Check now to ensure that they meet our expectations. if (VerifyMode) HadError = verifyDiagnostics(CI.getSourceMgr(), CI.getInputBufferIDs()); return HadError; } <|endoftext|>
<commit_before>//===-- SILOpt.cpp - SIL Optimization Driver ------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is a tool for reading sil files and running sil passes on them. The // targeted usecase is debugging and testing SIL passes. // //===----------------------------------------------------------------------===// #include "swift/Subsystems.h" #include "swift/AST/SILOptions.h" #include "swift/Frontend/DiagnosticVerifier.h" #include "swift/Frontend/Frontend.h" #include "swift/Frontend/PrintingDiagnosticConsumer.h" #include "swift/SILPasses/Passes.h" #include "swift/SILPasses/PassManager.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" using namespace swift; namespace { enum class PassKind { AllocBoxToStack, CapturePromotion, CCP, CSE, DefiniteInit, DCE, DataflowDiagnostics, InOutDeshadowing, MandatoryInlining, PredictableMemoryOpt, SILCleanup, SILMem2Reg, SILCombine, SILDeadFunctionElimination, SILSpecialization, SILDevirt, SimplifyCFG, PerformanceInlining, CodeMotion, LowerAggregateInstrs, SROA, ARCOpts, StripDebugInfo, DeadObjectElimination, InstCount, AADumper, LoadStoreOpts, }; } // end anonymous namespace static llvm::cl::opt<std::string> InputFilename(llvm::cl::desc("input file"), llvm::cl::init("-"), llvm::cl::Positional); static llvm::cl::opt<std::string> OutputFilename("o", llvm::cl::desc("output filename"), llvm::cl::init("-")); static llvm::cl::list<std::string> ImportPaths("I", llvm::cl::desc("add a directory to the import search path")); static llvm::cl::list<PassKind> Passes(llvm::cl::desc("Passes:"), llvm::cl::values(clEnumValN(PassKind::AllocBoxToStack, "allocbox-to-stack", "Promote memory"), clEnumValN(PassKind::CapturePromotion, "capture-promotion", "Promote closure capture variables"), clEnumValN(PassKind::SILMem2Reg, "mem2reg", "Promote stack allocations to registers"), clEnumValN(PassKind::SILCleanup, "cleanup", "Cleanup SIL in preparation for IRGen"), clEnumValN(PassKind::CCP, "constant-propagation", "Propagate constants"), clEnumValN(PassKind::CSE, "cse", "Perform constant subexpression elimination."), clEnumValN(PassKind::DataflowDiagnostics, "dataflow-diagnostics", "Emit SIL diagnostics"), clEnumValN(PassKind::DCE, "dead-code-elimination", "Remove dead code"), clEnumValN(PassKind::DefiniteInit, "definite-init","definitive initialization"), clEnumValN(PassKind::InOutDeshadowing, "inout-deshadow", "Remove inout argument shadow variables"), clEnumValN(PassKind::MandatoryInlining, "mandatory-inlining", "Inline transparent functions"), clEnumValN(PassKind::SILSpecialization, "specialize", "Specialize generic functions"), clEnumValN(PassKind::SILDevirt, "devirtualize", "Devirtualize virtual calls"), clEnumValN(PassKind::PredictableMemoryOpt, "predictable-memopt", "Predictable early memory optimization"), clEnumValN(PassKind::SILCombine, "sil-combine", "Perform small peepholes and combine" " operations."), clEnumValN(PassKind::SILDeadFunctionElimination, "sil-deadfuncelim", "Remove private unused functions"), clEnumValN(PassKind::SimplifyCFG, "simplify-cfg", "Clean up the CFG of SIL functions"), clEnumValN(PassKind::PerformanceInlining, "inline", "Inline functions which are determined to be" " less than a pre-set cost."), clEnumValN(PassKind::CodeMotion, "codemotion", "Perform code motion optimizations"), clEnumValN(PassKind::LowerAggregateInstrs, "lower-aggregate-instrs", "Perform lower aggregate instrs to scalar " "instrs."), clEnumValN(PassKind::SROA, "sroa", "Perform SIL scalar replacement of " "aggregates."), clEnumValN(PassKind::ARCOpts, "arc-opts", "Perform automatic reference counting " "optimizations."), clEnumValN(PassKind::StripDebugInfo, "strip-debug-info", "Strip debug info."), clEnumValN(PassKind::DeadObjectElimination, "deadobject-elim", "Eliminate unused object allocation with no " "side effect destructors."), clEnumValN(PassKind::InstCount, "inst-count", "Count all instructions in the given " "module."), clEnumValN(PassKind::AADumper, "aa-dump", "Dump AA result for all pairs of ValueKinds" " in all functions."), clEnumValN(PassKind::LoadStoreOpts, "load-store-opts", "Remove duplicate loads, dead stores, and " "perform load forwarding."), clEnumValEnd)); static llvm::cl::opt<bool> PrintStats("print-stats", llvm::cl::desc("Print various statistics")); static llvm::cl::opt<bool> VerifyMode("verify", llvm::cl::desc("verify diagnostics against expected-" "{error|warning|note} annotations")); static llvm::cl::opt<unsigned> SILInlineThreshold("sil-inline-threshold", llvm::cl::Hidden, llvm::cl::init(50)); static llvm::cl::opt<unsigned> SILDevirtThreshold("sil-devirt-threshold", llvm::cl::Hidden, llvm::cl::init(0)); static llvm::cl::opt<bool> EnableSILVerifyAll("enable-sil-verify-all", llvm::cl::Hidden, llvm::cl::init(true), llvm::cl::desc("Run sil verifications after every pass.")); static llvm::cl::opt<bool> EnableSILPrintAll("-sil-print-all", llvm::cl::Hidden, llvm::cl::init(false), llvm::cl::desc("Print sil after every pass.")); static llvm::cl::opt<bool> EmitVerboseSIL("emit-verbose-sil", llvm::cl::desc("Emit locations during sil emission.")); // This function isn't referenced outside its translation unit, but it // can't use the "static" keyword because its address is used for // getMainExecutable (since some platforms don't support taking the // address of main, and some platforms can't implement getMainExecutable // without being given the address of a function in the main executable). void anchorForGetMainExecutable() {} int main(int argc, char **argv) { // Print a stack trace if we signal out. llvm::sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram X(argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv, "Swift SIL optimizer\n"); // Call llvm_shutdown() on exit to print stats and free memory. llvm::llvm_shutdown_obj Y; if (PrintStats) llvm::EnableStatistics(); CompilerInvocation Invocation; Invocation.setMainExecutablePath( llvm::sys::fs::getMainExecutable(argv[0], reinterpret_cast<void *>(&anchorForGetMainExecutable))); // Give the context the list of search paths to use for modules. Invocation.setImportSearchPaths(ImportPaths); Invocation.setModuleName("main"); Invocation.setInputKind(SourceFileKind::SIL); Invocation.addInputFilename(InputFilename); CompilerInstance CI; PrintingDiagnosticConsumer PrintDiags; CI.addDiagnosticConsumer(&PrintDiags); if (CI.setup(Invocation)) return 1; CI.performParse(); // If parsing produced an error, don't run any passes. if (CI.getASTContext().hadError()) return 1; // If we're in verify mode, install a custom diagnostic handling for // SourceMgr. if (VerifyMode) enableDiagnosticVerifier(CI.getSourceMgr()); SILOptions &SILOpts = Invocation.getSILOptions(); SILOpts.InlineThreshold = SILInlineThreshold; SILOpts.DevirtThreshold = SILDevirtThreshold; SILOpts.VerifyAll = EnableSILVerifyAll; SILOpts.PrintAll = EnableSILPrintAll; SILPassManager PM(CI.getSILModule(), SILOpts); PM.registerAnalysis(createCallGraphAnalysis(CI.getSILModule())); PM.registerAnalysis(createAliasAnalysis(CI.getSILModule())); PM.registerAnalysis(createDominanceAnalysis(CI.getSILModule())); PM.registerAnalysis(createSpecializedArgsAnalysis(CI.getSILModule())); for (auto Pass : Passes) { switch (Pass) { case PassKind::AllocBoxToStack: PM.add(createAllocBoxToStack()); break; case PassKind::CapturePromotion: PM.add(createCapturePromotion()); break; case PassKind::CCP: PM.add(createConstantPropagation()); break; case PassKind::CSE: PM.add(createCSE()); break; case PassKind::DCE: PM.add(createDCE()); break; case PassKind::DefiniteInit: PM.add(createDefiniteInitialization()); break; case PassKind::DataflowDiagnostics: PM.add(createEmitDFDiagnostics()); break; case PassKind::InOutDeshadowing: PM.add(createInOutDeshadowing()); break; case PassKind::MandatoryInlining: PM.add(createMandatoryInlining()); break; case PassKind::PredictableMemoryOpt: PM.add(createPredictableMemoryOptimizations()); break; case PassKind::SILCleanup: PM.add(createSILCleanup()); break; case PassKind::SILMem2Reg: PM.add(createMem2Reg()); break; case PassKind::SILCombine: PM.add(createSILCombine()); break; case PassKind::SILDeadFunctionElimination: PM.add(createDeadFunctionElimination()); break; case PassKind::SILSpecialization: PM.add(createGenericSpecializer()); break; case PassKind::SILDevirt: PM.add(createDevirtualization()); break; case PassKind::SimplifyCFG: PM.add(createSimplifyCFG()); break; case PassKind::PerformanceInlining: PM.add(createPerfInliner()); break; case PassKind::CodeMotion: PM.add(createCodeMotion()); break; case PassKind::LowerAggregateInstrs: PM.add(createLowerAggregate()); break; case PassKind::SROA: PM.add(createSROA()); break; case PassKind::ARCOpts: PM.add(createARCOpts()); break; case PassKind::StripDebugInfo: PM.add(createStripDebug()); break; case PassKind::DeadObjectElimination: PM.add(createDeadObjectElimination()); break; case PassKind::InstCount: PM.add(createSILInstCount()); break; case PassKind::AADumper: PM.add(createSILAADumper()); break; case PassKind::LoadStoreOpts: PM.add(createLoadStoreOpts()); break; } } PM.run(); std::string ErrorInfo; llvm::raw_fd_ostream OS(OutputFilename.c_str(), ErrorInfo); if (!ErrorInfo.empty()) { llvm::errs() << "while opening '" << OutputFilename << "': " << ErrorInfo << '\n'; return 1; } CI.getSILModule()->print(OS, EmitVerboseSIL); bool HadError = CI.getASTContext().hadError(); // If we're in -verify mode, we've buffered up all of the generated // diagnostics. Check now to ensure that they meet our expectations. if (VerifyMode) HadError = verifyDiagnostics(CI.getSourceMgr(), CI.getInputBufferIDs()); return HadError; } <commit_msg>[sil-opt] Dump decls as well as SIL.<commit_after>//===-- SILOpt.cpp - SIL Optimization Driver ------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is a tool for reading sil files and running sil passes on them. The // targeted usecase is debugging and testing SIL passes. // //===----------------------------------------------------------------------===// #include "swift/Subsystems.h" #include "swift/AST/SILOptions.h" #include "swift/Frontend/DiagnosticVerifier.h" #include "swift/Frontend/Frontend.h" #include "swift/Frontend/PrintingDiagnosticConsumer.h" #include "swift/SILPasses/Passes.h" #include "swift/SILPasses/PassManager.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" using namespace swift; namespace { enum class PassKind { AllocBoxToStack, CapturePromotion, CCP, CSE, DefiniteInit, DCE, DataflowDiagnostics, InOutDeshadowing, MandatoryInlining, PredictableMemoryOpt, SILCleanup, SILMem2Reg, SILCombine, SILDeadFunctionElimination, SILSpecialization, SILDevirt, SimplifyCFG, PerformanceInlining, CodeMotion, LowerAggregateInstrs, SROA, ARCOpts, StripDebugInfo, DeadObjectElimination, InstCount, AADumper, LoadStoreOpts, }; } // end anonymous namespace static llvm::cl::opt<std::string> InputFilename(llvm::cl::desc("input file"), llvm::cl::init("-"), llvm::cl::Positional); static llvm::cl::opt<std::string> OutputFilename("o", llvm::cl::desc("output filename"), llvm::cl::init("-")); static llvm::cl::list<std::string> ImportPaths("I", llvm::cl::desc("add a directory to the import search path")); static llvm::cl::list<PassKind> Passes(llvm::cl::desc("Passes:"), llvm::cl::values(clEnumValN(PassKind::AllocBoxToStack, "allocbox-to-stack", "Promote memory"), clEnumValN(PassKind::CapturePromotion, "capture-promotion", "Promote closure capture variables"), clEnumValN(PassKind::SILMem2Reg, "mem2reg", "Promote stack allocations to registers"), clEnumValN(PassKind::SILCleanup, "cleanup", "Cleanup SIL in preparation for IRGen"), clEnumValN(PassKind::CCP, "constant-propagation", "Propagate constants"), clEnumValN(PassKind::CSE, "cse", "Perform constant subexpression elimination."), clEnumValN(PassKind::DataflowDiagnostics, "dataflow-diagnostics", "Emit SIL diagnostics"), clEnumValN(PassKind::DCE, "dead-code-elimination", "Remove dead code"), clEnumValN(PassKind::DefiniteInit, "definite-init","definitive initialization"), clEnumValN(PassKind::InOutDeshadowing, "inout-deshadow", "Remove inout argument shadow variables"), clEnumValN(PassKind::MandatoryInlining, "mandatory-inlining", "Inline transparent functions"), clEnumValN(PassKind::SILSpecialization, "specialize", "Specialize generic functions"), clEnumValN(PassKind::SILDevirt, "devirtualize", "Devirtualize virtual calls"), clEnumValN(PassKind::PredictableMemoryOpt, "predictable-memopt", "Predictable early memory optimization"), clEnumValN(PassKind::SILCombine, "sil-combine", "Perform small peepholes and combine" " operations."), clEnumValN(PassKind::SILDeadFunctionElimination, "sil-deadfuncelim", "Remove private unused functions"), clEnumValN(PassKind::SimplifyCFG, "simplify-cfg", "Clean up the CFG of SIL functions"), clEnumValN(PassKind::PerformanceInlining, "inline", "Inline functions which are determined to be" " less than a pre-set cost."), clEnumValN(PassKind::CodeMotion, "codemotion", "Perform code motion optimizations"), clEnumValN(PassKind::LowerAggregateInstrs, "lower-aggregate-instrs", "Perform lower aggregate instrs to scalar " "instrs."), clEnumValN(PassKind::SROA, "sroa", "Perform SIL scalar replacement of " "aggregates."), clEnumValN(PassKind::ARCOpts, "arc-opts", "Perform automatic reference counting " "optimizations."), clEnumValN(PassKind::StripDebugInfo, "strip-debug-info", "Strip debug info."), clEnumValN(PassKind::DeadObjectElimination, "deadobject-elim", "Eliminate unused object allocation with no " "side effect destructors."), clEnumValN(PassKind::InstCount, "inst-count", "Count all instructions in the given " "module."), clEnumValN(PassKind::AADumper, "aa-dump", "Dump AA result for all pairs of ValueKinds" " in all functions."), clEnumValN(PassKind::LoadStoreOpts, "load-store-opts", "Remove duplicate loads, dead stores, and " "perform load forwarding."), clEnumValEnd)); static llvm::cl::opt<bool> PrintStats("print-stats", llvm::cl::desc("Print various statistics")); static llvm::cl::opt<bool> VerifyMode("verify", llvm::cl::desc("verify diagnostics against expected-" "{error|warning|note} annotations")); static llvm::cl::opt<unsigned> SILInlineThreshold("sil-inline-threshold", llvm::cl::Hidden, llvm::cl::init(50)); static llvm::cl::opt<unsigned> SILDevirtThreshold("sil-devirt-threshold", llvm::cl::Hidden, llvm::cl::init(0)); static llvm::cl::opt<bool> EnableSILVerifyAll("enable-sil-verify-all", llvm::cl::Hidden, llvm::cl::init(true), llvm::cl::desc("Run sil verifications after every pass.")); static llvm::cl::opt<bool> EnableSILPrintAll("-sil-print-all", llvm::cl::Hidden, llvm::cl::init(false), llvm::cl::desc("Print sil after every pass.")); static llvm::cl::opt<bool> EmitVerboseSIL("emit-verbose-sil", llvm::cl::desc("Emit locations during sil emission.")); // This function isn't referenced outside its translation unit, but it // can't use the "static" keyword because its address is used for // getMainExecutable (since some platforms don't support taking the // address of main, and some platforms can't implement getMainExecutable // without being given the address of a function in the main executable). void anchorForGetMainExecutable() {} int main(int argc, char **argv) { // Print a stack trace if we signal out. llvm::sys::PrintStackTraceOnErrorSignal(); llvm::PrettyStackTraceProgram X(argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv, "Swift SIL optimizer\n"); // Call llvm_shutdown() on exit to print stats and free memory. llvm::llvm_shutdown_obj Y; if (PrintStats) llvm::EnableStatistics(); CompilerInvocation Invocation; Invocation.setMainExecutablePath( llvm::sys::fs::getMainExecutable(argv[0], reinterpret_cast<void *>(&anchorForGetMainExecutable))); // Give the context the list of search paths to use for modules. Invocation.setImportSearchPaths(ImportPaths); Invocation.setModuleName("main"); Invocation.setInputKind(SourceFileKind::SIL); Invocation.addInputFilename(InputFilename); CompilerInstance CI; PrintingDiagnosticConsumer PrintDiags; CI.addDiagnosticConsumer(&PrintDiags); if (CI.setup(Invocation)) return 1; CI.performParse(); // If parsing produced an error, don't run any passes. if (CI.getASTContext().hadError()) return 1; // If we're in verify mode, install a custom diagnostic handling for // SourceMgr. if (VerifyMode) enableDiagnosticVerifier(CI.getSourceMgr()); SILOptions &SILOpts = Invocation.getSILOptions(); SILOpts.InlineThreshold = SILInlineThreshold; SILOpts.DevirtThreshold = SILDevirtThreshold; SILOpts.VerifyAll = EnableSILVerifyAll; SILOpts.PrintAll = EnableSILPrintAll; SILPassManager PM(CI.getSILModule(), SILOpts); PM.registerAnalysis(createCallGraphAnalysis(CI.getSILModule())); PM.registerAnalysis(createAliasAnalysis(CI.getSILModule())); PM.registerAnalysis(createDominanceAnalysis(CI.getSILModule())); PM.registerAnalysis(createSpecializedArgsAnalysis(CI.getSILModule())); for (auto Pass : Passes) { switch (Pass) { case PassKind::AllocBoxToStack: PM.add(createAllocBoxToStack()); break; case PassKind::CapturePromotion: PM.add(createCapturePromotion()); break; case PassKind::CCP: PM.add(createConstantPropagation()); break; case PassKind::CSE: PM.add(createCSE()); break; case PassKind::DCE: PM.add(createDCE()); break; case PassKind::DefiniteInit: PM.add(createDefiniteInitialization()); break; case PassKind::DataflowDiagnostics: PM.add(createEmitDFDiagnostics()); break; case PassKind::InOutDeshadowing: PM.add(createInOutDeshadowing()); break; case PassKind::MandatoryInlining: PM.add(createMandatoryInlining()); break; case PassKind::PredictableMemoryOpt: PM.add(createPredictableMemoryOptimizations()); break; case PassKind::SILCleanup: PM.add(createSILCleanup()); break; case PassKind::SILMem2Reg: PM.add(createMem2Reg()); break; case PassKind::SILCombine: PM.add(createSILCombine()); break; case PassKind::SILDeadFunctionElimination: PM.add(createDeadFunctionElimination()); break; case PassKind::SILSpecialization: PM.add(createGenericSpecializer()); break; case PassKind::SILDevirt: PM.add(createDevirtualization()); break; case PassKind::SimplifyCFG: PM.add(createSimplifyCFG()); break; case PassKind::PerformanceInlining: PM.add(createPerfInliner()); break; case PassKind::CodeMotion: PM.add(createCodeMotion()); break; case PassKind::LowerAggregateInstrs: PM.add(createLowerAggregate()); break; case PassKind::SROA: PM.add(createSROA()); break; case PassKind::ARCOpts: PM.add(createARCOpts()); break; case PassKind::StripDebugInfo: PM.add(createStripDebug()); break; case PassKind::DeadObjectElimination: PM.add(createDeadObjectElimination()); break; case PassKind::InstCount: PM.add(createSILInstCount()); break; case PassKind::AADumper: PM.add(createSILAADumper()); break; case PassKind::LoadStoreOpts: PM.add(createLoadStoreOpts()); break; } } PM.run(); std::string ErrorInfo; llvm::raw_fd_ostream OS(OutputFilename.c_str(), ErrorInfo); if (!ErrorInfo.empty()) { llvm::errs() << "while opening '" << OutputFilename << "': " << ErrorInfo << '\n'; return 1; } CI.getSILModule()->print(OS, EmitVerboseSIL, CI.getMainModule()); bool HadError = CI.getASTContext().hadError(); // If we're in -verify mode, we've buffered up all of the generated // diagnostics. Check now to ensure that they meet our expectations. if (VerifyMode) HadError = verifyDiagnostics(CI.getSourceMgr(), CI.getInputBufferIDs()); return HadError; } <|endoftext|>
<commit_before>#include <pamix.hpp> #include <unistd.h> #include <configuration.hpp> #include <condition_variable> #include <queue> #include <csignal> // GLOBAL VARIABLES Configuration configuration; bool running = true; // sync main and callback threads std::mutex updMutex; std::condition_variable cv; std::queue<UpdateData> updateDataQ; void quit() { running = false; signal_update(false); } void __signal_update(bool all) { { std::lock_guard<std::mutex> lk(updMutex); updateDataQ.push(UpdateData(all)); } cv.notify_one(); } void signal_update(bool all, bool threaded) { if (threaded) std::thread(__signal_update, all).detach(); else __signal_update(all); } void set_volume(pamix_ui *ui, double pct) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->setVolume(it->second->m_Lock ? -1 : (int) ui->m_SelectedChannel, (pa_volume_t) (PA_VOLUME_NORM * pct)); } void add_volume(pamix_ui *ui, double pct) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->addVolume(it->second->m_Lock ? -1 : (int) ui->m_SelectedChannel, pct); } void cycle_switch(pamix_ui *ui, bool increment) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->cycleSwitch(increment); } void set_mute(pamix_ui *ui, bool mute) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->setMute(mute); } void toggle_mute(pamix_ui *ui) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->setMute(!it->second->m_Mute); } void set_lock(pamix_ui *ui, bool lock) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->m_Lock = lock; } void toggle_lock(pamix_ui *ui) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->m_Lock = !it->second->m_Lock; } void inputThread(pamix_ui *ui) { while (running) { int ch = ui->getKeyInput(); bool isValidKey = ch != ERR && ch != KEY_RESIZE && ch != KEY_MOUSE; //if (isValidKey && ui->m_paInterface->isConnected()) { if (isValidKey) { configuration.pressKey(ch); } usleep(2000); } } void pai_subscription(PAInterface *, pai_subscription_type_t type) { bool updAll = (type & PAI_SUBSCRIPTION_MASK_INFO) != 0 || (type & PAI_SUBSCRIPTION_MASK_CONNECTION_STATUS) != 0; signal_update(updAll); } void sig_handle_resize(int) { endwin(); refresh(); signal_update(true, true); } void init_colors() { start_color(); init_pair(1, COLOR_GREEN, 0); init_pair(2, COLOR_YELLOW, 0); init_pair(3, COLOR_RED, 0); } void sig_handle(int) { endwin(); } void loadConfiguration() { char *home = getenv("HOME"); char *xdg_config_home = getenv("XDG_CONFIG_HOME"); std::string path; path = xdg_config_home ? xdg_config_home : std::string(home) += "/.config"; path += "/pamix.conf"; if (Configuration::loadFile(&configuration, path)) return; char *xdg_config_dirs = getenv("XDG_CONFIG_DIRS"); path = xdg_config_dirs ? xdg_config_dirs : "/etc"; path += "/pamix.conf"; size_t cpos = path.find(':'); while (cpos != std::string::npos) { if (Configuration::loadFile(&configuration, path.substr(0, cpos))) return; path = path.substr(cpos + 1, path.length() - cpos - 1); cpos = path.find(':'); } if (Configuration::loadFile(&configuration, path)) return; // if config file cant be loaded, use default bindings configuration.bind("q", "quit"); configuration.bind("KEY_F(1)", "select-tab", "2"); configuration.bind("KEY_F(2)", "select-tab", "3"); configuration.bind("KEY_F(3)", "select-tab", "0"); configuration.bind("KEY_F(4)", "select-tab", "1"); configuration.bind("j", "select-next", "channel"); configuration.bind("KEY_DOWN", "select-next", "channel"); configuration.bind("J", "select-next"); configuration.bind("k", "select-prev", "channel"); configuration.bind("KEY_UP", "select-prev", "channel"); configuration.bind("K", "select-prev"); configuration.bind("h", "add-volume", "-0.05"); configuration.bind("KEY_LEFT", "add-volume", "-0.05"); configuration.bind("l", "add-volume", "0.05"); configuration.bind("KEY_RIGHT", "add-volume", "0.05"); configuration.bind("s", "cycle-next"); configuration.bind("S", "cycle-prev"); configuration.bind("c", "toggle-lock"); configuration.bind("m", "toggle-mute"); configuration.bind("1", "set-volume", "0.1"); configuration.bind("2", "set-volume", "0.2"); configuration.bind("3", "set-volume", "0.3"); configuration.bind("4", "set-volume", "0.4"); configuration.bind("5", "set-volume", "0.5"); configuration.bind("6", "set-volume", "0.6"); configuration.bind("7", "set-volume", "0.7"); configuration.bind("8", "set-volume", "0.8"); configuration.bind("9", "set-volume", "0.9"); configuration.bind("0", "set-volume", "1.0"); } void interfaceReconnectThread(PAInterface *interface) { while (running) { if (!interface->isConnected()) { interface->connect(); signal_update(true); } sleep(5); } } void handleArguments(int argc, char **argv) { for (int i = 1; i < argc; i++) { std::string arg = argv[i]; if (arg == "--version") { printf("PAmix v%s\n", GIT_VERSION); exit(0); } } } int main(int argc, char **argv) { handleArguments(argc, argv); loadConfiguration(); setlocale(LC_ALL, ""); initscr(); init_colors(); nodelay(stdscr, true); curs_set(0); keypad(stdscr, true); meta(stdscr, true); noecho(); signal(SIGABRT, sig_handle); signal(SIGSEGV, sig_handle); signal(SIGWINCH, sig_handle_resize); PAInterface pai("pamix"); pamix_ui pamixUi(&pai); if (configuration.has(CONFIGURATION_AUTOSPAWN_PULSE)) pai.setAutospawn(configuration.getBool(CONFIGURATION_AUTOSPAWN_PULSE)); entry_type initialEntryType = ENTRY_SINKINPUT; if (configuration.has(CONFIGURATION_DEFAULT_TAB)) { int value = configuration.getInt(CONFIGURATION_DEFAULT_TAB); if (value >= 0 && value < ENTRY_COUNT) initialEntryType = (entry_type) value; } pamixUi.selectEntries(initialEntryType); pai.subscribe(&pai_subscription); pai.connect(); pamix_setup(&pamixUi); pamixUi.redrawAll(); std::thread(&interfaceReconnectThread, &pai).detach(); std::thread inputT(inputThread, &pamixUi); inputT.detach(); while (running) { std::unique_lock<std::mutex> lk(updMutex); cv.wait(lk, [] { return !updateDataQ.empty(); }); if (updateDataQ.front().redrawAll) pamixUi.redrawAll(); else pamixUi.redrawVolumeBars(); updateDataQ.pop(); } endwin(); return 0; } <commit_msg>change default XDG_CONFIG_DIRS value when searching config file<commit_after>#include <pamix.hpp> #include <unistd.h> #include <configuration.hpp> #include <condition_variable> #include <queue> #include <csignal> // GLOBAL VARIABLES Configuration configuration; bool running = true; // sync main and callback threads std::mutex updMutex; std::condition_variable cv; std::queue<UpdateData> updateDataQ; void quit() { running = false; signal_update(false); } void __signal_update(bool all) { { std::lock_guard<std::mutex> lk(updMutex); updateDataQ.push(UpdateData(all)); } cv.notify_one(); } void signal_update(bool all, bool threaded) { if (threaded) std::thread(__signal_update, all).detach(); else __signal_update(all); } void set_volume(pamix_ui *ui, double pct) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->setVolume(it->second->m_Lock ? -1 : (int) ui->m_SelectedChannel, (pa_volume_t) (PA_VOLUME_NORM * pct)); } void add_volume(pamix_ui *ui, double pct) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->addVolume(it->second->m_Lock ? -1 : (int) ui->m_SelectedChannel, pct); } void cycle_switch(pamix_ui *ui, bool increment) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->cycleSwitch(increment); } void set_mute(pamix_ui *ui, bool mute) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->setMute(mute); } void toggle_mute(pamix_ui *ui) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->setMute(!it->second->m_Mute); } void set_lock(pamix_ui *ui, bool lock) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->m_Lock = lock; } void toggle_lock(pamix_ui *ui) { auto it = ui->getSelectedEntryIterator(); if (it != ui->m_Entries->end()) it->second->m_Lock = !it->second->m_Lock; } void inputThread(pamix_ui *ui) { while (running) { int ch = ui->getKeyInput(); bool isValidKey = ch != ERR && ch != KEY_RESIZE && ch != KEY_MOUSE; //if (isValidKey && ui->m_paInterface->isConnected()) { if (isValidKey) { configuration.pressKey(ch); } usleep(2000); } } void pai_subscription(PAInterface *, pai_subscription_type_t type) { bool updAll = (type & PAI_SUBSCRIPTION_MASK_INFO) != 0 || (type & PAI_SUBSCRIPTION_MASK_CONNECTION_STATUS) != 0; signal_update(updAll); } void sig_handle_resize(int) { endwin(); refresh(); signal_update(true, true); } void init_colors() { start_color(); init_pair(1, COLOR_GREEN, 0); init_pair(2, COLOR_YELLOW, 0); init_pair(3, COLOR_RED, 0); } void sig_handle(int) { endwin(); } void loadConfiguration() { char *home = getenv("HOME"); char *xdg_config_home = getenv("XDG_CONFIG_HOME"); std::string path; path = xdg_config_home ? xdg_config_home : std::string(home) += "/.config"; path += "/pamix.conf"; if (Configuration::loadFile(&configuration, path)) return; char *xdg_config_dirs = getenv("XDG_CONFIG_DIRS"); path = xdg_config_dirs ? xdg_config_dirs : "/etc/xdg"; path += "/pamix.conf"; size_t cpos = path.find(':'); while (cpos != std::string::npos) { if (Configuration::loadFile(&configuration, path.substr(0, cpos))) return; path = path.substr(cpos + 1, path.length() - cpos - 1); cpos = path.find(':'); } if (Configuration::loadFile(&configuration, path)) return; // if config file cant be loaded, use default bindings configuration.bind("q", "quit"); configuration.bind("KEY_F(1)", "select-tab", "2"); configuration.bind("KEY_F(2)", "select-tab", "3"); configuration.bind("KEY_F(3)", "select-tab", "0"); configuration.bind("KEY_F(4)", "select-tab", "1"); configuration.bind("j", "select-next", "channel"); configuration.bind("KEY_DOWN", "select-next", "channel"); configuration.bind("J", "select-next"); configuration.bind("k", "select-prev", "channel"); configuration.bind("KEY_UP", "select-prev", "channel"); configuration.bind("K", "select-prev"); configuration.bind("h", "add-volume", "-0.05"); configuration.bind("KEY_LEFT", "add-volume", "-0.05"); configuration.bind("l", "add-volume", "0.05"); configuration.bind("KEY_RIGHT", "add-volume", "0.05"); configuration.bind("s", "cycle-next"); configuration.bind("S", "cycle-prev"); configuration.bind("c", "toggle-lock"); configuration.bind("m", "toggle-mute"); configuration.bind("1", "set-volume", "0.1"); configuration.bind("2", "set-volume", "0.2"); configuration.bind("3", "set-volume", "0.3"); configuration.bind("4", "set-volume", "0.4"); configuration.bind("5", "set-volume", "0.5"); configuration.bind("6", "set-volume", "0.6"); configuration.bind("7", "set-volume", "0.7"); configuration.bind("8", "set-volume", "0.8"); configuration.bind("9", "set-volume", "0.9"); configuration.bind("0", "set-volume", "1.0"); } void interfaceReconnectThread(PAInterface *interface) { while (running) { if (!interface->isConnected()) { interface->connect(); signal_update(true); } sleep(5); } } void handleArguments(int argc, char **argv) { for (int i = 1; i < argc; i++) { std::string arg = argv[i]; if (arg == "--version") { printf("PAmix v%s\n", GIT_VERSION); exit(0); } } } int main(int argc, char **argv) { handleArguments(argc, argv); loadConfiguration(); setlocale(LC_ALL, ""); initscr(); init_colors(); nodelay(stdscr, true); curs_set(0); keypad(stdscr, true); meta(stdscr, true); noecho(); signal(SIGABRT, sig_handle); signal(SIGSEGV, sig_handle); signal(SIGWINCH, sig_handle_resize); PAInterface pai("pamix"); pamix_ui pamixUi(&pai); if (configuration.has(CONFIGURATION_AUTOSPAWN_PULSE)) pai.setAutospawn(configuration.getBool(CONFIGURATION_AUTOSPAWN_PULSE)); entry_type initialEntryType = ENTRY_SINKINPUT; if (configuration.has(CONFIGURATION_DEFAULT_TAB)) { int value = configuration.getInt(CONFIGURATION_DEFAULT_TAB); if (value >= 0 && value < ENTRY_COUNT) initialEntryType = (entry_type) value; } pamixUi.selectEntries(initialEntryType); pai.subscribe(&pai_subscription); pai.connect(); pamix_setup(&pamixUi); pamixUi.redrawAll(); std::thread(&interfaceReconnectThread, &pai).detach(); std::thread inputT(inputThread, &pamixUi); inputT.detach(); while (running) { std::unique_lock<std::mutex> lk(updMutex); cv.wait(lk, [] { return !updateDataQ.empty(); }); if (updateDataQ.front().redrawAll) pamixUi.redrawAll(); else pamixUi.redrawVolumeBars(); updateDataQ.pop(); } endwin(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkBitmapCache.h" #include "SkCanvas.h" #include "SkDiscardableMemoryPool.h" #include "SkGraphics.h" #include "SkResourceCache.h" #include "SkSurface.h" static const int kCanvasSize = 1; static const int kBitmapSize = 16; static const int kScale = 8; static bool is_in_scaled_image_cache(const SkBitmap& orig, SkScalar xScale, SkScalar yScale) { SkBitmap scaled; int width = SkScalarRoundToInt(orig.width() * xScale); int height = SkScalarRoundToInt(orig.height() * yScale); return SkBitmapCache::FindWH(SkBitmapCacheDesc::Make(orig, width, height), &scaled); } // Draw a scaled bitmap, then return true if it has been cached. static bool test_scaled_image_cache_usage() { SkAutoTUnref<SkSurface> surface(SkSurface::NewRasterN32Premul(kCanvasSize, kCanvasSize)); SkCanvas* canvas = surface->getCanvas(); SkBitmap bitmap; bitmap.allocN32Pixels(kBitmapSize, kBitmapSize); bitmap.eraseColor(0xFFFFFFFF); SkScalar xScale = SkIntToScalar(kScale); SkScalar yScale = xScale / 2; SkScalar xScaledSize = SkIntToScalar(kBitmapSize) * xScale; SkScalar yScaledSize = SkIntToScalar(kBitmapSize) * yScale; canvas->clipRect(SkRect::MakeLTRB(0, 0, xScaledSize, yScaledSize)); SkPaint paint; paint.setFilterQuality(kHigh_SkFilterQuality); canvas->drawBitmapRect(bitmap, SkRect::MakeLTRB(0, 0, xScaledSize, yScaledSize), &paint); return is_in_scaled_image_cache(bitmap, xScale, yScale); } // http://crbug.com/389439 DEF_TEST(ResourceCache_SingleAllocationByteLimit, reporter) { size_t originalByteLimit = SkGraphics::GetResourceCacheTotalByteLimit(); size_t originalAllocationLimit = SkGraphics::GetResourceCacheSingleAllocationByteLimit(); size_t size = kBitmapSize * kScale * kBitmapSize * kScale * SkColorTypeBytesPerPixel(kN32_SkColorType); SkGraphics::SetResourceCacheTotalByteLimit(0); // clear cache SkGraphics::SetResourceCacheTotalByteLimit(2 * size); SkGraphics::SetResourceCacheSingleAllocationByteLimit(0); // No limit REPORTER_ASSERT(reporter, test_scaled_image_cache_usage()); SkGraphics::SetResourceCacheTotalByteLimit(0); // clear cache SkGraphics::SetResourceCacheTotalByteLimit(2 * size); SkGraphics::SetResourceCacheSingleAllocationByteLimit(size * 2); // big enough REPORTER_ASSERT(reporter, test_scaled_image_cache_usage()); SkGraphics::SetResourceCacheTotalByteLimit(0); // clear cache SkGraphics::SetResourceCacheTotalByteLimit(2 * size); SkGraphics::SetResourceCacheSingleAllocationByteLimit(size / 2); // too small REPORTER_ASSERT(reporter, !test_scaled_image_cache_usage()); SkGraphics::SetResourceCacheSingleAllocationByteLimit(originalAllocationLimit); SkGraphics::SetResourceCacheTotalByteLimit(originalByteLimit); } //////////////////////////////////////////////////////////////////////////////////////// static void make_bitmap(SkBitmap* bitmap, const SkImageInfo& info, SkBitmap::Allocator* allocator) { if (allocator) { bitmap->setInfo(info); allocator->allocPixelRef(bitmap, 0); } else { bitmap->allocPixels(info); } } // http://skbug.com/2894 DEF_TEST(BitmapCache_add_rect, reporter) { SkResourceCache::DiscardableFactory factory = SkResourceCache::GetDiscardableFactory(); SkBitmap::Allocator* allocator = SkBitmapCache::GetAllocator(); SkAutoTDelete<SkResourceCache> cache; if (factory) { cache.reset(new SkResourceCache(factory)); } else { const size_t byteLimit = 100 * 1024; cache.reset(new SkResourceCache(byteLimit)); } SkBitmap cachedBitmap; make_bitmap(&cachedBitmap, SkImageInfo::MakeN32Premul(5, 5), allocator); cachedBitmap.setImmutable(); SkBitmap bm; SkIRect rect = SkIRect::MakeWH(5, 5); uint32_t cachedID = cachedBitmap.getGenerationID(); SkPixelRef* cachedPR = cachedBitmap.pixelRef(); // Wrong subset size REPORTER_ASSERT(reporter, !SkBitmapCache::Add(cachedPR, SkIRect::MakeWH(4, 6), cachedBitmap, cache)); REPORTER_ASSERT(reporter, !SkBitmapCache::Find(cachedID, rect, &bm, cache)); // Wrong offset value REPORTER_ASSERT(reporter, !SkBitmapCache::Add(cachedPR, SkIRect::MakeXYWH(-1, 0, 5, 5), cachedBitmap, cache)); REPORTER_ASSERT(reporter, !SkBitmapCache::Find(cachedID, rect, &bm, cache)); // Should not be in the cache REPORTER_ASSERT(reporter, !SkBitmapCache::Find(cachedID, rect, &bm, cache)); REPORTER_ASSERT(reporter, SkBitmapCache::Add(cachedPR, rect, cachedBitmap, cache)); // Should be in the cache, we just added it REPORTER_ASSERT(reporter, SkBitmapCache::Find(cachedID, rect, &bm, cache)); } #include "SkMipMap.h" enum LockedState { kNotLocked, kLocked, }; enum CachedState { kNotInCache, kInCache, }; static void check_data(skiatest::Reporter* reporter, const SkCachedData* data, int refcnt, CachedState cacheState, LockedState lockedState) { REPORTER_ASSERT(reporter, data->testing_only_getRefCnt() == refcnt); REPORTER_ASSERT(reporter, data->testing_only_isInCache() == (kInCache == cacheState)); bool isLocked = (data->data() != nullptr); REPORTER_ASSERT(reporter, isLocked == (lockedState == kLocked)); } static void test_mipmapcache(skiatest::Reporter* reporter, SkResourceCache* cache) { cache->purgeAll(); SkBitmap src; src.allocN32Pixels(5, 5); src.setImmutable(); const SkMipMap* mipmap = SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(src), cache); REPORTER_ASSERT(reporter, nullptr == mipmap); mipmap = SkMipMapCache::AddAndRef(src, cache); REPORTER_ASSERT(reporter, mipmap); { const SkMipMap* mm = SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(src), cache); REPORTER_ASSERT(reporter, mm); REPORTER_ASSERT(reporter, mm == mipmap); mm->unref(); } check_data(reporter, mipmap, 2, kInCache, kLocked); mipmap->unref(); // tricky, since technically after this I'm no longer an owner, but since the cache is // local, I know it won't get purged behind my back check_data(reporter, mipmap, 1, kInCache, kNotLocked); // find us again mipmap = SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(src), cache); check_data(reporter, mipmap, 2, kInCache, kLocked); cache->purgeAll(); check_data(reporter, mipmap, 1, kNotInCache, kLocked); mipmap->unref(); } static void test_mipmap_notify(skiatest::Reporter* reporter, SkResourceCache* cache) { const int N = 3; SkBitmap src[N]; for (int i = 0; i < N; ++i) { src[i].allocN32Pixels(5, 5); src[i].setImmutable(); SkMipMapCache::AddAndRef(src[i], cache)->unref(); } for (int i = 0; i < N; ++i) { const SkMipMap* mipmap = SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(src[i]), cache); if (cache) { // if cache is null, we're working on the global cache, and other threads might purge // it, making this check fragile. REPORTER_ASSERT(reporter, mipmap); } SkSafeUnref(mipmap); src[i].reset(); // delete the underlying pixelref, which *should* remove us from the cache mipmap = SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(src[i]), cache); REPORTER_ASSERT(reporter, !mipmap); } } static void test_bitmap_notify(skiatest::Reporter* reporter, SkResourceCache* cache) { const SkIRect subset = SkIRect::MakeWH(5, 5); const int N = 3; SkBitmap src[N], dst[N]; for (int i = 0; i < N; ++i) { src[i].allocN32Pixels(5, 5); src[i].setImmutable(); dst[i].allocN32Pixels(5, 5); dst[i].setImmutable(); SkBitmapCache::Add(src[i].pixelRef(), subset, dst[i], cache); } for (int i = 0; i < N; ++i) { const uint32_t genID = src[i].getGenerationID(); SkBitmap result; bool found = SkBitmapCache::Find(genID, subset, &result, cache); if (cache) { // if cache is null, we're working on the global cache, and other threads might purge // it, making this check fragile. REPORTER_ASSERT(reporter, found); } src[i].reset(); // delete the underlying pixelref, which *should* remove us from the cache found = SkBitmapCache::Find(genID, subset, &result, cache); REPORTER_ASSERT(reporter, !found); } } DEF_TEST(BitmapCache_discarded_bitmap, reporter) { SkResourceCache::DiscardableFactory factory = SkResourceCache::GetDiscardableFactory(); SkBitmap::Allocator* allocator = SkBitmapCache::GetAllocator(); SkAutoTDelete<SkResourceCache> cache; if (factory) { cache.reset(new SkResourceCache(factory)); } else { const size_t byteLimit = 100 * 1024; cache.reset(new SkResourceCache(byteLimit)); } SkBitmap cachedBitmap; make_bitmap(&cachedBitmap, SkImageInfo::MakeN32Premul(5, 5), allocator); cachedBitmap.setImmutable(); cachedBitmap.unlockPixels(); SkBitmap bm; SkIRect rect = SkIRect::MakeWH(5, 5); // Add a bitmap to the cache. REPORTER_ASSERT(reporter, SkBitmapCache::Add(cachedBitmap.pixelRef(), rect, cachedBitmap, cache)); REPORTER_ASSERT(reporter, SkBitmapCache::Find(cachedBitmap.getGenerationID(), rect, &bm, cache)); // Finding more than once works fine. REPORTER_ASSERT(reporter, SkBitmapCache::Find(cachedBitmap.getGenerationID(), rect, &bm, cache)); bm.unlockPixels(); // Drop the pixels in the bitmap. if (factory) { REPORTER_ASSERT(reporter, SkGetGlobalDiscardableMemoryPool()->getRAMUsed() > 0); SkGetGlobalDiscardableMemoryPool()->dumpPool(); REPORTER_ASSERT(reporter, SkGetGlobalDiscardableMemoryPool()->getRAMUsed() == 0); // The bitmap is not in the cache since it has been dropped. REPORTER_ASSERT(reporter, !SkBitmapCache::Find(cachedBitmap.getGenerationID(), rect, &bm, cache)); } make_bitmap(&cachedBitmap, SkImageInfo::MakeN32Premul(5, 5), allocator); cachedBitmap.setImmutable(); cachedBitmap.unlockPixels(); // We can add the bitmap back to the cache and find it again. REPORTER_ASSERT(reporter, SkBitmapCache::Add(cachedBitmap.pixelRef(), rect, cachedBitmap, cache)); REPORTER_ASSERT(reporter, SkBitmapCache::Find(cachedBitmap.getGenerationID(), rect, &bm, cache)); test_mipmapcache(reporter, cache); test_bitmap_notify(reporter, cache); test_mipmap_notify(reporter, cache); } <commit_msg>remove racy tests, as they assume the cache can't be purged behind their back<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkBitmapCache.h" #include "SkCanvas.h" #include "SkDiscardableMemoryPool.h" #include "SkGraphics.h" #include "SkResourceCache.h" #include "SkSurface.h" //////////////////////////////////////////////////////////////////////////////////////// static void make_bitmap(SkBitmap* bitmap, const SkImageInfo& info, SkBitmap::Allocator* allocator) { if (allocator) { bitmap->setInfo(info); allocator->allocPixelRef(bitmap, 0); } else { bitmap->allocPixels(info); } } // http://skbug.com/2894 DEF_TEST(BitmapCache_add_rect, reporter) { SkResourceCache::DiscardableFactory factory = SkResourceCache::GetDiscardableFactory(); SkBitmap::Allocator* allocator = SkBitmapCache::GetAllocator(); SkAutoTDelete<SkResourceCache> cache; if (factory) { cache.reset(new SkResourceCache(factory)); } else { const size_t byteLimit = 100 * 1024; cache.reset(new SkResourceCache(byteLimit)); } SkBitmap cachedBitmap; make_bitmap(&cachedBitmap, SkImageInfo::MakeN32Premul(5, 5), allocator); cachedBitmap.setImmutable(); SkBitmap bm; SkIRect rect = SkIRect::MakeWH(5, 5); uint32_t cachedID = cachedBitmap.getGenerationID(); SkPixelRef* cachedPR = cachedBitmap.pixelRef(); // Wrong subset size REPORTER_ASSERT(reporter, !SkBitmapCache::Add(cachedPR, SkIRect::MakeWH(4, 6), cachedBitmap, cache)); REPORTER_ASSERT(reporter, !SkBitmapCache::Find(cachedID, rect, &bm, cache)); // Wrong offset value REPORTER_ASSERT(reporter, !SkBitmapCache::Add(cachedPR, SkIRect::MakeXYWH(-1, 0, 5, 5), cachedBitmap, cache)); REPORTER_ASSERT(reporter, !SkBitmapCache::Find(cachedID, rect, &bm, cache)); // Should not be in the cache REPORTER_ASSERT(reporter, !SkBitmapCache::Find(cachedID, rect, &bm, cache)); REPORTER_ASSERT(reporter, SkBitmapCache::Add(cachedPR, rect, cachedBitmap, cache)); // Should be in the cache, we just added it REPORTER_ASSERT(reporter, SkBitmapCache::Find(cachedID, rect, &bm, cache)); } #include "SkMipMap.h" enum LockedState { kNotLocked, kLocked, }; enum CachedState { kNotInCache, kInCache, }; static void check_data(skiatest::Reporter* reporter, const SkCachedData* data, int refcnt, CachedState cacheState, LockedState lockedState) { REPORTER_ASSERT(reporter, data->testing_only_getRefCnt() == refcnt); REPORTER_ASSERT(reporter, data->testing_only_isInCache() == (kInCache == cacheState)); bool isLocked = (data->data() != nullptr); REPORTER_ASSERT(reporter, isLocked == (lockedState == kLocked)); } static void test_mipmapcache(skiatest::Reporter* reporter, SkResourceCache* cache) { cache->purgeAll(); SkBitmap src; src.allocN32Pixels(5, 5); src.setImmutable(); const SkMipMap* mipmap = SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(src), cache); REPORTER_ASSERT(reporter, nullptr == mipmap); mipmap = SkMipMapCache::AddAndRef(src, cache); REPORTER_ASSERT(reporter, mipmap); { const SkMipMap* mm = SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(src), cache); REPORTER_ASSERT(reporter, mm); REPORTER_ASSERT(reporter, mm == mipmap); mm->unref(); } check_data(reporter, mipmap, 2, kInCache, kLocked); mipmap->unref(); // tricky, since technically after this I'm no longer an owner, but since the cache is // local, I know it won't get purged behind my back check_data(reporter, mipmap, 1, kInCache, kNotLocked); // find us again mipmap = SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(src), cache); check_data(reporter, mipmap, 2, kInCache, kLocked); cache->purgeAll(); check_data(reporter, mipmap, 1, kNotInCache, kLocked); mipmap->unref(); } static void test_mipmap_notify(skiatest::Reporter* reporter, SkResourceCache* cache) { const int N = 3; SkBitmap src[N]; for (int i = 0; i < N; ++i) { src[i].allocN32Pixels(5, 5); src[i].setImmutable(); SkMipMapCache::AddAndRef(src[i], cache)->unref(); } for (int i = 0; i < N; ++i) { const SkMipMap* mipmap = SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(src[i]), cache); if (cache) { // if cache is null, we're working on the global cache, and other threads might purge // it, making this check fragile. REPORTER_ASSERT(reporter, mipmap); } SkSafeUnref(mipmap); src[i].reset(); // delete the underlying pixelref, which *should* remove us from the cache mipmap = SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(src[i]), cache); REPORTER_ASSERT(reporter, !mipmap); } } static void test_bitmap_notify(skiatest::Reporter* reporter, SkResourceCache* cache) { const SkIRect subset = SkIRect::MakeWH(5, 5); const int N = 3; SkBitmap src[N], dst[N]; for (int i = 0; i < N; ++i) { src[i].allocN32Pixels(5, 5); src[i].setImmutable(); dst[i].allocN32Pixels(5, 5); dst[i].setImmutable(); SkBitmapCache::Add(src[i].pixelRef(), subset, dst[i], cache); } for (int i = 0; i < N; ++i) { const uint32_t genID = src[i].getGenerationID(); SkBitmap result; bool found = SkBitmapCache::Find(genID, subset, &result, cache); if (cache) { // if cache is null, we're working on the global cache, and other threads might purge // it, making this check fragile. REPORTER_ASSERT(reporter, found); } src[i].reset(); // delete the underlying pixelref, which *should* remove us from the cache found = SkBitmapCache::Find(genID, subset, &result, cache); REPORTER_ASSERT(reporter, !found); } } DEF_TEST(BitmapCache_discarded_bitmap, reporter) { SkResourceCache::DiscardableFactory factory = SkResourceCache::GetDiscardableFactory(); SkBitmap::Allocator* allocator = SkBitmapCache::GetAllocator(); SkAutoTDelete<SkResourceCache> cache; if (factory) { cache.reset(new SkResourceCache(factory)); } else { const size_t byteLimit = 100 * 1024; cache.reset(new SkResourceCache(byteLimit)); } SkBitmap cachedBitmap; make_bitmap(&cachedBitmap, SkImageInfo::MakeN32Premul(5, 5), allocator); cachedBitmap.setImmutable(); cachedBitmap.unlockPixels(); SkBitmap bm; SkIRect rect = SkIRect::MakeWH(5, 5); // Add a bitmap to the cache. REPORTER_ASSERT(reporter, SkBitmapCache::Add(cachedBitmap.pixelRef(), rect, cachedBitmap, cache)); REPORTER_ASSERT(reporter, SkBitmapCache::Find(cachedBitmap.getGenerationID(), rect, &bm, cache)); // Finding more than once works fine. REPORTER_ASSERT(reporter, SkBitmapCache::Find(cachedBitmap.getGenerationID(), rect, &bm, cache)); bm.unlockPixels(); // Drop the pixels in the bitmap. if (factory) { REPORTER_ASSERT(reporter, SkGetGlobalDiscardableMemoryPool()->getRAMUsed() > 0); SkGetGlobalDiscardableMemoryPool()->dumpPool(); // The bitmap is not in the cache since it has been dropped. REPORTER_ASSERT(reporter, !SkBitmapCache::Find(cachedBitmap.getGenerationID(), rect, &bm, cache)); } make_bitmap(&cachedBitmap, SkImageInfo::MakeN32Premul(5, 5), allocator); cachedBitmap.setImmutable(); cachedBitmap.unlockPixels(); // We can add the bitmap back to the cache and find it again. REPORTER_ASSERT(reporter, SkBitmapCache::Add(cachedBitmap.pixelRef(), rect, cachedBitmap, cache)); REPORTER_ASSERT(reporter, SkBitmapCache::Find(cachedBitmap.getGenerationID(), rect, &bm, cache)); test_mipmapcache(reporter, cache); test_bitmap_notify(reporter, cache); test_mipmap_notify(reporter, cache); } <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2018 whitequark <whitequark@whitequark.org> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct EquivOptPass:public ScriptPass { EquivOptPass() : ScriptPass("equiv_opt", "prove equivalence for optimized circuit") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" equiv_opt [options] [command]\n"); log("\n"); log("This command uses temporal induction to check circuit equivalence before and\n"); log("after an optimization pass.\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to the start of the command list, and empty to\n"); log(" label is synonymous to the end of the command list.\n"); log("\n"); log(" -map <filename>\n"); log(" expand the modules in this file before proving equivalence. this is\n"); log(" useful for handling architecture-specific primitives.\n"); log("\n"); log(" -assert\n"); log(" produce an error if the circuits are not equivalent.\n"); log("\n"); log(" -multiclock\n"); log(" run clk2fflogic before equivalence checking.\n"); log("\n"); log(" -undef\n"); log(" enable modelling of undef states during equiv_induct.\n"); log("\n"); log("The following commands are executed by this verification command:\n"); help_script(); log("\n"); } std::string command, techmap_opts; bool assert, undef, multiclock; void clear_flags() YS_OVERRIDE { command = ""; techmap_opts = ""; assert = false; undef = false; multiclock = false; } void execute(std::vector < std::string > args, RTLIL::Design * design) YS_OVERRIDE { string run_from, run_to; clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-run" && argidx + 1 < args.size()) { size_t pos = args[argidx + 1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos + 1); continue; } if (args[argidx] == "-map" && argidx + 1 < args.size()) { techmap_opts += " -map " + args[++argidx]; continue; } if (args[argidx] == "-assert") { assert = true; continue; } if (args[argidx] == "-undef") { undef = true; continue; } if (args[argidx] == "-multiclock") { multiclock = true; continue; } break; } for (; argidx < args.size(); argidx++) { if (command.empty()) { if (args[argidx].compare(0, 1, "-") == 0) cmd_error(args, argidx, "Unknown option."); } else { command += " "; } command += args[argidx]; } if (command.empty()) log_cmd_error("No optimization pass specified!\n"); if (!design->full_selection()) log_cmd_error("This command only operates on fully selected designs!\n"); log_header(design, "Executing EQUIV_OPT pass.\n"); log_push(); run_script(design, run_from, run_to); log_pop(); } void script() YS_OVERRIDE { if (check_label("run_pass")) { run("hierarchy -auto-top"); run("design -save preopt"); if (help_mode) run("[command]"); else run(command); run("design -stash postopt"); } if (check_label("prepare")) { run("design -copy-from preopt -as gold A:top"); run("design -copy-from postopt -as gate A:top"); } if ((!techmap_opts.empty() || help_mode) && check_label("techmap", "(only with -map)")) { string opts; if (help_mode) opts = " -map <filename> ..."; else opts = techmap_opts; run("techmap -wb -D EQUIV -autoproc" + opts); } if (check_label("prove")) { if (multiclock || help_mode) run("clk2fflogic", "(only with -multiclock)"); if (!multiclock || help_mode) run("async2sync", "(only without -multiclock)"); run("equiv_make gold gate equiv"); if (help_mode) run("equiv_induct [-undef] equiv"); else if (undef) run("equiv_induct -undef equiv"); else run("equiv_induct equiv"); if (help_mode) run("equiv_status [-assert] equiv"); else if (assert) run("equiv_status -assert equiv"); else run("equiv_status equiv"); } if (check_label("restore")) { run("design -load preopt"); } } } EquivOptPass; PRIVATE_NAMESPACE_END <commit_msg>Revert "Update doc for equiv_opt"<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2018 whitequark <whitequark@whitequark.org> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct EquivOptPass:public ScriptPass { EquivOptPass() : ScriptPass("equiv_opt", "prove equivalence for optimized circuit") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" equiv_opt [options] [command]\n"); log("\n"); log("This command checks circuit equivalence before and after an optimization pass.\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to the start of the command list, and empty to\n"); log(" label is synonymous to the end of the command list.\n"); log("\n"); log(" -map <filename>\n"); log(" expand the modules in this file before proving equivalence. this is\n"); log(" useful for handling architecture-specific primitives.\n"); log("\n"); log(" -assert\n"); log(" produce an error if the circuits are not equivalent.\n"); log("\n"); log(" -multiclock\n"); log(" run clk2fflogic before equivalence checking.\n"); log("\n"); log(" -undef\n"); log(" enable modelling of undef states during equiv_induct.\n"); log("\n"); log("The following commands are executed by this verification command:\n"); help_script(); log("\n"); } std::string command, techmap_opts; bool assert, undef, multiclock; void clear_flags() YS_OVERRIDE { command = ""; techmap_opts = ""; assert = false; undef = false; multiclock = false; } void execute(std::vector < std::string > args, RTLIL::Design * design) YS_OVERRIDE { string run_from, run_to; clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-run" && argidx + 1 < args.size()) { size_t pos = args[argidx + 1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos + 1); continue; } if (args[argidx] == "-map" && argidx + 1 < args.size()) { techmap_opts += " -map " + args[++argidx]; continue; } if (args[argidx] == "-assert") { assert = true; continue; } if (args[argidx] == "-undef") { undef = true; continue; } if (args[argidx] == "-multiclock") { multiclock = true; continue; } break; } for (; argidx < args.size(); argidx++) { if (command.empty()) { if (args[argidx].compare(0, 1, "-") == 0) cmd_error(args, argidx, "Unknown option."); } else { command += " "; } command += args[argidx]; } if (command.empty()) log_cmd_error("No optimization pass specified!\n"); if (!design->full_selection()) log_cmd_error("This command only operates on fully selected designs!\n"); log_header(design, "Executing EQUIV_OPT pass.\n"); log_push(); run_script(design, run_from, run_to); log_pop(); } void script() YS_OVERRIDE { if (check_label("run_pass")) { run("hierarchy -auto-top"); run("design -save preopt"); if (help_mode) run("[command]"); else run(command); run("design -stash postopt"); } if (check_label("prepare")) { run("design -copy-from preopt -as gold A:top"); run("design -copy-from postopt -as gate A:top"); } if ((!techmap_opts.empty() || help_mode) && check_label("techmap", "(only with -map)")) { string opts; if (help_mode) opts = " -map <filename> ..."; else opts = techmap_opts; run("techmap -wb -D EQUIV -autoproc" + opts); } if (check_label("prove")) { if (multiclock || help_mode) run("clk2fflogic", "(only with -multiclock)"); else run("async2sync", "(only without -multiclock)"); run("equiv_make gold gate equiv"); if (help_mode) run("equiv_induct [-undef] equiv"); else if (undef) run("equiv_induct -undef equiv"); else run("equiv_induct equiv"); if (help_mode) run("equiv_status [-assert] equiv"); else if (assert) run("equiv_status -assert equiv"); else run("equiv_status equiv"); } if (check_label("restore")) { run("design -load preopt"); } } } EquivOptPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/* socket.io-arduino-client: a Socket.IO client for the Arduino Based on the Kevin Rohling WebSocketClient Copyright 2013 Bill Roy 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 <SocketIOClient.h> bool SocketIOClient::connect(Adafruit_CC3000 cc3000, char thehostname[], int theport) { ip = 0; uint8_t timeoutRetry = 0; while (ip == 0) { if (!cc3000.getHostByName(thehostname, &ip)){ timeoutRetry++; if (timeoutRetry < 3) { // wdt_reset(); } } delay(200); } unsigned long lastRead = millis(); do { client = cc3000.connectTCP(ip, 80); } while((!client.connected()) && ((millis() - lastRead) < 3000)); hostname = thehostname; port = theport; sendHandshake(hostname); return readHandshake(cc3000); } bool SocketIOClient::connected() { return client.connected(); } void SocketIOClient::disconnect() { client.close(); } // find the nth colon starting from dataptr void SocketIOClient::findColon(char which) { while (*dataptr) { if (*dataptr == ':') { if (--which <= 0) return; } ++dataptr; } } // terminate command at dataptr at closing double quote void SocketIOClient::terminateCommand(void) { dataptr[strlen(dataptr)-3] = 0; } void SocketIOClient::monitor(Adafruit_CC3000 cc3000) { *databuffer = 0; if (!client.connected()) { connect(cc3000, hostname, port); } if (!client.available()){ // Serial.println("sdfsdfsdf"); return; } char which; while (client.available()) { readLine(); dataptr = databuffer; dataptr[strlen(dataptr)-1] = 0; switch (databuffer[0]) { case '1': // connect: [] which = 6; break; case '2': // heartbeat: [2::] client.print((char)0); client.print("2::"); client.print((char)255); continue; case '5': // event: [5:::{"name":"ls"}] which = 4; break; default: Serial.print("Drop "); Serial.println(dataptr); continue; } findColon(which); //Print out entire buffer (with message) // Serial.println(dataptr); // CARVE OUT EVENT NAME // dataptr += 2; // char *optr = databuffer; // while (*dataptr && (*dataptr != '"')) { // if (*dataptr == '\\') { // ++dataptr; // todo: this just handles "; handle \r, \n, \t, \xdd // } // *optr++ = *dataptr++; // } // *optr = 0; //Serial.print("["); // Serial.print(databuffer); //Serial.print("]"); if (dataArrivedDelegate != NULL) { dataArrivedDelegate(*this, databuffer); } } } void SocketIOClient::setDataArrivedDelegate(DataArrivedDelegate newdataArrivedDelegate) { dataArrivedDelegate = newdataArrivedDelegate; } void SocketIOClient::sendHandshake(char hostname[]) { Serial.println(client.connected()); client.fastrprint(F("GET /socket.io/1/ HTTP/1.1\r\n")); client.fastrprint(F("Host: ")); client.fastrprint(hostname); client.fastrprint(F("\r\n")); //other headers client.fastrprint(F("Origin: Arduino\r\n")); //end headers client.fastrprint(F("\r\n")); client.println(); } bool SocketIOClient::waitForInput(void) { unsigned long now = millis(); while (!client.available() && ((millis() - now) < 30000UL)) {;} return client.available(); } void SocketIOClient::eatHeader(void) { while (client.available()) { // consume the header readLine(); if (strlen(databuffer) == 0) break; } } bool SocketIOClient::readHandshake(Adafruit_CC3000 cc3000) { if (!waitForInput()) return false; // check for happy "HTTP/1.1 200" response readLine(); if (atoi(&databuffer[9]) != 200) { while (client.available()) readLine(); client.close(); return false; } eatHeader(); readLine(); // read first line of response readLine(); // read sid : transport : timeout char *iptr = databuffer; char *optr = sid; while (*iptr && (*iptr != ':') && (optr < &sid[SID_LEN-2])) *optr++ = *iptr++; *optr = 0; Serial.print(F("Connected. SID=")); Serial.println(sid); // sid:transport:timeout while (client.available()) readLine(); client.close(); delay(1000); // reconnect on websocket connection Serial.print(F("WS Connect...")); ip = 0; uint8_t timeoutRetry = 0; while (ip == 0) { if (!cc3000.getHostByName(hostname, &ip)){ timeoutRetry++; if (timeoutRetry < 3) { // wdt_reset(); } } delay(200); } unsigned long lastRead = millis(); do { client = cc3000.connectTCP(ip, 80); } while((!client.connected()) && ((millis() - lastRead) < 3000)); Serial.println(F("Reconnected.")); wdt_reset(); client.print(F("GET /socket.io/1/websocket/")); client.print(sid); client.println(F(" HTTP/1.1")); client.print(F("Host: ")); client.println(hostname); client.println(F("Origin: ArduinoSocketIOClient")); client.println(F("Upgrade: WebSocket")); // must be camelcase ?! client.println(F("Connection: Upgrade\r\n")); if (!waitForInput()) return false; readLine(); if (atoi(&databuffer[9]) != 101) { while (client.available()) readLine(); client.close(); return false; } eatHeader(); monitor(cc3000); // treat the response as input return true; } void SocketIOClient::readLine() { dataptr = databuffer; while (client.available() && (dataptr < &databuffer[DATA_BUFFER_LEN-2])) { char c = client.read(); if (c == 0) {;} else if (c == 255) Serial.print(F("0x255")); else if (c == '\r') {;} else if (c == '\n') break; else *dataptr++ = c; } *dataptr = 0; } void SocketIOClient::sendMessage(char *data) { client.print((char)0); client.print("3:::"); client.print(data); client.print((char)255); } void SocketIOClient::sendEvent(char *event, char *data) { client.print((char)0); Serial.print((char)0); client.print("5:::{\"name\":\""); Serial.print("5:::{\"name\":\""); client.print(event); Serial.print(event); client.print("\", \"args\":\""); Serial.print("\", \"args\":\""); client.print(data); Serial.print(data); client.print("\"}"); Serial.print("\"}"); client.print((char)255); Serial.print((char)255); } <commit_msg>remove SendEvent debugging prints<commit_after>/* socket.io-arduino-client: a Socket.IO client for the Arduino Based on the Kevin Rohling WebSocketClient Copyright 2013 Bill Roy 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 <SocketIOClient.h> bool SocketIOClient::connect(Adafruit_CC3000 cc3000, char thehostname[], int theport) { ip = 0; uint8_t timeoutRetry = 0; while (ip == 0) { if (!cc3000.getHostByName(thehostname, &ip)){ timeoutRetry++; if (timeoutRetry < 3) { // wdt_reset(); } } delay(200); } unsigned long lastRead = millis(); do { client = cc3000.connectTCP(ip, 80); } while((!client.connected()) && ((millis() - lastRead) < 3000)); hostname = thehostname; port = theport; sendHandshake(hostname); return readHandshake(cc3000); } bool SocketIOClient::connected() { return client.connected(); } void SocketIOClient::disconnect() { client.close(); } // find the nth colon starting from dataptr void SocketIOClient::findColon(char which) { while (*dataptr) { if (*dataptr == ':') { if (--which <= 0) return; } ++dataptr; } } // terminate command at dataptr at closing double quote void SocketIOClient::terminateCommand(void) { dataptr[strlen(dataptr)-3] = 0; } void SocketIOClient::monitor(Adafruit_CC3000 cc3000) { *databuffer = 0; if (!client.connected()) { connect(cc3000, hostname, port); } if (!client.available()){ // Serial.println("sdfsdfsdf"); return; } char which; while (client.available()) { readLine(); dataptr = databuffer; dataptr[strlen(dataptr)-1] = 0; switch (databuffer[0]) { case '1': // connect: [] which = 6; break; case '2': // heartbeat: [2::] client.print((char)0); client.print("2::"); client.print((char)255); continue; case '5': // event: [5:::{"name":"ls"}] which = 4; break; default: Serial.print("Drop "); Serial.println(dataptr); continue; } findColon(which); //Print out entire buffer (with message) // Serial.println(dataptr); // CARVE OUT EVENT NAME // dataptr += 2; // char *optr = databuffer; // while (*dataptr && (*dataptr != '"')) { // if (*dataptr == '\\') { // ++dataptr; // todo: this just handles "; handle \r, \n, \t, \xdd // } // *optr++ = *dataptr++; // } // *optr = 0; //Serial.print("["); // Serial.print(databuffer); //Serial.print("]"); if (dataArrivedDelegate != NULL) { dataArrivedDelegate(*this, databuffer); } } } void SocketIOClient::setDataArrivedDelegate(DataArrivedDelegate newdataArrivedDelegate) { dataArrivedDelegate = newdataArrivedDelegate; } void SocketIOClient::sendHandshake(char hostname[]) { Serial.println(client.connected()); client.fastrprint(F("GET /socket.io/1/ HTTP/1.1\r\n")); client.fastrprint(F("Host: ")); client.fastrprint(hostname); client.fastrprint(F("\r\n")); //other headers client.fastrprint(F("Origin: Arduino\r\n")); //end headers client.fastrprint(F("\r\n")); client.println(); } bool SocketIOClient::waitForInput(void) { unsigned long now = millis(); while (!client.available() && ((millis() - now) < 30000UL)) {;} return client.available(); } void SocketIOClient::eatHeader(void) { while (client.available()) { // consume the header readLine(); if (strlen(databuffer) == 0) break; } } bool SocketIOClient::readHandshake(Adafruit_CC3000 cc3000) { if (!waitForInput()) return false; // check for happy "HTTP/1.1 200" response readLine(); if (atoi(&databuffer[9]) != 200) { while (client.available()) readLine(); client.close(); return false; } eatHeader(); readLine(); // read first line of response readLine(); // read sid : transport : timeout char *iptr = databuffer; char *optr = sid; while (*iptr && (*iptr != ':') && (optr < &sid[SID_LEN-2])) *optr++ = *iptr++; *optr = 0; Serial.print(F("Connected. SID=")); Serial.println(sid); // sid:transport:timeout while (client.available()) readLine(); client.close(); delay(1000); // reconnect on websocket connection Serial.print(F("WS Connect...")); ip = 0; uint8_t timeoutRetry = 0; while (ip == 0) { if (!cc3000.getHostByName(hostname, &ip)){ timeoutRetry++; if (timeoutRetry < 3) { // wdt_reset(); } } delay(200); } unsigned long lastRead = millis(); do { client = cc3000.connectTCP(ip, 80); } while((!client.connected()) && ((millis() - lastRead) < 3000)); Serial.println(F("Reconnected.")); wdt_reset(); client.print(F("GET /socket.io/1/websocket/")); client.print(sid); client.println(F(" HTTP/1.1")); client.print(F("Host: ")); client.println(hostname); client.println(F("Origin: ArduinoSocketIOClient")); client.println(F("Upgrade: WebSocket")); // must be camelcase ?! client.println(F("Connection: Upgrade\r\n")); if (!waitForInput()) return false; readLine(); if (atoi(&databuffer[9]) != 101) { while (client.available()) readLine(); client.close(); return false; } eatHeader(); monitor(cc3000); // treat the response as input return true; } void SocketIOClient::readLine() { dataptr = databuffer; while (client.available() && (dataptr < &databuffer[DATA_BUFFER_LEN-2])) { char c = client.read(); if (c == 0) {;} else if (c == 255) Serial.print(F("0x255")); else if (c == '\r') {;} else if (c == '\n') break; else *dataptr++ = c; } *dataptr = 0; } void SocketIOClient::sendMessage(char *data) { client.print((char)0); client.print("3:::"); client.print(data); client.print((char)255); } void SocketIOClient::sendEvent(char *event, char *data) { client.print((char)0); client.print("5:::{\"name\":\""); client.print(event); client.print("\", \"args\":\""); client.print(data); client.print("\"}"); client.print((char)255); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImageRegistrationMethod.h" #include "itkMeanSquaresImageToImageMetric.h" #include "itkRegularStepGradientDescentOptimizer.h" #include "itkCenteredTransformInitializer.h" #include "itkAffineTransform.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" #include "itkSubtractImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkNumericSeriesFileNames.h" #include "itkTimeProbesCollectorBase.h" // // The following piece of code implements an observer // that will monitor the evolution of the registration process. // #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {}; public: typedef itk::RegularStepGradientDescentOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( ! itk::IterationEvent().CheckEvent( &event ) ) { return; } std::cout << optimizer->GetCurrentIteration() << " "; std::cout << optimizer->GetValue() << " "; std::cout << optimizer->GetCurrentPosition(); // Print the angle for the trace plot vnl_matrix<double> p(2, 2); p[0][0] = (double) optimizer->GetCurrentPosition()[0]; p[0][1] = (double) optimizer->GetCurrentPosition()[1]; p[1][0] = (double) optimizer->GetCurrentPosition()[2]; p[1][1] = (double) optimizer->GetCurrentPosition()[3]; vnl_svd<double> svd(p); vnl_matrix<double> r(2, 2); r = svd.U() * vnl_transpose(svd.V()); double angle = vcl_asin(r[1][0]); std::cout << " AffineAngle: " << angle * 180.0 / vnl_math::pi << std::endl; } }; class AffineRegistration { public: typedef itk::AffineTransform< double, 2 > TransformType; AffineRegistration() { this->m_OutputInterSliceTransform = TransformType::New(); } ~AffineRegistration() {} void SetFixedImageFileName( const std::string & name ) { this->m_FixedImageFilename = name; } void SetMovingImageFileName( const std::string & name ) { this->m_MovingImageFilename = name; } void SetRegisteredImageFileName( const std::string & name ) { this->m_RegisteredImageFileName = name; } const TransformType * GetOutputInterSliceTransform() const { return this->m_OutputInterSliceTransform.GetPointer(); } void Execute(); private: std::string m_FixedImageFilename; std::string m_MovingImageFilename; std::string m_RegisteredImageFileName; TransformType::Pointer m_OutputInterSliceTransform; }; void AffineRegistration::Execute() { std::cout << "AffineRegistration of " << std::endl; std::cout << this->m_FixedImageFilename << std::endl; std::cout << this->m_MovingImageFilename << std::endl; std::cout << std::endl; itk::TimeProbesCollectorBase chronometer; const unsigned int Dimension = 2; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef itk::RegularStepGradientDescentOptimizer OptimizerType; typedef itk::MeanSquaresImageToImageMetric< FixedImageType, MovingImageType > MetricType; typedef itk:: LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; MetricType::Pointer metric = MetricType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetMetric( metric ); registration->SetOptimizer( optimizer ); registration->SetInterpolator( interpolator ); registration->SetTransform( this->m_OutputInterSliceTransform ); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( this->m_FixedImageFilename ); movingImageReader->SetFileName( this->m_MovingImageFilename ); chronometer.Start("Reading"); fixedImageReader->Update(); movingImageReader->Update(); chronometer.Stop("Reading"); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); registration->SetFixedImageRegion( fixedImageReader->GetOutput()->GetBufferedRegion() ); typedef itk::CenteredTransformInitializer< TransformType, FixedImageType, MovingImageType > TransformInitializerType; TransformInitializerType::Pointer initializer = TransformInitializerType::New(); initializer->SetTransform( this->m_OutputInterSliceTransform ); initializer->SetFixedImage( fixedImageReader->GetOutput() ); initializer->SetMovingImage( movingImageReader->GetOutput() ); initializer->GeometryOn(); chronometer.Start("Initialization"); initializer->InitializeTransform(); chronometer.Stop("Initialization"); registration->SetInitialTransformParameters( this->m_OutputInterSliceTransform->GetParameters() ); double translationScale = 1.0 / 1000.0; typedef OptimizerType::ScalesType OptimizerScalesType; OptimizerScalesType optimizerScales( this->m_OutputInterSliceTransform->GetNumberOfParameters() ); optimizerScales[0] = 1.0; optimizerScales[1] = 1.0; optimizerScales[2] = 1.0; optimizerScales[3] = 1.0; optimizerScales[4] = translationScale; optimizerScales[5] = translationScale; optimizer->SetScales( optimizerScales ); double steplength = 0.1; unsigned int maxNumberOfIterations = 300; optimizer->SetMaximumStepLength( steplength ); optimizer->SetMinimumStepLength( 0.0001 ); optimizer->SetNumberOfIterations( maxNumberOfIterations ); optimizer->MinimizeOn(); CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { chronometer.Start("Registration"); registration->StartRegistration(); chronometer.Stop("Registration"); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return; } std::cout << "Optimizer stop condition: " << registration->GetOptimizer()->GetStopConditionDescription() << std::endl; OptimizerType::ParametersType finalParameters = registration->GetLastTransformParameters(); const double finalRotationCenterX = this->m_OutputInterSliceTransform->GetCenter()[0]; const double finalRotationCenterY = this->m_OutputInterSliceTransform->GetCenter()[1]; const double finalTranslationX = finalParameters[4]; const double finalTranslationY = finalParameters[5]; const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); const double bestValue = optimizer->GetValue(); std::cout << "Result = " << std::endl; std::cout << " Center X = " << finalRotationCenterX << std::endl; std::cout << " Center Y = " << finalRotationCenterY << std::endl; std::cout << " Translation X = " << finalTranslationX << std::endl; std::cout << " Translation Y = " << finalTranslationY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; vnl_matrix<double> p(2, 2); p[0][0] = (double) finalParameters[0]; p[0][1] = (double) finalParameters[1]; p[1][0] = (double) finalParameters[2]; p[1][1] = (double) finalParameters[3]; vnl_svd<double> svd(p); vnl_matrix<double> r(2, 2); r = svd.U() * vnl_transpose(svd.V()); double angle = vcl_asin(r[1][0]); const double angleInDegrees = angle * 180.0 / vnl_math::pi; std::cout << " Scale 1 = " << svd.W(0) << std::endl; std::cout << " Scale 2 = " << svd.W(1) << std::endl; std::cout << " Angle (degrees) = " << angleInDegrees << std::endl; typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); finalTransform->SetFixedParameters( this->m_OutputInterSliceTransform->GetFixedParameters() ); ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetTransform( finalTransform ); resampler->SetInput( movingImageReader->GetOutput() ); FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resampler->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resampler->SetOutputOrigin( fixedImage->GetOrigin() ); resampler->SetOutputSpacing( fixedImage->GetSpacing() ); resampler->SetOutputDirection( fixedImage->GetDirection() ); resampler->SetDefaultPixelValue( 100 ); chronometer.Start("Resampling"); resampler->Update(); chronometer.Stop("Resampling"); typedef unsigned char OutputPixelType; typedef itk::ImageFileWriter< FixedImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( m_RegisteredImageFileName ); writer->SetInput( resampler->GetOutput() ); chronometer.Start("Writing"); writer->Update(); chronometer.Stop("Writing"); chronometer.Report( std::cout ); } int main( int argc, char *argv[] ) { if( argc < 4 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile " << std::endl; std::cerr << " outputImagefile [differenceBeforeRegistration] " << std::endl; std::cerr << " [differenceAfterRegistration] " << std::endl; std::cerr << " [stepLength] [maxNumberOfIterations] "<< std::endl; return EXIT_FAILURE; } typedef AffineRegistration::TransformType TransformType; typedef itk::NumericSeriesFileNames NameGeneratorType; NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New(); nameGenerator->SetSeriesFormat( argv[1] ); nameGenerator->SetStartIndex( atoi( argv[2] ) ); nameGenerator->SetEndIndex( atoi( argv[3] ) ); nameGenerator->SetIncrementIndex( 1 ); typedef std::vector< std::string > FileNamesType; const FileNamesType & nameList = nameGenerator->GetFileNames(); FileNamesType::const_iterator nameFixed = nameList.begin(); FileNamesType::const_iterator nameMoving = nameList.begin(); FileNamesType::const_iterator nameEnd = nameList.end(); nameMoving++; while( nameMoving != nameEnd ) { AffineRegistration registration; registration.SetFixedImageFileName( *nameFixed ); registration.SetMovingImageFileName( *nameMoving ); registration.SetRegisteredImageFileName("registered.png"); registration.Execute(); const TransformType * intersliceTransform = registration.GetOutputInterSliceTransform(); intersliceTransform->Print( std::cout ); nameFixed++; nameMoving++; } } <commit_msg>ENH: Fix command line error message.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImageRegistrationMethod.h" #include "itkMeanSquaresImageToImageMetric.h" #include "itkRegularStepGradientDescentOptimizer.h" #include "itkCenteredTransformInitializer.h" #include "itkAffineTransform.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" #include "itkSubtractImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkNumericSeriesFileNames.h" #include "itkTimeProbesCollectorBase.h" // // The following piece of code implements an observer // that will monitor the evolution of the registration process. // #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {}; public: typedef itk::RegularStepGradientDescentOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( ! itk::IterationEvent().CheckEvent( &event ) ) { return; } std::cout << optimizer->GetCurrentIteration() << " "; std::cout << optimizer->GetValue() << " "; std::cout << optimizer->GetCurrentPosition(); // Print the angle for the trace plot vnl_matrix<double> p(2, 2); p[0][0] = (double) optimizer->GetCurrentPosition()[0]; p[0][1] = (double) optimizer->GetCurrentPosition()[1]; p[1][0] = (double) optimizer->GetCurrentPosition()[2]; p[1][1] = (double) optimizer->GetCurrentPosition()[3]; vnl_svd<double> svd(p); vnl_matrix<double> r(2, 2); r = svd.U() * vnl_transpose(svd.V()); double angle = vcl_asin(r[1][0]); std::cout << " AffineAngle: " << angle * 180.0 / vnl_math::pi << std::endl; } }; class AffineRegistration { public: typedef itk::AffineTransform< double, 2 > TransformType; AffineRegistration() { this->m_OutputInterSliceTransform = TransformType::New(); } ~AffineRegistration() {} void SetFixedImageFileName( const std::string & name ) { this->m_FixedImageFilename = name; } void SetMovingImageFileName( const std::string & name ) { this->m_MovingImageFilename = name; } void SetRegisteredImageFileName( const std::string & name ) { this->m_RegisteredImageFileName = name; } const TransformType * GetOutputInterSliceTransform() const { return this->m_OutputInterSliceTransform.GetPointer(); } void Execute(); private: std::string m_FixedImageFilename; std::string m_MovingImageFilename; std::string m_RegisteredImageFileName; TransformType::Pointer m_OutputInterSliceTransform; }; void AffineRegistration::Execute() { std::cout << "AffineRegistration of " << std::endl; std::cout << this->m_FixedImageFilename << std::endl; std::cout << this->m_MovingImageFilename << std::endl; std::cout << std::endl; itk::TimeProbesCollectorBase chronometer; const unsigned int Dimension = 2; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef itk::RegularStepGradientDescentOptimizer OptimizerType; typedef itk::MeanSquaresImageToImageMetric< FixedImageType, MovingImageType > MetricType; typedef itk:: LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; MetricType::Pointer metric = MetricType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetMetric( metric ); registration->SetOptimizer( optimizer ); registration->SetInterpolator( interpolator ); registration->SetTransform( this->m_OutputInterSliceTransform ); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( this->m_FixedImageFilename ); movingImageReader->SetFileName( this->m_MovingImageFilename ); chronometer.Start("Reading"); fixedImageReader->Update(); movingImageReader->Update(); chronometer.Stop("Reading"); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); registration->SetFixedImageRegion( fixedImageReader->GetOutput()->GetBufferedRegion() ); typedef itk::CenteredTransformInitializer< TransformType, FixedImageType, MovingImageType > TransformInitializerType; TransformInitializerType::Pointer initializer = TransformInitializerType::New(); initializer->SetTransform( this->m_OutputInterSliceTransform ); initializer->SetFixedImage( fixedImageReader->GetOutput() ); initializer->SetMovingImage( movingImageReader->GetOutput() ); initializer->GeometryOn(); chronometer.Start("Initialization"); initializer->InitializeTransform(); chronometer.Stop("Initialization"); registration->SetInitialTransformParameters( this->m_OutputInterSliceTransform->GetParameters() ); double translationScale = 1.0 / 1000.0; typedef OptimizerType::ScalesType OptimizerScalesType; OptimizerScalesType optimizerScales( this->m_OutputInterSliceTransform->GetNumberOfParameters() ); optimizerScales[0] = 1.0; optimizerScales[1] = 1.0; optimizerScales[2] = 1.0; optimizerScales[3] = 1.0; optimizerScales[4] = translationScale; optimizerScales[5] = translationScale; optimizer->SetScales( optimizerScales ); double steplength = 0.1; unsigned int maxNumberOfIterations = 300; optimizer->SetMaximumStepLength( steplength ); optimizer->SetMinimumStepLength( 0.0001 ); optimizer->SetNumberOfIterations( maxNumberOfIterations ); optimizer->MinimizeOn(); CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { chronometer.Start("Registration"); registration->StartRegistration(); chronometer.Stop("Registration"); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return; } std::cout << "Optimizer stop condition: " << registration->GetOptimizer()->GetStopConditionDescription() << std::endl; OptimizerType::ParametersType finalParameters = registration->GetLastTransformParameters(); const double finalRotationCenterX = this->m_OutputInterSliceTransform->GetCenter()[0]; const double finalRotationCenterY = this->m_OutputInterSliceTransform->GetCenter()[1]; const double finalTranslationX = finalParameters[4]; const double finalTranslationY = finalParameters[5]; const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); const double bestValue = optimizer->GetValue(); std::cout << "Result = " << std::endl; std::cout << " Center X = " << finalRotationCenterX << std::endl; std::cout << " Center Y = " << finalRotationCenterY << std::endl; std::cout << " Translation X = " << finalTranslationX << std::endl; std::cout << " Translation Y = " << finalTranslationY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; vnl_matrix<double> p(2, 2); p[0][0] = (double) finalParameters[0]; p[0][1] = (double) finalParameters[1]; p[1][0] = (double) finalParameters[2]; p[1][1] = (double) finalParameters[3]; vnl_svd<double> svd(p); vnl_matrix<double> r(2, 2); r = svd.U() * vnl_transpose(svd.V()); double angle = vcl_asin(r[1][0]); const double angleInDegrees = angle * 180.0 / vnl_math::pi; std::cout << " Scale 1 = " << svd.W(0) << std::endl; std::cout << " Scale 2 = " << svd.W(1) << std::endl; std::cout << " Angle (degrees) = " << angleInDegrees << std::endl; typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); finalTransform->SetFixedParameters( this->m_OutputInterSliceTransform->GetFixedParameters() ); ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetTransform( finalTransform ); resampler->SetInput( movingImageReader->GetOutput() ); FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resampler->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resampler->SetOutputOrigin( fixedImage->GetOrigin() ); resampler->SetOutputSpacing( fixedImage->GetSpacing() ); resampler->SetOutputDirection( fixedImage->GetDirection() ); resampler->SetDefaultPixelValue( 100 ); chronometer.Start("Resampling"); resampler->Update(); chronometer.Stop("Resampling"); typedef unsigned char OutputPixelType; typedef itk::ImageFileWriter< FixedImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( m_RegisteredImageFileName ); writer->SetInput( resampler->GetOutput() ); chronometer.Start("Writing"); writer->Update(); chronometer.Stop("Writing"); chronometer.Report( std::cout ); } int main( int argc, char *argv[] ) { if( argc < 4 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " slices_filename_base_pattern firstSliceNumber LastSliceNumber" << std::endl; return EXIT_FAILURE; } typedef AffineRegistration::TransformType TransformType; typedef itk::NumericSeriesFileNames NameGeneratorType; NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New(); nameGenerator->SetSeriesFormat( argv[1] ); nameGenerator->SetStartIndex( atoi( argv[2] ) ); nameGenerator->SetEndIndex( atoi( argv[3] ) ); nameGenerator->SetIncrementIndex( 1 ); typedef std::vector< std::string > FileNamesType; const FileNamesType & nameList = nameGenerator->GetFileNames(); FileNamesType::const_iterator nameFixed = nameList.begin(); FileNamesType::const_iterator nameMoving = nameList.begin(); FileNamesType::const_iterator nameEnd = nameList.end(); nameMoving++; while( nameMoving != nameEnd ) { AffineRegistration registration; registration.SetFixedImageFileName( *nameFixed ); registration.SetMovingImageFileName( *nameMoving ); registration.SetRegisteredImageFileName("registered.png"); registration.Execute(); const TransformType * intersliceTransform = registration.GetOutputInterSliceTransform(); intersliceTransform->Print( std::cout ); nameFixed++; nameMoving++; } } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright RTK Consortium * * 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.txt * * 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 "rtkGgoFunctions.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkFDKConeBeamReconstructionFilter.h" #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include "rtkFieldOfViewImageFilter.h" #include <itkExtractImageFilter.h> #include <itkMultiplyByConstantImageFilter.h> template<class TImage> void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType; ImageIteratorType itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage::PixelType TestVal = itTest.Get(); typename TImage::PixelType RefVal = itRef.Get(); if( TestVal != RefVal ) { //std::cout << "Not equal" << std::endl; TestError += vcl_abs(RefVal - TestVal); //std::cout << "Error ="<< TestError << std::endl; EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); } ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (2.0-ErrorPerPixel)/2.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 0.005) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 0.005" << std::endl; exit( EXIT_FAILURE); } if (PSNR < 25.) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 25" << std::endl; exit( EXIT_FAILURE); } } int main(int argc, char* argv[]) { const unsigned int Dimension = 3; typedef float OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; const unsigned int NumberOfProjectionImages = 360; // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; // FOV filter Input Volume, it is used as the input to create the fov mask. const ConstantImageSourceType::Pointer fovInput = ConstantImageSourceType::New(); origin[0] = -127; origin[1] = -127; origin[2] = -127; size[0] = 256; size[1] = 256; size[2] = 256; spacing[0] = 1.; spacing[1] = 1.; spacing[2] = 1.; fovInput->SetOrigin( origin ); fovInput->SetSpacing( spacing ); fovInput->SetSize( size ); fovInput->SetConstant( 1. ); // FDK Input Projections, it is used as the input to create the fov mask. const ConstantImageSourceType::Pointer fdkInput = ConstantImageSourceType::New(); origin[0] = -127; origin[1] = -127; origin[2] = -127; size[0] = 256; size[1] = 256; size[2] = NumberOfProjectionImages; spacing[0] = 1.; spacing[1] = 1.; spacing[2] = 1.; fdkInput->SetOrigin( origin ); fdkInput->SetSpacing( spacing ); fdkInput->SetSize( size ); fdkInput->SetConstant( 1. ); // Stack of empty projections const ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New(); origin[0] = -127; origin[1] = -127; origin[2] = -127; size[0] = 256; size[1] = 256; size[2] = 256; spacing[0] = 1.; spacing[1] = 1.; spacing[2] = 1.; projectionsSource->SetOrigin( origin ); projectionsSource->SetSpacing( spacing ); projectionsSource->SetSize( size ); projectionsSource->SetConstant( 0. ); //FOV filter typedef rtk::FieldOfViewImageFilter<OutputImageType, OutputImageType> FOVFilterType; FOVFilterType::Pointer fov=FOVFilterType::New(); // FDK reconstruction filtering typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType; FDKCPUType::Pointer feldkamp = FDKCPUType::New(); // Writer typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); // Creating geometry for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(1000, 1500., noProj*360./NumberOfProjectionImages); // Calculating ray box intersection of the resized Input fov->SetInput(0, fovInput->GetOutput()); fov->SetProjectionsStack(projectionsSource->GetOutput()); fov->SetGeometry( geometry ); fov->Update(); // Writting writer->SetFileName( "fov.mhd" ); writer->SetInput( fov->GetOutput() ); writer->Update(); // Backproject stack of projections feldkamp->SetInput( 0, projectionsSource->GetOutput() ); feldkamp->SetInput( 1, fdkInput->GetOutput() ); feldkamp->SetGeometry( geometry ); feldkamp->GetRampFilter()->SetHannCutFrequency(0.); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); // typedef itk::ImageRegionIterator<OutputImageType> OutputIterator; // typedef typename OutputImageType::RegionType OutputImageRegionType; // const OutputImageRegionType outputRegion = feldkamp->GetOutput()->GetLargestPossibleRegion(); // OutputIterator itOut(feldkamp->GetOutput(), outputRegion ); // itOut.GoToBegin(); // const OutputImageType::SizeValueType loopSize = outputRegion.GetSize(0)*outputRegion.GetSize(1)*outputRegion.GetSize(2); // bool inside = false; // OutputPixelType previous = 0.; // for(unsigned int k=0; k<loopSize; k++) // { // if(inside) // { // if(itOut.Get()-previous > 0.01) // inside = false; // previous = itOut.Get(); // itOut.Set(1.); // } // else // { // if(itOut.Get()-previous < -0.01) // inside = true; // previous = itOut.Get(); // itOut.Set(0.); // } // ++itOut; // } // Writting writer->SetFileName( "bkp_fov.mhd" ); writer->SetInput( feldkamp->GetOutput() ); writer->Update(); CheckImageQuality<OutputImageType>(fov->GetOutput(), feldkamp->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; exit(EXIT_SUCCESS); } <commit_msg>Fixed FOV test<commit_after>#include <itkImageRegionConstIterator.h> #include <itkBinaryThresholdImageFilter.h> #include "rtkMacro.h" #include "rtkFieldOfViewImageFilter.h" #include "rtkConstantImageSource.h" #include "rtkBackProjectionImageFilter.h" template<class TImage> void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType; ImageIteratorType itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage::PixelType TestVal = itTest.Get(); typename TImage::PixelType RefVal = itRef.Get(); TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (2.0-ErrorPerPixel)/2.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 0.02) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 0.02." << std::endl; exit( EXIT_FAILURE); } if (PSNR < 23.5) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 23.5" << std::endl; exit( EXIT_FAILURE); } } int main(int argc, char* argv[]) { const unsigned int Dimension = 3; typedef float OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; const unsigned int NumberOfProjectionImages = 180; // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; // FOV filter Input Volume, it is used as the input to create the fov mask. const ConstantImageSourceType::Pointer fovInput = ConstantImageSourceType::New(); origin[0] = -127.; origin[1] = -127.; origin[2] = -127.; size[0] = 128.; size[1] = 128.; size[2] = 128.; spacing[0] = 2.; spacing[1] = 2.; spacing[2] = 2.; fovInput->SetOrigin( origin ); fovInput->SetSpacing( spacing ); fovInput->SetSize( size ); fovInput->SetConstant( 1. ); // BP volume const ConstantImageSourceType::Pointer bpInput = ConstantImageSourceType::New(); bpInput->SetOrigin( origin ); bpInput->SetSpacing( spacing ); bpInput->SetSize( size ); // BackProjection Input Projections, it is used as the input to create the fov mask. const ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New(); origin[0] = -254.; origin[1] = -254.; origin[2] = -254.; size[0] = 128; size[1] = 128; size[2] = NumberOfProjectionImages; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; projectionsSource->SetOrigin( origin ); projectionsSource->SetSpacing( spacing ); projectionsSource->SetSize( size ); projectionsSource->SetConstant( 1. ); // Geometry typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600, 1200., noProj*360./NumberOfProjectionImages); // FOV typedef rtk::FieldOfViewImageFilter<OutputImageType, OutputImageType> FOVFilterType; FOVFilterType::Pointer fov=FOVFilterType::New(); fov->SetInput(0, fovInput->GetOutput()); fov->SetProjectionsStack(projectionsSource->GetOutput()); fov->SetGeometry( geometry ); fov->Update(); // Backprojection reconstruction filter typedef rtk::BackProjectionImageFilter< OutputImageType, OutputImageType > BPType; BPType::Pointer bp = BPType::New(); bp->SetInput( 0, bpInput->GetOutput() ); bp->SetInput( 1, projectionsSource->GetOutput() ); bp->SetGeometry( geometry.GetPointer() ); // Thresholded to the number of projections typedef itk::BinaryThresholdImageFilter< OutputImageType, OutputImageType > ThresholdType; ThresholdType::Pointer threshold = ThresholdType::New(); threshold->SetInput(bp->GetOutput()); threshold->SetOutsideValue(0.); threshold->SetLowerThreshold(NumberOfProjectionImages-0.5); threshold->SetUpperThreshold(NumberOfProjectionImages+0.5); threshold->SetInsideValue(1.); TRY_AND_EXIT_ON_ITK_EXCEPTION( threshold->Update() ); CheckImageQuality<OutputImageType>(fov->GetOutput(), threshold->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before><commit_msg>Trying to allow deepest setbacks throughout eco scale.<commit_after><|endoftext|>
<commit_before><commit_msg>TODO-721: gearing up to sending first secure frames<commit_after><|endoftext|>
<commit_before><commit_msg>TODO-786: WIP<commit_after><|endoftext|>
<commit_before>#include "MCWin32.h" // should be first include. #include "MCHashMap.h" #include <stdlib.h> #include <string.h> #include "MCDefines.h" #include "MCArray.h" #include "MCString.h" #include "MCUtils.h" #include "MCLog.h" #include "MCIterator.h" #include "MCAssert.h" using namespace mailcore; namespace mailcore { struct HashMapCell { unsigned int func; Object * key; Object * value; HashMapCell * next; }; } #define CHASH_DEFAULTSIZE 13 #define CHASH_MAXDEPTH 3 void HashMap::init() { mCount = 0; size_t hashMapCellSize = sizeof(HashMapCell *); mCells = (void **) calloc(CHASH_DEFAULTSIZE, hashMapCellSize); mAllocated = CHASH_DEFAULTSIZE; } HashMap::HashMap() { init(); } HashMap::HashMap(HashMap * other) { init(); Array * keys = other->allKeys(); for(unsigned int i = 0 ; i < keys->count() ; i ++) { Object * key = keys->objectAtIndex(i); Object * value = other->objectForKey(key); setObjectForKey(key, value); } } HashMap::~HashMap() { for(unsigned int indx = 0; indx < mAllocated; indx++) { HashMapIter * iter, * next; iter = (HashMapIter *) mCells[indx]; while (iter) { next = iter->next; iter->key->release(); iter->value->release(); free(iter); iter = next; } } free(mCells); } void HashMap::allocate(unsigned int size) { HashMapCell ** cells; unsigned int indx, nindx; HashMapIter * iter, * next; if (mAllocated == size) return; cells = (HashMapCell **) calloc(size, sizeof(HashMapCell *)); /* iterate over initial hash and copy items in second hash */ for(indx = 0 ; indx < mAllocated ; indx ++) { iter = (HashMapIter *) mCells[indx]; while (iter) { next = iter->next; nindx = iter->func % size; iter->next = cells[nindx]; cells[nindx] = iter; iter = next; } } free(mCells); mAllocated = size; mCells = (void **) cells; } HashMap * HashMap::hashMap() { HashMap * result = new HashMap(); return (HashMap *) result->autorelease(); } String * HashMap::description() { String * result = String::string(); Array * keys = allKeys(); result->appendUTF8Characters("{"); for(unsigned int i = 0 ; i < keys->count() ; i ++) { Object * key = keys->objectAtIndex(i); if (i != 0) { result->appendUTF8Characters(","); } result->appendString(key->description()); result->appendUTF8Characters(":"); Object * value = objectForKey(key); result->appendString(value->description()); } result->appendUTF8Characters("}"); return result; } Object * HashMap::copy() { return new HashMap(this); } unsigned int HashMap::count() { return mCount; } void HashMap::setObjectForKey(Object * key, Object * value) { unsigned int func, indx; HashMapIter * iter, * cell; if (mCount > mAllocated * CHASH_MAXDEPTH) { allocate((mCount / CHASH_MAXDEPTH) * 2 + 1); } func = key->hash(); indx = func % mAllocated; /* look for the key in existing cells */ iter = (HashMapIter *) mCells[indx]; while (iter) { if (iter->func == func && iter->key->isEqual(key)) { /* found, replacing entry */ value->retain(); iter->value->release(); iter->value = value; return; } iter = iter->next; } /* not found, adding entry */ cell = (HashMapCell *) malloc(sizeof(HashMapCell)); cell->key = key->copy(); cell->value = value->retain(); cell->func = func; cell->next = (HashMapCell *) mCells[indx]; mCells[indx] = cell; mCount ++; } void HashMap::removeObjectForKey(Object * key) { unsigned int func, indx; HashMapIter * iter, * old; func = key->hash();; indx = func % mAllocated; /* look for the key in existing cells */ old = NULL; iter = (HashMapIter *) mCells[indx]; while (iter) { if (iter->func == func && iter->key->isEqual(key)) { /* found, deleting */ if (old) old->next = iter->next; else mCells[indx] = iter->next; iter->key->release(); iter->value->release(); free(iter); mCount --; return; } old = iter; iter = iter->next; } // Not found. } Object * HashMap::objectForKey(Object * key) { unsigned int func; HashMapIter * iter; func = key->hash(); /* look for the key in existing cells */ iter = (HashMapIter *) mCells[func % mAllocated]; while (iter) { if (iter->func == func && key->isEqual(iter->key)) { return iter->value; /* found */ } iter = iter->next; } return NULL; } HashMapIter * HashMap::iteratorBegin() { HashMapIter * iter; unsigned int indx = 0; iter = (HashMapIter *) mCells[0]; while (!iter) { indx ++; if (indx >= mAllocated) return NULL; iter = (HashMapIter *) mCells[indx]; } return iter; } HashMapIter * HashMap::iteratorNext(HashMapIter * iter) { unsigned int indx; if (!iter) return NULL; indx = iter->func % mAllocated; iter = iter->next; while(!iter) { indx++; if (indx >= mAllocated) return NULL; iter = (HashMapIter *) mCells[indx]; } return iter; } Array * HashMap::allKeys() { Array * keys = Array::array(); for(HashMapIter * iter = iteratorBegin() ; iter != NULL ; iter = iteratorNext(iter)) { keys->addObject(iter->key); } return keys; } Array * HashMap::allValues() { Array * values = Array::array(); for(HashMapIter * iter = iteratorBegin() ; iter != NULL ; iter = iteratorNext(iter)) { values->addObject(iter->value); } return values; } void HashMap::removeAllObjects() { for(unsigned int indx = 0 ; indx < mAllocated ; indx++) { HashMapIter * iter, * next; iter = (HashMapIter *) mCells[indx]; while (iter) { next = iter->next; iter->key->release(); iter->value->release(); free(iter); iter = next; } } memset(mCells, 0, mAllocated * sizeof(* mCells)); mCount = 0; } bool HashMap::isEqual(Object * otherObject) { HashMap * otherMap = (HashMap *) otherObject; if (otherMap->count() != count()) { return false; } bool result = true; mc_foreachhashmapKeyAndValue(Object, key, Object, value, this) { Object * otherValue = otherMap->objectForKey(key); if (otherValue == NULL) { result = false; break; } if (!value->isEqual(otherValue)) { fprintf(stderr, "%s: %s %s\n", MCUTF8(key), MCUTF8(value), MCUTF8(otherValue)); result = false; break; } } return result; } HashMap * HashMap::serializable() { HashMap * result = Object::serializable(); Array * keys = Array::array(); Array * values = Array::array(); mc_foreachhashmapKeyAndValue(Object, key, Object, value, this) { if (MCISKINDOFCLASS(key, String)) { keys->addObject(key); } else { keys->addObject(key->serializable()); } values->addObject(value->serializable()); } result->setObjectForKey(MCSTR("keys"), keys); result->setObjectForKey(MCSTR("values"), values); return result; } void HashMap::importSerializable(HashMap * serializable) { Array * keys = (Array *) serializable->objectForKey(MCSTR("keys")); Array * values = (Array *) serializable->objectForKey(MCSTR("values")); unsigned int count = keys->count(); MCAssert(count == values->count()); for(unsigned int i = 0 ; i < count ; i ++) { Object * serializedKey = keys->objectAtIndex(i); Object * key; if (MCISKINDOFCLASS(serializedKey, String)) { key = serializedKey; } else { key = Object::objectWithSerializable((HashMap *) serializedKey); } Object * value = Object::objectWithSerializable((HashMap *) values->objectAtIndex(i)); setObjectForKey(key, value); } } static void * createObject() { return new HashMap(); } INITIALIZE(HashMap) { Object::registerObjectConstructor("mailcore::HashMap", &createObject); } <commit_msg>Don't crash when removing a nil key from a hashmap<commit_after>#include "MCWin32.h" // should be first include. #include "MCHashMap.h" #include <stdlib.h> #include <string.h> #include "MCDefines.h" #include "MCArray.h" #include "MCString.h" #include "MCUtils.h" #include "MCLog.h" #include "MCIterator.h" #include "MCAssert.h" using namespace mailcore; namespace mailcore { struct HashMapCell { unsigned int func; Object * key; Object * value; HashMapCell * next; }; } #define CHASH_DEFAULTSIZE 13 #define CHASH_MAXDEPTH 3 void HashMap::init() { mCount = 0; size_t hashMapCellSize = sizeof(HashMapCell *); mCells = (void **) calloc(CHASH_DEFAULTSIZE, hashMapCellSize); mAllocated = CHASH_DEFAULTSIZE; } HashMap::HashMap() { init(); } HashMap::HashMap(HashMap * other) { init(); Array * keys = other->allKeys(); for(unsigned int i = 0 ; i < keys->count() ; i ++) { Object * key = keys->objectAtIndex(i); Object * value = other->objectForKey(key); setObjectForKey(key, value); } } HashMap::~HashMap() { for(unsigned int indx = 0; indx < mAllocated; indx++) { HashMapIter * iter, * next; iter = (HashMapIter *) mCells[indx]; while (iter) { next = iter->next; iter->key->release(); iter->value->release(); free(iter); iter = next; } } free(mCells); } void HashMap::allocate(unsigned int size) { HashMapCell ** cells; unsigned int indx, nindx; HashMapIter * iter, * next; if (mAllocated == size) return; cells = (HashMapCell **) calloc(size, sizeof(HashMapCell *)); /* iterate over initial hash and copy items in second hash */ for(indx = 0 ; indx < mAllocated ; indx ++) { iter = (HashMapIter *) mCells[indx]; while (iter) { next = iter->next; nindx = iter->func % size; iter->next = cells[nindx]; cells[nindx] = iter; iter = next; } } free(mCells); mAllocated = size; mCells = (void **) cells; } HashMap * HashMap::hashMap() { HashMap * result = new HashMap(); return (HashMap *) result->autorelease(); } String * HashMap::description() { String * result = String::string(); Array * keys = allKeys(); result->appendUTF8Characters("{"); for(unsigned int i = 0 ; i < keys->count() ; i ++) { Object * key = keys->objectAtIndex(i); if (i != 0) { result->appendUTF8Characters(","); } result->appendString(key->description()); result->appendUTF8Characters(":"); Object * value = objectForKey(key); result->appendString(value->description()); } result->appendUTF8Characters("}"); return result; } Object * HashMap::copy() { return new HashMap(this); } unsigned int HashMap::count() { return mCount; } void HashMap::setObjectForKey(Object * key, Object * value) { unsigned int func, indx; HashMapIter * iter, * cell; if (mCount > mAllocated * CHASH_MAXDEPTH) { allocate((mCount / CHASH_MAXDEPTH) * 2 + 1); } func = key->hash(); indx = func % mAllocated; /* look for the key in existing cells */ iter = (HashMapIter *) mCells[indx]; while (iter) { if (iter->func == func && iter->key->isEqual(key)) { /* found, replacing entry */ value->retain(); iter->value->release(); iter->value = value; return; } iter = iter->next; } /* not found, adding entry */ cell = (HashMapCell *) malloc(sizeof(HashMapCell)); cell->key = key->copy(); cell->value = value->retain(); cell->func = func; cell->next = (HashMapCell *) mCells[indx]; mCells[indx] = cell; mCount ++; } void HashMap::removeObjectForKey(Object * key) { unsigned int func, indx; HashMapIter * iter, * old; if (key == NULL) { return; } func = key->hash();; indx = func % mAllocated; /* look for the key in existing cells */ old = NULL; iter = (HashMapIter *) mCells[indx]; while (iter) { if (iter->func == func && iter->key->isEqual(key)) { /* found, deleting */ if (old) old->next = iter->next; else mCells[indx] = iter->next; iter->key->release(); iter->value->release(); free(iter); mCount --; return; } old = iter; iter = iter->next; } // Not found. } Object * HashMap::objectForKey(Object * key) { unsigned int func; HashMapIter * iter; func = key->hash(); /* look for the key in existing cells */ iter = (HashMapIter *) mCells[func % mAllocated]; while (iter) { if (iter->func == func && key->isEqual(iter->key)) { return iter->value; /* found */ } iter = iter->next; } return NULL; } HashMapIter * HashMap::iteratorBegin() { HashMapIter * iter; unsigned int indx = 0; iter = (HashMapIter *) mCells[0]; while (!iter) { indx ++; if (indx >= mAllocated) return NULL; iter = (HashMapIter *) mCells[indx]; } return iter; } HashMapIter * HashMap::iteratorNext(HashMapIter * iter) { unsigned int indx; if (!iter) return NULL; indx = iter->func % mAllocated; iter = iter->next; while(!iter) { indx++; if (indx >= mAllocated) return NULL; iter = (HashMapIter *) mCells[indx]; } return iter; } Array * HashMap::allKeys() { Array * keys = Array::array(); for(HashMapIter * iter = iteratorBegin() ; iter != NULL ; iter = iteratorNext(iter)) { keys->addObject(iter->key); } return keys; } Array * HashMap::allValues() { Array * values = Array::array(); for(HashMapIter * iter = iteratorBegin() ; iter != NULL ; iter = iteratorNext(iter)) { values->addObject(iter->value); } return values; } void HashMap::removeAllObjects() { for(unsigned int indx = 0 ; indx < mAllocated ; indx++) { HashMapIter * iter, * next; iter = (HashMapIter *) mCells[indx]; while (iter) { next = iter->next; iter->key->release(); iter->value->release(); free(iter); iter = next; } } memset(mCells, 0, mAllocated * sizeof(* mCells)); mCount = 0; } bool HashMap::isEqual(Object * otherObject) { HashMap * otherMap = (HashMap *) otherObject; if (otherMap->count() != count()) { return false; } bool result = true; mc_foreachhashmapKeyAndValue(Object, key, Object, value, this) { Object * otherValue = otherMap->objectForKey(key); if (otherValue == NULL) { result = false; break; } if (!value->isEqual(otherValue)) { fprintf(stderr, "%s: %s %s\n", MCUTF8(key), MCUTF8(value), MCUTF8(otherValue)); result = false; break; } } return result; } HashMap * HashMap::serializable() { HashMap * result = Object::serializable(); Array * keys = Array::array(); Array * values = Array::array(); mc_foreachhashmapKeyAndValue(Object, key, Object, value, this) { if (MCISKINDOFCLASS(key, String)) { keys->addObject(key); } else { keys->addObject(key->serializable()); } values->addObject(value->serializable()); } result->setObjectForKey(MCSTR("keys"), keys); result->setObjectForKey(MCSTR("values"), values); return result; } void HashMap::importSerializable(HashMap * serializable) { Array * keys = (Array *) serializable->objectForKey(MCSTR("keys")); Array * values = (Array *) serializable->objectForKey(MCSTR("values")); unsigned int count = keys->count(); MCAssert(count == values->count()); for(unsigned int i = 0 ; i < count ; i ++) { Object * serializedKey = keys->objectAtIndex(i); Object * key; if (MCISKINDOFCLASS(serializedKey, String)) { key = serializedKey; } else { key = Object::objectWithSerializable((HashMap *) serializedKey); } Object * value = Object::objectWithSerializable((HashMap *) values->objectAtIndex(i)); setObjectForKey(key, value); } } static void * createObject() { return new HashMap(); } INITIALIZE(HashMap) { Object::registerObjectConstructor("mailcore::HashMap", &createObject); } <|endoftext|>
<commit_before>/**************************************************************************** * This file is part of Qt AccountsService Addon. * * Copyright (C) 2015 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> * * Author(s): * Pier Luigi Fiorini * * $BEGIN_LICENSE:GPL2+$ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * $END_LICENSE$ ***************************************************************************/ #include <QtTest/QtTest> #include "fakeaccounts.h" #include "fakeaccountsadaptor.h" #include "accountsmanager.h" #include "useraccount.h" using namespace QtAccountsService; class TestApi : public QObject { Q_OBJECT public: TestApi(QObject *parent = 0) : QObject(parent) , accounts(Q_NULLPTR) , manager(Q_NULLPTR) { } private Q_SLOTS: void initTestCase() { accounts = new FakeAccounts(this); new FakeAccountsAdaptor(accounts); manager = new AccountsManager(QDBusConnection::sessionBus()); } void cleanupTestCase() { delete manager; manager = Q_NULLPTR; delete accounts; accounts = Q_NULLPTR; } void createAccounts() { // Find a user that doesn't exist QVERIFY(manager->findUserById(1000) == Q_NULLPTR); // Create user bool ret = manager->createUser(QStringLiteral("testuser"), QStringLiteral("Test User"), UserAccount::StandardAccountType); QVERIFY(ret == true); // Find the same user UserAccount *account = manager->findUserById(1000); QVERIFY(account != Q_NULLPTR); if (account) QCOMPARE(account->userName(), QStringLiteral("testuser")); } void cacheAccounts() { UserAccountList cachedUsers; // We start with no cached users cachedUsers = manager->listCachedUsers(); QCOMPARE(cachedUsers.size(), 0); // Cache one user UserAccount *account = manager->cacheUser(QStringLiteral("testuser")); QCOMPARE(account->userName(), QStringLiteral("testuser")); // Verify we have 1 cached user cachedUsers = manager->listCachedUsers(); QCOMPARE(cachedUsers.size(), 1); // Uncache the user manager->uncacheUser(QStringLiteral("testuser")); // No cached users cachedUsers = manager->listCachedUsers(); QCOMPARE(cachedUsers.size(), 0); } void deleteAccounts() { bool ret = manager->deleteUser(1000, false); QVERIFY(ret == true); } private: FakeAccounts *accounts; AccountsManager *manager; }; QTEST_MAIN(TestApi) #include "tst_api.moc" <commit_msg>Avoid potential crashes during tests<commit_after>/**************************************************************************** * This file is part of Qt AccountsService Addon. * * Copyright (C) 2015 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> * * Author(s): * Pier Luigi Fiorini * * $BEGIN_LICENSE:GPL2+$ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * $END_LICENSE$ ***************************************************************************/ #include <QtTest/QtTest> #include "fakeaccounts.h" #include "fakeaccountsadaptor.h" #include "accountsmanager.h" #include "useraccount.h" using namespace QtAccountsService; class TestApi : public QObject { Q_OBJECT public: TestApi(QObject *parent = 0) : QObject(parent) , accounts(Q_NULLPTR) , manager(Q_NULLPTR) { } private Q_SLOTS: void initTestCase() { accounts = new FakeAccounts(this); new FakeAccountsAdaptor(accounts); manager = new AccountsManager(QDBusConnection::sessionBus()); } void cleanupTestCase() { delete manager; manager = Q_NULLPTR; delete accounts; accounts = Q_NULLPTR; } void createAccounts() { // Find a user that doesn't exist QVERIFY(manager->findUserById(1000) == Q_NULLPTR); // Create user bool ret = manager->createUser(QStringLiteral("testuser"), QStringLiteral("Test User"), UserAccount::StandardAccountType); QVERIFY(ret == true); // Find the same user UserAccount *account = manager->findUserById(1000); QVERIFY(account != Q_NULLPTR); if (account) QCOMPARE(account->userName(), QStringLiteral("testuser")); } void cacheAccounts() { UserAccountList cachedUsers; // We start with no cached users cachedUsers = manager->listCachedUsers(); QCOMPARE(cachedUsers.size(), 0); // Cache one user UserAccount *account = manager->cacheUser(QStringLiteral("testuser")); QVERIFY(account != Q_NULLPTR); if (account) QCOMPARE(account->userName(), QStringLiteral("testuser")); // Verify we have 1 cached user cachedUsers = manager->listCachedUsers(); QCOMPARE(cachedUsers.size(), 1); // Uncache the user manager->uncacheUser(QStringLiteral("testuser")); // No cached users cachedUsers = manager->listCachedUsers(); QCOMPARE(cachedUsers.size(), 0); } void deleteAccounts() { bool ret = manager->deleteUser(1000, false); QVERIFY(ret == true); } private: FakeAccounts *accounts; AccountsManager *manager; }; QTEST_MAIN(TestApi) #include "tst_api.moc" <|endoftext|>
<commit_before>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpcpp/impl/codegen/server_context_impl.h> #include <algorithm> #include <utility> #include <grpc/compression.h> #include <grpc/grpc.h> #include <grpc/load_reporting.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpcpp/impl/call.h> #include <grpcpp/impl/codegen/completion_queue_impl.h> #include <grpcpp/support/server_callback.h> #include <grpcpp/support/time.h> #include "src/core/lib/gprpp/ref_counted.h" #include "src/core/lib/gprpp/sync.h" #include "src/core/lib/surface/call.h" namespace grpc_impl { // CompletionOp class ServerContextBase::CompletionOp final : public ::grpc::internal::CallOpSetInterface { public: // initial refs: one in the server context, one in the cq // must ref the call before calling constructor and after deleting this CompletionOp(::grpc::internal::Call* call, ::grpc_impl::internal::ServerCallbackCall* callback_controller) : call_(*call), callback_controller_(callback_controller), has_tag_(false), tag_(nullptr), core_cq_tag_(this), refs_(2), finalized_(false), cancelled_(0), done_intercepting_(false) {} // CompletionOp isn't copyable or movable CompletionOp(const CompletionOp&) = delete; CompletionOp& operator=(const CompletionOp&) = delete; CompletionOp(CompletionOp&&) = delete; CompletionOp& operator=(CompletionOp&&) = delete; ~CompletionOp() { if (call_.server_rpc_info()) { call_.server_rpc_info()->Unref(); } } void FillOps(::grpc::internal::Call* call) override; // This should always be arena allocated in the call, so override delete. // But this class is not trivially destructible, so must actually call delete // before allowing the arena to be freed static void operator delete(void* /*ptr*/, std::size_t size) { // Use size to avoid unused-parameter warning since assert seems to be // compiled out and treated as unused in some gcc optimized versions. (void)size; assert(size == sizeof(CompletionOp)); } // This operator should never be called as the memory should be freed as part // of the arena destruction. It only exists to provide a matching operator // delete to the operator new so that some compilers will not complain (see // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this // there are no tests catching the compiler warning. static void operator delete(void*, void*) { assert(0); } bool FinalizeResult(void** tag, bool* status) override; bool CheckCancelled(CompletionQueue* cq) { cq->TryPluck(this); return CheckCancelledNoPluck(); } bool CheckCancelledAsync() { return CheckCancelledNoPluck(); } void set_tag(void* tag) { has_tag_ = true; tag_ = tag; } void set_core_cq_tag(void* core_cq_tag) { core_cq_tag_ = core_cq_tag; } void* core_cq_tag() override { return core_cq_tag_; } void Unref(); // This will be called while interceptors are run if the RPC is a hijacked // RPC. This should set hijacking state for each of the ops. void SetHijackingState() override { /* Servers don't allow hijacking */ GPR_ASSERT(false); } /* Should be called after interceptors are done running */ void ContinueFillOpsAfterInterception() override {} /* Should be called after interceptors are done running on the finalize result * path */ void ContinueFinalizeResultAfterInterception() override { done_intercepting_ = true; if (!has_tag_) { /* We don't have a tag to return. */ Unref(); return; } /* Start a dummy op so that we can return the tag */ GPR_ASSERT(grpc_call_start_batch(call_.call(), nullptr, 0, core_cq_tag_, nullptr) == GRPC_CALL_OK); } private: bool CheckCancelledNoPluck() { grpc_core::MutexLock lock(&mu_); return finalized_ ? (cancelled_ != 0) : false; } ::grpc::internal::Call call_; ::grpc_impl::internal::ServerCallbackCall* const callback_controller_; bool has_tag_; void* tag_; void* core_cq_tag_; grpc_core::RefCount refs_; grpc_core::Mutex mu_; bool finalized_; int cancelled_; // This is an int (not bool) because it is passed to core bool done_intercepting_; ::grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_; }; void ServerContextBase::CompletionOp::Unref() { if (refs_.Unref()) { grpc_call* call = call_.call(); delete this; grpc_call_unref(call); } } void ServerContextBase::CompletionOp::FillOps(::grpc::internal::Call* call) { grpc_op ops; ops.op = GRPC_OP_RECV_CLOSE_ON_SERVER; ops.data.recv_close_on_server.cancelled = &cancelled_; ops.flags = 0; ops.reserved = nullptr; interceptor_methods_.SetCall(&call_); interceptor_methods_.SetReverse(); interceptor_methods_.SetCallOpSetInterface(this); // The following call_start_batch is internally-generated so no need for an // explanatory log on failure. GPR_ASSERT(grpc_call_start_batch(call->call(), &ops, 1, core_cq_tag_, nullptr) == GRPC_CALL_OK); /* No interceptors to run here */ } bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) { bool ret = false; grpc_core::ReleasableMutexLock lock(&mu_); if (done_intercepting_) { /* We are done intercepting. */ if (has_tag_) { *tag = tag_; ret = true; } Unref(); return ret; } finalized_ = true; // If for some reason the incoming status is false, mark that as a // cancellation. // TODO(vjpai): does this ever happen? if (!*status) { cancelled_ = 1; } // Decide whether to call the cancel callback before releasing the lock bool call_cancel = (cancelled_ != 0); // Release the lock since we may call a callback and interceptors now. lock.Unlock(); if (call_cancel && callback_controller_ != nullptr) { callback_controller_->MaybeCallOnCancel(); } /* Add interception point and run through interceptors */ interceptor_methods_.AddInterceptionHookPoint( ::grpc::experimental::InterceptionHookPoints::POST_RECV_CLOSE); if (interceptor_methods_.RunInterceptors()) { /* No interceptors were run */ if (has_tag_) { *tag = tag_; ret = true; } Unref(); return ret; } /* There are interceptors to be run. Return false for now */ return false; } // ServerContextBase body ServerContextBase::ServerContextBase() { Setup(gpr_inf_future(GPR_CLOCK_REALTIME)); } ServerContextBase::ServerContextBase(gpr_timespec deadline, grpc_metadata_array* arr) { Setup(deadline); std::swap(*client_metadata_.arr(), *arr); } void ServerContextBase::Setup(gpr_timespec deadline) { completion_op_ = nullptr; has_notify_when_done_tag_ = false; async_notify_when_done_tag_ = nullptr; deadline_ = deadline; call_ = nullptr; cq_ = nullptr; sent_initial_metadata_ = false; compression_level_set_ = false; has_pending_ops_ = false; rpc_info_ = nullptr; } void ServerContextBase::BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr) { deadline_ = deadline; std::swap(*client_metadata_.arr(), *arr); } ServerContextBase::~ServerContextBase() { Clear(); } void ServerContextBase::Clear() { auth_context_.reset(); initial_metadata_.clear(); trailing_metadata_.clear(); client_metadata_.Reset(); if (completion_op_) { completion_op_->Unref(); completion_op_ = nullptr; completion_tag_.Clear(); } if (rpc_info_) { rpc_info_->Unref(); rpc_info_ = nullptr; } if (call_) { auto* call = call_; call_ = nullptr; grpc_call_unref(call); } if (default_reactor_used_.load(std::memory_order_relaxed)) { reinterpret_cast<Reactor*>(&default_reactor_)->~Reactor(); default_reactor_used_.store(false, std::memory_order_relaxed); } test_unary_.reset(); } void ServerContextBase::BeginCompletionOp( ::grpc::internal::Call* call, std::function<void(bool)> callback, ::grpc_impl::internal::ServerCallbackCall* callback_controller) { GPR_ASSERT(!completion_op_); if (rpc_info_) { rpc_info_->Ref(); } grpc_call_ref(call->call()); completion_op_ = new (grpc_call_arena_alloc(call->call(), sizeof(CompletionOp))) CompletionOp(call, callback_controller); if (callback_controller != nullptr) { completion_tag_.Set(call->call(), std::move(callback), completion_op_, true); completion_op_->set_core_cq_tag(&completion_tag_); completion_op_->set_tag(completion_op_); } else if (has_notify_when_done_tag_) { completion_op_->set_tag(async_notify_when_done_tag_); } call->PerformOps(completion_op_); } ::grpc::internal::CompletionQueueTag* ServerContextBase::GetCompletionOpTag() { return static_cast<::grpc::internal::CompletionQueueTag*>(completion_op_); } void ServerContextBase::AddInitialMetadata(const grpc::string& key, const grpc::string& value) { initial_metadata_.insert(std::make_pair(key, value)); } void ServerContextBase::AddTrailingMetadata(const grpc::string& key, const grpc::string& value) { trailing_metadata_.insert(std::make_pair(key, value)); } void ServerContextBase::TryCancel() const { ::grpc::internal::CancelInterceptorBatchMethods cancel_methods; if (rpc_info_) { for (size_t i = 0; i < rpc_info_->interceptors_.size(); i++) { rpc_info_->RunInterceptor(&cancel_methods, i); } } grpc_call_error err = grpc_call_cancel_with_status( call_, GRPC_STATUS_CANCELLED, "Cancelled on the server side", nullptr); if (err != GRPC_CALL_OK) { gpr_log(GPR_ERROR, "TryCancel failed with: %d", err); } } bool ServerContextBase::IsCancelled() const { if (completion_tag_) { // When using callback API, this result is always valid. return completion_op_->CheckCancelledAsync(); } else if (has_notify_when_done_tag_) { // When using async API, the result is only valid // if the tag has already been delivered at the completion queue return completion_op_ && completion_op_->CheckCancelledAsync(); } else { // when using sync API, the result is always valid return completion_op_ && completion_op_->CheckCancelled(cq_); } } void ServerContextBase::set_compression_algorithm( grpc_compression_algorithm algorithm) { compression_algorithm_ = algorithm; const char* algorithm_name = nullptr; if (!grpc_compression_algorithm_name(algorithm, &algorithm_name)) { gpr_log(GPR_ERROR, "Name for compression algorithm '%d' unknown.", algorithm); abort(); } GPR_ASSERT(algorithm_name != nullptr); AddInitialMetadata(GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, algorithm_name); } grpc::string ServerContextBase::peer() const { grpc::string peer; if (call_) { char* c_peer = grpc_call_get_peer(call_); peer = c_peer; gpr_free(c_peer); } return peer; } const struct census_context* ServerContextBase::census_context() const { return grpc_census_call_get_context(call_); } void ServerContextBase::SetLoadReportingCosts( const std::vector<grpc::string>& cost_data) { if (call_ == nullptr) return; for (const auto& cost_datum : cost_data) { AddTrailingMetadata(GRPC_LB_COST_MD_KEY, cost_datum); } } } // namespace grpc_impl <commit_msg>Avoid a use of ReleasableMutexLock<commit_after>/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpcpp/impl/codegen/server_context_impl.h> #include <algorithm> #include <utility> #include <grpc/compression.h> #include <grpc/grpc.h> #include <grpc/load_reporting.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpcpp/impl/call.h> #include <grpcpp/impl/codegen/completion_queue_impl.h> #include <grpcpp/support/server_callback.h> #include <grpcpp/support/time.h> #include "src/core/lib/gprpp/ref_counted.h" #include "src/core/lib/gprpp/sync.h" #include "src/core/lib/surface/call.h" namespace grpc_impl { // CompletionOp class ServerContextBase::CompletionOp final : public ::grpc::internal::CallOpSetInterface { public: // initial refs: one in the server context, one in the cq // must ref the call before calling constructor and after deleting this CompletionOp(::grpc::internal::Call* call, ::grpc_impl::internal::ServerCallbackCall* callback_controller) : call_(*call), callback_controller_(callback_controller), has_tag_(false), tag_(nullptr), core_cq_tag_(this), refs_(2), finalized_(false), cancelled_(0), done_intercepting_(false) {} // CompletionOp isn't copyable or movable CompletionOp(const CompletionOp&) = delete; CompletionOp& operator=(const CompletionOp&) = delete; CompletionOp(CompletionOp&&) = delete; CompletionOp& operator=(CompletionOp&&) = delete; ~CompletionOp() { if (call_.server_rpc_info()) { call_.server_rpc_info()->Unref(); } } void FillOps(::grpc::internal::Call* call) override; // This should always be arena allocated in the call, so override delete. // But this class is not trivially destructible, so must actually call delete // before allowing the arena to be freed static void operator delete(void* /*ptr*/, std::size_t size) { // Use size to avoid unused-parameter warning since assert seems to be // compiled out and treated as unused in some gcc optimized versions. (void)size; assert(size == sizeof(CompletionOp)); } // This operator should never be called as the memory should be freed as part // of the arena destruction. It only exists to provide a matching operator // delete to the operator new so that some compilers will not complain (see // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this // there are no tests catching the compiler warning. static void operator delete(void*, void*) { assert(0); } bool FinalizeResult(void** tag, bool* status) override; bool CheckCancelled(CompletionQueue* cq) { cq->TryPluck(this); return CheckCancelledNoPluck(); } bool CheckCancelledAsync() { return CheckCancelledNoPluck(); } void set_tag(void* tag) { has_tag_ = true; tag_ = tag; } void set_core_cq_tag(void* core_cq_tag) { core_cq_tag_ = core_cq_tag; } void* core_cq_tag() override { return core_cq_tag_; } void Unref(); // This will be called while interceptors are run if the RPC is a hijacked // RPC. This should set hijacking state for each of the ops. void SetHijackingState() override { /* Servers don't allow hijacking */ GPR_ASSERT(false); } /* Should be called after interceptors are done running */ void ContinueFillOpsAfterInterception() override {} /* Should be called after interceptors are done running on the finalize result * path */ void ContinueFinalizeResultAfterInterception() override { done_intercepting_ = true; if (!has_tag_) { /* We don't have a tag to return. */ Unref(); return; } /* Start a dummy op so that we can return the tag */ GPR_ASSERT(grpc_call_start_batch(call_.call(), nullptr, 0, core_cq_tag_, nullptr) == GRPC_CALL_OK); } private: bool CheckCancelledNoPluck() { grpc_core::MutexLock lock(&mu_); return finalized_ ? (cancelled_ != 0) : false; } ::grpc::internal::Call call_; ::grpc_impl::internal::ServerCallbackCall* const callback_controller_; bool has_tag_; void* tag_; void* core_cq_tag_; grpc_core::RefCount refs_; grpc_core::Mutex mu_; bool finalized_; int cancelled_; // This is an int (not bool) because it is passed to core bool done_intercepting_; ::grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_; }; void ServerContextBase::CompletionOp::Unref() { if (refs_.Unref()) { grpc_call* call = call_.call(); delete this; grpc_call_unref(call); } } void ServerContextBase::CompletionOp::FillOps(::grpc::internal::Call* call) { grpc_op ops; ops.op = GRPC_OP_RECV_CLOSE_ON_SERVER; ops.data.recv_close_on_server.cancelled = &cancelled_; ops.flags = 0; ops.reserved = nullptr; interceptor_methods_.SetCall(&call_); interceptor_methods_.SetReverse(); interceptor_methods_.SetCallOpSetInterface(this); // The following call_start_batch is internally-generated so no need for an // explanatory log on failure. GPR_ASSERT(grpc_call_start_batch(call->call(), &ops, 1, core_cq_tag_, nullptr) == GRPC_CALL_OK); /* No interceptors to run here */ } bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) { // Decide whether to call the cancel callback within the lock bool call_cancel; { grpc_core::MutexLock lock(&mu_); if (done_intercepting_) { // We are done intercepting. bool has_tag = has_tag_; if (has_tag) { *tag = tag_; } Unref(); return has_tag; } finalized_ = true; // If for some reason the incoming status is false, mark that as a // cancellation. // TODO(vjpai): does this ever happen? if (!*status) { cancelled_ = 1; } call_cancel = (cancelled_ != 0); // Release the lock since we may call a callback and interceptors. } if (call_cancel && callback_controller_ != nullptr) { callback_controller_->MaybeCallOnCancel(); } /* Add interception point and run through interceptors */ interceptor_methods_.AddInterceptionHookPoint( ::grpc::experimental::InterceptionHookPoints::POST_RECV_CLOSE); if (interceptor_methods_.RunInterceptors()) { // No interceptors were run bool has_tag = has_tag_; if (has_tag) { *tag = tag_; } Unref(); return has_tag; } // There are interceptors to be run. Return false for now. return false; } // ServerContextBase body ServerContextBase::ServerContextBase() { Setup(gpr_inf_future(GPR_CLOCK_REALTIME)); } ServerContextBase::ServerContextBase(gpr_timespec deadline, grpc_metadata_array* arr) { Setup(deadline); std::swap(*client_metadata_.arr(), *arr); } void ServerContextBase::Setup(gpr_timespec deadline) { completion_op_ = nullptr; has_notify_when_done_tag_ = false; async_notify_when_done_tag_ = nullptr; deadline_ = deadline; call_ = nullptr; cq_ = nullptr; sent_initial_metadata_ = false; compression_level_set_ = false; has_pending_ops_ = false; rpc_info_ = nullptr; } void ServerContextBase::BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr) { deadline_ = deadline; std::swap(*client_metadata_.arr(), *arr); } ServerContextBase::~ServerContextBase() { Clear(); } void ServerContextBase::Clear() { auth_context_.reset(); initial_metadata_.clear(); trailing_metadata_.clear(); client_metadata_.Reset(); if (completion_op_) { completion_op_->Unref(); completion_op_ = nullptr; completion_tag_.Clear(); } if (rpc_info_) { rpc_info_->Unref(); rpc_info_ = nullptr; } if (call_) { auto* call = call_; call_ = nullptr; grpc_call_unref(call); } if (default_reactor_used_.load(std::memory_order_relaxed)) { reinterpret_cast<Reactor*>(&default_reactor_)->~Reactor(); default_reactor_used_.store(false, std::memory_order_relaxed); } test_unary_.reset(); } void ServerContextBase::BeginCompletionOp( ::grpc::internal::Call* call, std::function<void(bool)> callback, ::grpc_impl::internal::ServerCallbackCall* callback_controller) { GPR_ASSERT(!completion_op_); if (rpc_info_) { rpc_info_->Ref(); } grpc_call_ref(call->call()); completion_op_ = new (grpc_call_arena_alloc(call->call(), sizeof(CompletionOp))) CompletionOp(call, callback_controller); if (callback_controller != nullptr) { completion_tag_.Set(call->call(), std::move(callback), completion_op_, true); completion_op_->set_core_cq_tag(&completion_tag_); completion_op_->set_tag(completion_op_); } else if (has_notify_when_done_tag_) { completion_op_->set_tag(async_notify_when_done_tag_); } call->PerformOps(completion_op_); } ::grpc::internal::CompletionQueueTag* ServerContextBase::GetCompletionOpTag() { return static_cast<::grpc::internal::CompletionQueueTag*>(completion_op_); } void ServerContextBase::AddInitialMetadata(const grpc::string& key, const grpc::string& value) { initial_metadata_.insert(std::make_pair(key, value)); } void ServerContextBase::AddTrailingMetadata(const grpc::string& key, const grpc::string& value) { trailing_metadata_.insert(std::make_pair(key, value)); } void ServerContextBase::TryCancel() const { ::grpc::internal::CancelInterceptorBatchMethods cancel_methods; if (rpc_info_) { for (size_t i = 0; i < rpc_info_->interceptors_.size(); i++) { rpc_info_->RunInterceptor(&cancel_methods, i); } } grpc_call_error err = grpc_call_cancel_with_status( call_, GRPC_STATUS_CANCELLED, "Cancelled on the server side", nullptr); if (err != GRPC_CALL_OK) { gpr_log(GPR_ERROR, "TryCancel failed with: %d", err); } } bool ServerContextBase::IsCancelled() const { if (completion_tag_) { // When using callback API, this result is always valid. return completion_op_->CheckCancelledAsync(); } else if (has_notify_when_done_tag_) { // When using async API, the result is only valid // if the tag has already been delivered at the completion queue return completion_op_ && completion_op_->CheckCancelledAsync(); } else { // when using sync API, the result is always valid return completion_op_ && completion_op_->CheckCancelled(cq_); } } void ServerContextBase::set_compression_algorithm( grpc_compression_algorithm algorithm) { compression_algorithm_ = algorithm; const char* algorithm_name = nullptr; if (!grpc_compression_algorithm_name(algorithm, &algorithm_name)) { gpr_log(GPR_ERROR, "Name for compression algorithm '%d' unknown.", algorithm); abort(); } GPR_ASSERT(algorithm_name != nullptr); AddInitialMetadata(GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, algorithm_name); } grpc::string ServerContextBase::peer() const { grpc::string peer; if (call_) { char* c_peer = grpc_call_get_peer(call_); peer = c_peer; gpr_free(c_peer); } return peer; } const struct census_context* ServerContextBase::census_context() const { return grpc_census_call_get_context(call_); } void ServerContextBase::SetLoadReportingCosts( const std::vector<grpc::string>& cost_data) { if (call_ == nullptr) return; for (const auto& cost_datum : cost_data) { AddTrailingMetadata(GRPC_LB_COST_MD_KEY, cost_datum); } } } // namespace grpc_impl <|endoftext|>
<commit_before> #include "Column.h" //==[ EXAMPLE ]======================================================== using Utility::Column; using Utility::AccessMap; class Example : private AccessMap<Example, int> , private AccessMap<Example, double> , private AccessMap<Example, std::string> { public: Example(int i, double d, std::string const& s) : intVar_(i) , dblVar_(d) , strVar_(s) {} using rows = std::vector<Example>; template<typename T, bool NoCheck = false> using column = Column<T, Example, NoCheck>; template<bool NoCheck = false> static column<int, NoCheck> intColumn( rows* matrix, std::string const& name ) { return AccessMap<Example, int>::column<NoCheck>( matrix, name ); } template<bool NoCheck = false> static column<double, NoCheck> dblColumn( rows* matrix, std::string const& name ) { return AccessMap<Example, double>::column<NoCheck>( matrix, name ); } template<bool NoCheck = false> static column<std::string, NoCheck> strColumn( rows* matrix, std::string const& name ) { return AccessMap<Example, std::string>::column<NoCheck>( matrix, name ); } private: int intVar_; double dblVar_; std::string strVar_; friend class AccessMap<Example, int>; friend class AccessMap<Example, double>; friend class AccessMap<Example, std::string>; }; template<> AccessMap<Example, int>::FieldMap AccessMap<Example, int>::map_ = { { "int", &Example::intVar_ } }; template<> AccessMap<Example, double>::FieldMap AccessMap<Example, double>::map_ = { { "dbl", &Example::dblVar_ } }; template<> AccessMap<Example, std::string>::FieldMap AccessMap<Example, std::string>::map_ = { { "str", &Example::strVar_ } }; std::vector<Example> exampleVec = { { 1, 1.1, "one" }, { 2, 2.2, "two" }, { 3, 3.3, "three" }, }; std::vector<double> newVals = { 4.4, 5.5, 6.6 }; #include <iostream> #include <algorithm> int main() { for ( auto const& _i : Example::intColumn<>( &exampleVec, "int" ) ) { std::cerr << "int value: " << _i << std::endl; } for ( auto const& _d : Example::dblColumn<>( &exampleVec, "dbl" ) ) { std::cerr << "dbl value: " << _d << std::endl; } for ( auto const& _s : Example::strColumn<>( &exampleVec, "str" ) ) { std::cerr << "str value: " << _s << std::endl; } std::copy( newVals.begin(), newVals.end(), Example::dblColumn<>( &exampleVec, "dbl" ).begin() ); for ( auto const& _d : Example::dblColumn<>( &exampleVec, "dbl" ) ) { std::cerr << "dbl value: " << _d << std::endl; } return 0; } <commit_msg>simplify<commit_after> #include "Column.h" //==[ EXAMPLE ]======================================================== using Utility::Column; using Utility::AccessMap; class Example { public: Example(int i, double d, std::string const& s) : intVar_(i) , dblVar_(d) , strVar_(s) {} using rows = std::vector<Example>; template<typename T, bool NoCheck = false> using column = Column<T, Example, NoCheck>; template<bool NoCheck = false> static column<int, NoCheck> intColumn( rows* matrix, std::string const& name ) { return AccessMap<Example, int>::column<NoCheck>( matrix, name ); } template<bool NoCheck = false> static column<double, NoCheck> dblColumn( rows* matrix, std::string const& name ) { return AccessMap<Example, double>::column<NoCheck>( matrix, name ); } template<bool NoCheck = false> static column<std::string, NoCheck> strColumn( rows* matrix, std::string const& name ) { return AccessMap<Example, std::string>::column<NoCheck>( matrix, name ); } private: int intVar_; double dblVar_; std::string strVar_; friend class AccessMap<Example, int>; friend class AccessMap<Example, double>; friend class AccessMap<Example, std::string>; }; template<> AccessMap<Example, int>::FieldMap AccessMap<Example, int>::map_ = { { "int", &Example::intVar_ } }; template<> AccessMap<Example, double>::FieldMap AccessMap<Example, double>::map_ = { { "dbl", &Example::dblVar_ } }; template<> AccessMap<Example, std::string>::FieldMap AccessMap<Example, std::string>::map_ = { { "str", &Example::strVar_ } }; std::vector<Example> exampleVec = { { 1, 1.1, "one" }, { 2, 2.2, "two" }, { 3, 3.3, "three" }, }; std::vector<double> newVals = { 4.4, 5.5, 6.6 }; #include <iostream> #include <algorithm> int main() { for ( auto const& _i : Example::intColumn<>( &exampleVec, "int" ) ) { std::cerr << "int value: " << _i << std::endl; } for ( auto const& _d : Example::dblColumn<>( &exampleVec, "dbl" ) ) { std::cerr << "dbl value: " << _d << std::endl; } for ( auto const& _s : Example::strColumn<>( &exampleVec, "str" ) ) { std::cerr << "str value: " << _s << std::endl; } std::copy( newVals.begin(), newVals.end(), Example::dblColumn<>( &exampleVec, "dbl" ).begin() ); for ( auto const& _d : Example::dblColumn<>( &exampleVec, "dbl" ) ) { std::cerr << "dbl value: " << _d << std::endl; } return 0; } <|endoftext|>
<commit_before>//// License: Apache 2.0. See LICENSE file in root directory. //// Copyright(c) 2020 Intel Corporation. All Rights Reserved. #include "depth-to-rgb-calibration.h" #include <librealsense2/rs.hpp> #include "core/streaming.h" #include "calibrated-sensor.h" #include "context.h" #include "api.h" // VALIDATE_INTERFACE_NO_THROW #include "algo/depth-to-rgb-calibration/debug.h" #ifndef _WIN32 #include <sys/stat.h> // mkdir #endif using namespace librealsense; namespace impl = librealsense::algo::depth_to_rgb_calibration; static rs2_extrinsics fix_extrinsics( rs2_extrinsics extr, float by ) { // The extrinsics we get are based in meters, and AC algo is based in millimeters // NOTE that the scaling here needs to be accompanied by the same scaling of the depth // units! extr.translation[0] *= by; extr.translation[1] *= by; extr.translation[2] *= by; // This transposing is absolutely mandatory because our internal algorithms are // written with a transposed matrix in mind! (see rs2_transform_point_to_point) // This is the opposite transpose to the one we do with the extrinsics we get // from the camera... std::swap( extr.rotation[1], extr.rotation[3] ); std::swap( extr.rotation[2], extr.rotation[6] ); std::swap( extr.rotation[5], extr.rotation[7] ); return extr; } depth_to_rgb_calibration::depth_to_rgb_calibration( rs2::frame depth, rs2::frame ir, rs2::frame yuy, rs2::frame prev_yuy, algo::depth_to_rgb_calibration::algo_calibration_info const & cal_info, algo::depth_to_rgb_calibration::algo_calibration_registers const & cal_regs ) : _intr( yuy.get_profile().as< rs2::video_stream_profile >().get_intrinsics() ) , _extr( fix_extrinsics( depth.get_profile().get_extrinsics_to( yuy.get_profile() ), 1000 )) , _from( depth.get_profile().get()->profile ) , _to( yuy.get_profile().get()->profile ) { AC_LOG( DEBUG, "... setting yuy data" ); auto color_profile = yuy.get_profile().as< rs2::video_stream_profile >(); auto yuy_data = (impl::yuy_t const *) yuy.get_data(); auto prev_yuy_data = (impl::yuy_t const *) prev_yuy.get_data(); impl::calib calibration( _intr, _extr ); _algo.set_yuy_data( std::vector< impl::yuy_t >( yuy_data, yuy_data + yuy.get_data_size() / sizeof( impl::yuy_t )), std::vector< impl::yuy_t >( prev_yuy_data, prev_yuy_data + yuy.get_data_size() / sizeof( impl::yuy_t ) ), calibration ); AC_LOG( DEBUG, "... setting ir data" ); auto ir_profile = ir.get_profile().as< rs2::video_stream_profile >(); auto ir_data = (impl::ir_t const *) ir.get_data(); _algo.set_ir_data( std::vector< impl::ir_t >( ir_data, ir_data + ir.get_data_size() / sizeof( impl::ir_t )), ir_profile.width(), ir_profile.height() ); auto si = ((frame_interface *) depth.get() )->get_sensor(); auto cs = VALIDATE_INTERFACE_NO_THROW( si, librealsense::calibrated_sensor ); if( !cs ) { // We can only calibrate depth sensors that supply this interface! throw librealsense::not_implemented_exception( "the depth frame supplied is not from a calibrated_sensor" ); } _dsm_params = cs->get_dsm_params(); AC_LOG( DEBUG, "... setting z data" ); auto z_profile = depth.get_profile().as< rs2::video_stream_profile >(); auto z_data = (impl::z_t const *) depth.get_data(); _algo.set_z_data( std::vector< impl::z_t >( z_data, z_data + depth.get_data_size() / sizeof( impl::z_t ) ), z_profile.get_intrinsics(), _dsm_params, cal_info, cal_regs, depth.as< rs2::depth_frame >().get_units() * 1000.f // same scaling as for extrinsics! ); debug_calibration( "old" ); // If the user has this env var defined, then we write out logs and frames to it // NOTE: The var should end with a directory separator \ or / auto dir_ = getenv( "RS2_DEBUG_DIR" ); if( dir_ ) { std::string dir( dir_ ); dir += std::to_string( depth.get_frame_number() ); #ifdef _WIN32 auto status = _mkdir( dir.c_str() ); #else auto status = mkdir( dir.c_str(), 0700 ); #endif if( status == 0 ) _algo.write_data_to( dir ); else AC_LOG( WARNING, "Failed (" << status << ") to write AC frame data to: " << dir ); } } rs2_calibration_status depth_to_rgb_calibration::optimize( std::function<void( rs2_calibration_status )> call_back ) { #define DISABLE_RS2_CALIBRATION_CHECKS "DISABLE_RS2_CALIBRATION_CHECKS" try { AC_LOG( DEBUG, "... checking scene validity" ); if( !_algo.is_scene_valid() ) { AC_LOG( ERROR, "Calibration scene was found invalid!" ); call_back( RS2_CALIBRATION_SCENE_INVALID ); if( !getenv( DISABLE_RS2_CALIBRATION_CHECKS ) ) { // Default behavior is to stop AC and trigger a retry return RS2_CALIBRATION_RETRY; } AC_LOG( DEBUG, DISABLE_RS2_CALIBRATION_CHECKS << " is on; continuing" ); } AC_LOG( DEBUG, "... optimizing" ); auto n_iterations = _algo.optimize(); if( !n_iterations ) { // AC_LOG( INFO, "Calibration not necessary; nothing done" ); return RS2_CALIBRATION_NOT_NEEDED; } AC_LOG( DEBUG, "... checking result validity" ); if( !_algo.is_valid_results() ) { // Error would have printed inside call_back( RS2_CALIBRATION_BAD_RESULT ); if( !getenv( DISABLE_RS2_CALIBRATION_CHECKS ) ) { // Default behavior is to stop and trigger a retry AC_LOG( DEBUG, DISABLE_RS2_CALIBRATION_CHECKS << " is off; will retry if possible" ); return RS2_CALIBRATION_RETRY; } if( !getenv( "FORCE_RS2_CALIBRATION_RESULTS" ) ) { // This is mostly for validation use, where we don't want the retries and instead want // to fail on bad results (we don't want to write bad results to the camera!) AC_LOG( DEBUG, DISABLE_RS2_CALIBRATION_CHECKS << " is on; no retries" ); return RS2_CALIBRATION_FAILED; } // Allow forcing of results... be careful! This may damage the camera in AC2! AC_LOG( DEBUG, DISABLE_RS2_CALIBRATION_CHECKS << " is on but so is FORCE_RS2_CALIBRATION_RESULTS: results will be used!" ); } // AC_LOG( INFO, "Calibration finished; original cost= " << original_cost << " optimized // cost= " << params_curr.cost ); AC_LOG( DEBUG, "... optimization successful!" ); _intr = _algo.get_calibration().get_intrinsics(); _extr = fix_extrinsics( _algo.get_calibration().get_extrinsics(), 0.001f ); _dsm_params = _algo.get_dsm_params(); debug_calibration( "new" ); return RS2_CALIBRATION_SUCCESSFUL; } catch( std::exception const & e ) { AC_LOG( ERROR, "Calibration threw error: " << e.what() ); return RS2_CALIBRATION_FAILED; } } void depth_to_rgb_calibration::debug_calibration( char const * prefix ) { AC_LOG( DEBUG, AC_F_PREC << prefix << " intr[ " << _intr.width << "x" << _intr.height << " ppx: " << _intr.ppx << ", ppy: " << _intr.ppy << ", fx: " << _intr.fx << ", fy: " << _intr.fy << ", model: " << int( _intr.model ) << " coeffs[" << _intr.coeffs[0] << ", " << _intr.coeffs[1] << ", " << _intr.coeffs[2] << ", " << _intr.coeffs[3] << ", " << _intr.coeffs[4] << "] ]" ); AC_LOG( DEBUG, AC_F_PREC << prefix << " extr" << _extr ); AC_LOG( DEBUG, AC_F_PREC << prefix << " dsm" << _dsm_params ); } <commit_msg>added flag to fail on invalid scene, per request; all flags now RS2_AC_...<commit_after>//// License: Apache 2.0. See LICENSE file in root directory. //// Copyright(c) 2020 Intel Corporation. All Rights Reserved. #include "depth-to-rgb-calibration.h" #include <librealsense2/rs.hpp> #include "core/streaming.h" #include "calibrated-sensor.h" #include "context.h" #include "api.h" // VALIDATE_INTERFACE_NO_THROW #include "algo/depth-to-rgb-calibration/debug.h" #ifndef _WIN32 #include <sys/stat.h> // mkdir #endif using namespace librealsense; namespace impl = librealsense::algo::depth_to_rgb_calibration; static rs2_extrinsics fix_extrinsics( rs2_extrinsics extr, float by ) { // The extrinsics we get are based in meters, and AC algo is based in millimeters // NOTE that the scaling here needs to be accompanied by the same scaling of the depth // units! extr.translation[0] *= by; extr.translation[1] *= by; extr.translation[2] *= by; // This transposing is absolutely mandatory because our internal algorithms are // written with a transposed matrix in mind! (see rs2_transform_point_to_point) // This is the opposite transpose to the one we do with the extrinsics we get // from the camera... std::swap( extr.rotation[1], extr.rotation[3] ); std::swap( extr.rotation[2], extr.rotation[6] ); std::swap( extr.rotation[5], extr.rotation[7] ); return extr; } depth_to_rgb_calibration::depth_to_rgb_calibration( rs2::frame depth, rs2::frame ir, rs2::frame yuy, rs2::frame prev_yuy, algo::depth_to_rgb_calibration::algo_calibration_info const & cal_info, algo::depth_to_rgb_calibration::algo_calibration_registers const & cal_regs ) : _intr( yuy.get_profile().as< rs2::video_stream_profile >().get_intrinsics() ) , _extr( fix_extrinsics( depth.get_profile().get_extrinsics_to( yuy.get_profile() ), 1000 )) , _from( depth.get_profile().get()->profile ) , _to( yuy.get_profile().get()->profile ) { AC_LOG( DEBUG, "... setting yuy data" ); auto color_profile = yuy.get_profile().as< rs2::video_stream_profile >(); auto yuy_data = (impl::yuy_t const *) yuy.get_data(); auto prev_yuy_data = (impl::yuy_t const *) prev_yuy.get_data(); impl::calib calibration( _intr, _extr ); _algo.set_yuy_data( std::vector< impl::yuy_t >( yuy_data, yuy_data + yuy.get_data_size() / sizeof( impl::yuy_t )), std::vector< impl::yuy_t >( prev_yuy_data, prev_yuy_data + yuy.get_data_size() / sizeof( impl::yuy_t ) ), calibration ); AC_LOG( DEBUG, "... setting ir data" ); auto ir_profile = ir.get_profile().as< rs2::video_stream_profile >(); auto ir_data = (impl::ir_t const *) ir.get_data(); _algo.set_ir_data( std::vector< impl::ir_t >( ir_data, ir_data + ir.get_data_size() / sizeof( impl::ir_t )), ir_profile.width(), ir_profile.height() ); auto si = ((frame_interface *) depth.get() )->get_sensor(); auto cs = VALIDATE_INTERFACE_NO_THROW( si, librealsense::calibrated_sensor ); if( !cs ) { // We can only calibrate depth sensors that supply this interface! throw librealsense::not_implemented_exception( "the depth frame supplied is not from a calibrated_sensor" ); } _dsm_params = cs->get_dsm_params(); AC_LOG( DEBUG, "... setting z data" ); auto z_profile = depth.get_profile().as< rs2::video_stream_profile >(); auto z_data = (impl::z_t const *) depth.get_data(); _algo.set_z_data( std::vector< impl::z_t >( z_data, z_data + depth.get_data_size() / sizeof( impl::z_t ) ), z_profile.get_intrinsics(), _dsm_params, cal_info, cal_regs, depth.as< rs2::depth_frame >().get_units() * 1000.f // same scaling as for extrinsics! ); debug_calibration( "old" ); // If the user has this env var defined, then we write out logs and frames to it // NOTE: The var should end with a directory separator \ or / auto dir_ = getenv( "RS2_DEBUG_DIR" ); if( dir_ ) { std::string dir( dir_ ); dir += std::to_string( depth.get_frame_number() ); #ifdef _WIN32 auto status = _mkdir( dir.c_str() ); #else auto status = mkdir( dir.c_str(), 0700 ); #endif if( status == 0 ) _algo.write_data_to( dir ); else AC_LOG( WARNING, "Failed (" << status << ") to write AC frame data to: " << dir ); } } rs2_calibration_status depth_to_rgb_calibration::optimize( std::function<void( rs2_calibration_status )> call_back ) { #define DISABLE_RS2_CALIBRATION_CHECKS "RS2_AC_DISABLE_RETRIES" try { AC_LOG( DEBUG, "... checking scene validity" ); if( !_algo.is_scene_valid() ) { AC_LOG( ERROR, "Calibration scene was found invalid!" ); call_back( RS2_CALIBRATION_SCENE_INVALID ); if( !getenv( DISABLE_RS2_CALIBRATION_CHECKS ) ) { // Default behavior is to stop AC and trigger a retry return RS2_CALIBRATION_RETRY; } if( getenv( "RS2_AC_INVALID_SCENE_FAIL" ) ) { // Here we don't want a retry, but we also do not want the calibration // to possibly be successful -- fail it AC_LOG( DEBUG, DISABLE_RS2_CALIBRATION_CHECKS << " is on but so is RS2_AC_INVALID_SCENE_FAIL: fail!" ); return RS2_CALIBRATION_FAILED; } AC_LOG( DEBUG, DISABLE_RS2_CALIBRATION_CHECKS << " is on; continuing" ); } AC_LOG( DEBUG, "... optimizing" ); _algo.optimize(); AC_LOG( DEBUG, "... checking result validity" ); if( !_algo.is_valid_results() ) { // Error would have printed inside call_back( RS2_CALIBRATION_BAD_RESULT ); if( !getenv( DISABLE_RS2_CALIBRATION_CHECKS ) ) { // Default behavior is to stop and trigger a retry AC_LOG( DEBUG, DISABLE_RS2_CALIBRATION_CHECKS << " is off; will retry if possible" ); return RS2_CALIBRATION_RETRY; } if( !getenv( "RS2_AC_FORCE_BAD_RESULT" ) ) { // This is mostly for validation use, where we don't want the retries and instead want // to fail on bad results (we don't want to write bad results to the camera!) AC_LOG( DEBUG, DISABLE_RS2_CALIBRATION_CHECKS << " is on; no retries" ); return RS2_CALIBRATION_FAILED; } // Allow forcing of results... be careful! This may damage the camera in AC2! AC_LOG( DEBUG, DISABLE_RS2_CALIBRATION_CHECKS << " is on but so is RS2_AC_FORCE_BAD_RESULT: results will be used!" ); } // AC_LOG( INFO, "Calibration finished; original cost= " << original_cost << " optimized // cost= " << params_curr.cost ); AC_LOG( DEBUG, "... optimization successful!" ); _intr = _algo.get_calibration().get_intrinsics(); _extr = fix_extrinsics( _algo.get_calibration().get_extrinsics(), 0.001f ); _dsm_params = _algo.get_dsm_params(); debug_calibration( "new" ); return RS2_CALIBRATION_SUCCESSFUL; } catch( std::exception const & e ) { AC_LOG( ERROR, "Calibration threw error: " << e.what() ); return RS2_CALIBRATION_FAILED; } } void depth_to_rgb_calibration::debug_calibration( char const * prefix ) { AC_LOG( DEBUG, AC_F_PREC << prefix << " intr[ " << _intr.width << "x" << _intr.height << " ppx: " << _intr.ppx << ", ppy: " << _intr.ppy << ", fx: " << _intr.fx << ", fy: " << _intr.fy << ", model: " << int( _intr.model ) << " coeffs[" << _intr.coeffs[0] << ", " << _intr.coeffs[1] << ", " << _intr.coeffs[2] << ", " << _intr.coeffs[3] << ", " << _intr.coeffs[4] << "] ]" ); AC_LOG( DEBUG, AC_F_PREC << prefix << " extr" << _extr ); AC_LOG( DEBUG, AC_F_PREC << prefix << " dsm" << _dsm_params ); } <|endoftext|>
<commit_before>#include "sqloxx_tests_common.hpp" #include "derived_po.hpp" #include "../database_connection.hpp" #include "../detail/sql_statement_impl.hpp" #include "../detail/sqlite_dbconn.hpp" #include "../sql_statement.hpp" #include <boost/filesystem.hpp> #include <jewel/stopwatch.hpp> #include <cassert> #include <cstdlib> #include <iostream> #include <string> #include <vector> using jewel::Stopwatch; using std::abort; using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using sqloxx::detail::SQLStatementImpl; using sqloxx::detail::SQLiteDBConn; namespace filesystem = boost::filesystem; namespace sqloxx { namespace tests { bool file_exists(filesystem::path const& filepath) { return filesystem::exists ( filesystem::status(filepath) ); } void abort_if_exists(filesystem::path const& filepath) { if (file_exists(filepath)) { cerr << "File named \"" << filepath.string() << "\" already " << "exists. Test aborted." << endl; std::abort(); } return; } void do_speed_test() { string const filename("aaksjh237nsal"); int const loops = 50000; vector<string> statements; statements.push_back ( "insert into dummy(colA, colB) values(3, 'hi')" ); statements.push_back ( "select colA, colB from dummy where colB = " " 'asfkjasdlfkasdfasdf' and colB = '-90982097';" ); statements.push_back ( "insert into dummy(colA, colB) values(198712319, 'aasdfhasdkjhash');" ); statements.push_back ( "select colA, colB from dummy where colA = " " 'noasdsjhasdfkjhasdkfjh' and colB = '-9987293879';" ); vector<string>::size_type const num_statements = statements.size(); string const table_creation_string ( "create table dummy(colA int not null, colB text)" ); // With SQLStatement DatabaseConnection db; db.open(filename); db.execute_sql(table_creation_string); cout << "Timing with SQLStatement." << endl; db.execute_sql("begin"); Stopwatch sw1; for (int i = 0; i != loops; ++i) { SQLStatement s(db, statements[i % num_statements]); // s.step_final(); } sw1.log(); db.execute_sql("end"); boost::filesystem::remove(filename); // With SQLStatementImpl SQLiteDBConn sdbc; sdbc.open(filename); sdbc.execute_sql(table_creation_string); cout << "Timing with SQLStatementImpl." << endl; sdbc.execute_sql("begin"); Stopwatch sw0; for (int i = 0; i != loops; ++i) { SQLStatementImpl s(sdbc, statements[i % num_statements]); // s.step_final(); } sw0.log(); sdbc.execute_sql("end"); boost::filesystem::remove(filename); return; } DatabaseConnectionFixture::DatabaseConnectionFixture(): db_filepath("Testfile_01") { if (filesystem::exists(filesystem::status(db_filepath))) { cerr << "File named \"" << db_filepath.string() << "\" already exists. Test aborted." << endl; abort(); } dbc.open(db_filepath); assert (dbc.is_valid()); } DatabaseConnectionFixture::~DatabaseConnectionFixture() { assert (dbc.is_valid()); filesystem::remove(db_filepath); assert (!file_exists(db_filepath)); } DerivedPOFixture::DerivedPOFixture(): db_filepath("Testfile_dpof"), pdbc(new DerivedDatabaseConnection) { if (filesystem::exists(filesystem::status(db_filepath))) { cerr << "File named \"" << db_filepath.string() << "\" already exists. Test aborted." << endl; abort(); } pdbc->open(db_filepath); assert (pdbc->is_valid()); DerivedPO::setup_tables(*pdbc); } DerivedPOFixture::~DerivedPOFixture() { assert (pdbc->is_valid()); filesystem::remove(db_filepath); assert (!file_exists(db_filepath)); } } // namespace sqloxx } // namespace tests <commit_msg>Factored out some duplicate code in Sqloxx test setup.<commit_after>#include "sqloxx_tests_common.hpp" #include "derived_po.hpp" #include "../database_connection.hpp" #include "../detail/sql_statement_impl.hpp" #include "../detail/sqlite_dbconn.hpp" #include "../sql_statement.hpp" #include <boost/filesystem.hpp> #include <jewel/stopwatch.hpp> #include <cassert> #include <cstdlib> #include <iostream> #include <string> #include <vector> using jewel::Stopwatch; using std::abort; using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using sqloxx::detail::SQLStatementImpl; using sqloxx::detail::SQLiteDBConn; namespace filesystem = boost::filesystem; namespace sqloxx { namespace tests { bool file_exists(filesystem::path const& filepath) { return filesystem::exists ( filesystem::status(filepath) ); } void abort_if_exists(filesystem::path const& filepath) { if (file_exists(filepath)) { cerr << "File named \"" << filepath.string() << "\" already " << "exists. Test aborted." << endl; std::abort(); } return; } void do_speed_test() { string const filename("aaksjh237nsal"); int const loops = 50000; vector<string> statements; statements.push_back ( "insert into dummy(colA, colB) values(3, 'hi')" ); statements.push_back ( "select colA, colB from dummy where colB = " " 'asfkjasdlfkasdfasdf' and colB = '-90982097';" ); statements.push_back ( "insert into dummy(colA, colB) values(198712319, 'aasdfhasdkjhash');" ); statements.push_back ( "select colA, colB from dummy where colA = " " 'noasdsjhasdfkjhasdkfjh' and colB = '-9987293879';" ); vector<string>::size_type const num_statements = statements.size(); string const table_creation_string ( "create table dummy(colA int not null, colB text)" ); // With SQLStatement DatabaseConnection db; db.open(filename); db.execute_sql(table_creation_string); cout << "Timing with SQLStatement." << endl; db.execute_sql("begin"); Stopwatch sw1; for (int i = 0; i != loops; ++i) { SQLStatement s(db, statements[i % num_statements]); // s.step_final(); } sw1.log(); db.execute_sql("end"); boost::filesystem::remove(filename); // With SQLStatementImpl SQLiteDBConn sdbc; sdbc.open(filename); sdbc.execute_sql(table_creation_string); cout << "Timing with SQLStatementImpl." << endl; sdbc.execute_sql("begin"); Stopwatch sw0; for (int i = 0; i != loops; ++i) { SQLStatementImpl s(sdbc, statements[i % num_statements]); // s.step_final(); } sw0.log(); sdbc.execute_sql("end"); boost::filesystem::remove(filename); return; } DatabaseConnectionFixture::DatabaseConnectionFixture(): db_filepath("Testfile_01") { abort_if_exists(db_filepath); dbc.open(db_filepath); assert (dbc.is_valid()); } DatabaseConnectionFixture::~DatabaseConnectionFixture() { assert (dbc.is_valid()); filesystem::remove(db_filepath); assert (!file_exists(db_filepath)); } DerivedPOFixture::DerivedPOFixture(): db_filepath("Testfile_dpof"), pdbc(new DerivedDatabaseConnection) { abort_if_exists(db_filepath); pdbc->open(db_filepath); assert (pdbc->is_valid()); DerivedPO::setup_tables(*pdbc); } DerivedPOFixture::~DerivedPOFixture() { assert (pdbc->is_valid()); filesystem::remove(db_filepath); assert (!file_exists(db_filepath)); } } // namespace sqloxx } // namespace tests <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2003 by Unai Garro * * ugarro@users.sourceforge.net * * * * 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 "recipeviewdialog.h" #include "image.h" #include "propertycalculator.h" RecipeViewDialog::RecipeViewDialog(QWidget *parent, RecipeDB *db, int recipeID):QVBox(parent) { // Initialize UI Elements recipeView=new KHTMLPart(this); // Store/Initialize local variables database=db; // Store the database pointer. loadedRecipe=new Recipe(); properties=new IngredientPropertyList; //----------Load the recipe -------- loadRecipe(recipeID); //this->calculateProperties(); } RecipeViewDialog::~RecipeViewDialog() { } void RecipeViewDialog::loadRecipe(int recipeID) { // Load specified Recipe ID database->loadRecipe(loadedRecipe,recipeID); // Calculate the property list calculateProperties(loadedRecipe,database,properties); // Display the recipe showRecipe(); } void RecipeViewDialog::showRecipe(void) { QString recipeHTML; // Create HTML Code if (loadedRecipe->recipeID<0) { // Show default (empty) recipe recipeHTML="<html><head><title>Title of the Recipe</title></head><body>"; recipeHTML+="<div STYLE=\"position: absolute; top: 30px; left:1%; width: 22%\"> <li>Ingredient 1</li>"; recipeHTML+="<li>Ingredient 2</li> <li>Ingredient 3</li> </div>"; recipeHTML+="<div STYLE=\"position: absolute; top: 30px; left:25%; width: 74%\">"; recipeHTML+="<center><h1>Title of the Recipe</h1></center>"; recipeHTML+="<p>Recipe Instructions </p></div></body></html>"; } else { // Format the loaded recipe as HTML code // title (not shown) recipeHTML= QString("<html><head><title>%1</title></head><body>").arg( loadedRecipe->title); // Left Block (ingredients+properties) // Ingredient Block recipeHTML+="<div STYLE=\"position: absolute; top: 230px; left:1%; width: 220px; height: 240px; background-color:#D4A143 \">"; //Ingredients Ingredient * ing; for ( ing = loadedRecipe->ingList.getFirst(); ing; ing = loadedRecipe->ingList.getNext() ) { recipeHTML+=QString("<li>%2 %3 %1</li>") .arg(ing->name) .arg(ing->amount) .arg(ing->units); } recipeHTML+="</div>"; // Properties Block recipeHTML+="<div STYLE=\"position: absolute; top: 480px; left:1%; width: 220px; background-color: #0071D3\">"; //Properties IngredientProperty * prop; for ( prop = properties->getFirst(); prop; prop = properties->getNext() ) { recipeHTML+=QString("<li>%1: %2 %3</li>") .arg(prop->name) .arg(prop->amount) .arg(prop->units); } recipeHTML+="</div>"; // Instructions Block recipeHTML+="<div STYLE=\"margin-left: 240px;margin-right: 150;margin-top: 80px\">"; recipeHTML+=QString("<center><h1>%1</h1></center>").arg(loadedRecipe->title); recipeHTML+=QString("<p>%1</p></div>").arg(loadedRecipe->instructions); // Photo Block recipeHTML+="<div STYLE=\"position: absolute; top: 50px; left:1%; width: 220px; height: 165px; border: solid #000000 1px \">"; recipeHTML+=QString("<img src=\"/tmp/krecipes_photo.png\" width=220px height=165px> </div>"); // Header recipeHTML+="<div STYLE=\"position: absolute; top: 5px; left:1%; width: 98%; height:30px; background-color: #EDD89E\">"; recipeHTML+=QString("<p align=right >Recipe: #%1</p></div>").arg(loadedRecipe->recipeID); // Close HTML recipeHTML+="</body></html>"; // Store Photo if (!loadedRecipe->photo.isNull()) loadedRecipe->photo.save("/tmp/krecipes_photo.png","PNG"); else {QPixmap dp(defaultPhoto); dp.save("/tmp/krecipes_photo.png","PNG");} } recipeView->begin(KURL("file:/tmp/" )); // Initialize to /tmp, where the photo was stored recipeView->write(recipeHTML); recipeView->end(); } <commit_msg>Some more cosmtic changes: Change ordering<commit_after>/*************************************************************************** * Copyright (C) 2003 by Unai Garro * * ugarro@users.sourceforge.net * * * * 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 "recipeviewdialog.h" #include "image.h" #include "propertycalculator.h" RecipeViewDialog::RecipeViewDialog(QWidget *parent, RecipeDB *db, int recipeID):QVBox(parent) { // Initialize UI Elements recipeView=new KHTMLPart(this); // Store/Initialize local variables database=db; // Store the database pointer. loadedRecipe=new Recipe(); properties=new IngredientPropertyList; //----------Load the recipe -------- loadRecipe(recipeID); //this->calculateProperties(); } RecipeViewDialog::~RecipeViewDialog() { } void RecipeViewDialog::loadRecipe(int recipeID) { // Load specified Recipe ID database->loadRecipe(loadedRecipe,recipeID); // Calculate the property list calculateProperties(loadedRecipe,database,properties); // Display the recipe showRecipe(); } void RecipeViewDialog::showRecipe(void) { QString recipeHTML; // Create HTML Code if (loadedRecipe->recipeID<0) { // Show default (empty) recipe recipeHTML="<html><head><title>Title of the Recipe</title></head><body>"; recipeHTML+="<div STYLE=\"position: absolute; top: 30px; left:1%; width: 22%\"> <li>Ingredient 1</li>"; recipeHTML+="<li>Ingredient 2</li> <li>Ingredient 3</li> </div>"; recipeHTML+="<div STYLE=\"position: absolute; top: 30px; left:25%; width: 74%\">"; recipeHTML+="<center><h1>Title of the Recipe</h1></center>"; recipeHTML+="<p>Recipe Instructions </p></div></body></html>"; } else { // Format the loaded recipe as HTML code // title (not shown) recipeHTML= QString("<html><head><title>%1</title></head><body>").arg( loadedRecipe->title); // Left Block (ingredients+properties) // Ingredient Block recipeHTML+="<div STYLE=\"position: absolute; top: 230px; left:1%; width: 220px; height: 240px; background-color:#D4A143 \">"; //Ingredients Ingredient * ing; for ( ing = loadedRecipe->ingList.getFirst(); ing; ing = loadedRecipe->ingList.getNext() ) { recipeHTML+=QString("<li>%1: %2 %3</li>") .arg(ing->name) .arg(ing->amount) .arg(ing->units); } recipeHTML+="</div>"; // Properties Block recipeHTML+="<div STYLE=\"position: absolute; top: 480px; left:1%; width: 220px; background-color: #0071D3\">"; //Properties IngredientProperty * prop; for ( prop = properties->getFirst(); prop; prop = properties->getNext() ) { recipeHTML+=QString("<li>%1: %2 %3</li>") .arg(prop->name) .arg(prop->amount) .arg(prop->units); } recipeHTML+="</div>"; // Instructions Block recipeHTML+="<div STYLE=\"margin-left: 240px;margin-right: 150;margin-top: 80px\">"; recipeHTML+=QString("<center><h1>%1</h1></center>").arg(loadedRecipe->title); recipeHTML+=QString("<p>%1</p></div>").arg(loadedRecipe->instructions); // Photo Block recipeHTML+="<div STYLE=\"position: absolute; top: 50px; left:1%; width: 220px; height: 165px; border: solid #000000 1px \">"; recipeHTML+=QString("<img src=\"/tmp/krecipes_photo.png\" width=220px height=165px> </div>"); // Header recipeHTML+="<div STYLE=\"position: absolute; top: 5px; left:1%; width: 98%; height:30px; background-color: #EDD89E\">"; recipeHTML+=QString("<p align=right >Recipe: #%1</p></div>").arg(loadedRecipe->recipeID); // Close HTML recipeHTML+="</body></html>"; // Store Photo if (!loadedRecipe->photo.isNull()) loadedRecipe->photo.save("/tmp/krecipes_photo.png","PNG"); else {QPixmap dp(defaultPhoto); dp.save("/tmp/krecipes_photo.png","PNG");} } recipeView->begin(KURL("file:/tmp/" )); // Initialize to /tmp, where the photo was stored recipeView->write(recipeHTML); recipeView->end(); } <|endoftext|>
<commit_before>/// /// @file pmath.hpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef PMATH_HPP #define PMATH_HPP #include <stdint.h> #include <cmath> #include <vector> #include <limits> inline int64_t isquare(int64_t x) { return x * x; } template <typename T1, typename T2, typename T3> inline T2 in_between(T1 min, T2 x, T3 max) { if (x < min) return static_cast<T2>(min); if (x > max) return static_cast<T2>(max); return x; } template <typename T> inline T number_of_bits(T) { return static_cast<T>(sizeof(T) * 8); } /// @brief Round up to the next power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline T next_power_of_2(T x) { x--; for (T i = 1; i < number_of_bits(x); i += i) x |= (x >> i); return ++x; } /// Raise to power template <int N> inline int64_t ipow(int64_t x) { int64_t r = 1; for (int i = 0; i < N; i++) r *= x; return r; } /// Integer suare root template <typename T> inline T isqrt(T x) { T r = static_cast<T>(std::sqrt(static_cast<double>(x))); // correct rounding error while (ipow<2>(r) > x) r--; while (ipow<2>(r + 1) <= x) r++; return r; } /// Integer nth root template <int N, typename T> inline T iroot(T x) { T r = static_cast<T>(std::pow(static_cast<double>(x), 1.0 / N)); // correct rounding error while (ipow<N>(r) > x) r--; while (ipow<N>(r + 1) <= x) r++; return r; } /// Generate a vector with Möbius function values. /// This implementation is based on code by Rick Sladkey /// posted here: http://mathoverflow.net/a/99545 /// inline std::vector<int32_t> make_moebius(int64_t max) { std::vector<int32_t> mu(max + 1, 1); for (int32_t i = 2; i * i <= max; i++) { if (mu[i] == 1) { for (int32_t j = i; j <= max; j += i) mu[j] *= -i; for (int32_t j = i * i; j <= max; j += i * i) mu[j] = 0; } } for (int32_t i = 2; i <= max; i++) { if (mu[i] == i) mu[i] = 1; else if (mu[i] == -i) mu[i] = -1; else if (mu[i] < 0) mu[i] = 1; else if (mu[i] > 0) mu[i] = -1; } return mu; } /// Generate a vector with the least prime /// factors of the integers <= max. /// inline std::vector<int32_t> make_least_prime_factor(int64_t max) { std::vector<int32_t> lpf(max + 1, 1); // phi(x / 1, c) contributes to the sum, thus // set lpf[1] = MAX in order to pass // if (lpf[1] > primes[c]) if (lpf.size() > 1) lpf[1] = std::numeric_limits<int32_t>::max(); for (int32_t i = 2; i * i <= max; i++) if (lpf[i] == 1) for (int32_t j = i * 2; j <= max; j += i) if (lpf[j] == 1) lpf[j] = i; for (int32_t i = 2; i <= max; i++) if (lpf[i] == 1) lpf[i] = i; return lpf; } #endif <commit_msg>Add make_pi(x)<commit_after>/// /// @file pmath.hpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef PMATH_HPP #define PMATH_HPP #include <stdint.h> #include <cmath> #include <vector> #include <limits> inline int64_t isquare(int64_t x) { return x * x; } template <typename T1, typename T2, typename T3> inline T2 in_between(T1 min, T2 x, T3 max) { if (x < min) return static_cast<T2>(min); if (x > max) return static_cast<T2>(max); return x; } template <typename T> inline T number_of_bits(T) { return static_cast<T>(sizeof(T) * 8); } /// @brief Round up to the next power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline T next_power_of_2(T x) { x--; for (T i = 1; i < number_of_bits(x); i += i) x |= (x >> i); return ++x; } /// Raise to power template <int N> inline int64_t ipow(int64_t x) { int64_t r = 1; for (int i = 0; i < N; i++) r *= x; return r; } /// Integer suare root template <typename T> inline T isqrt(T x) { T r = static_cast<T>(std::sqrt(static_cast<double>(x))); // correct rounding error while (ipow<2>(r) > x) r--; while (ipow<2>(r + 1) <= x) r++; return r; } /// Integer nth root template <int N, typename T> inline T iroot(T x) { T r = static_cast<T>(std::pow(static_cast<double>(x), 1.0 / N)); // correct rounding error while (ipow<N>(r) > x) r--; while (ipow<N>(r + 1) <= x) r++; return r; } /// Generate a vector with Möbius function values. /// This implementation is based on code by Rick Sladkey /// posted here: http://mathoverflow.net/a/99545 /// inline std::vector<int32_t> make_moebius(int64_t max) { std::vector<int32_t> mu(max + 1, 1); for (int32_t i = 2; i * i <= max; i++) { if (mu[i] == 1) { for (int32_t j = i; j <= max; j += i) mu[j] *= -i; for (int32_t j = i * i; j <= max; j += i * i) mu[j] = 0; } } for (int32_t i = 2; i <= max; i++) { if (mu[i] == i) mu[i] = 1; else if (mu[i] == -i) mu[i] = -1; else if (mu[i] < 0) mu[i] = 1; else if (mu[i] > 0) mu[i] = -1; } return mu; } /// Generate a vector with the least prime /// factors of the integers <= max. /// inline std::vector<int32_t> make_least_prime_factor(int64_t max) { std::vector<int32_t> lpf(max + 1, 1); // phi(x / 1, c) contributes to the sum, thus // set lpf[1] = MAX in order to pass // if (lpf[1] > primes[c]) if (lpf.size() > 1) lpf[1] = std::numeric_limits<int32_t>::max(); for (int32_t i = 2; i * i <= max; i++) if (lpf[i] == 1) for (int32_t j = i * 2; j <= max; j += i) if (lpf[j] == 1) lpf[j] = i; for (int32_t i = 2; i <= max; i++) if (lpf[i] == 1) lpf[i] = i; return lpf; } /// Generate a vector with the prime counts below max /// using the sieve of Eratosthenes. /// inline std::vector<int32_t> make_pi(int64_t max) { std::vector<char> is_prime(max + 1, 1); for (int64_t i = 2; i * i <= max; i++) if (is_prime[i]) for (int64_t j = i * i; j <= max; j += i * 2) is_prime[j] = 0; std::vector<int32_t> pi(max + 1, 0); int32_t pix = 0; for (int64_t x = 2; x <= max; x++) { pix += is_prime[x]; pi[x] = pix; } return pi; } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2013-2016 Alexander Saprykin <xelfium@gmail.com> * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, see <http://www.gnu.org/licenses/>. */ #ifndef PLIBSYS_TESTS_STATIC # define BOOST_TEST_DYN_LINK #endif #define BOOST_TEST_MODULE patomic_test #include "plibsys.h" #ifdef PLIBSYS_TESTS_STATIC # include <boost/test/included/unit_test.hpp> #else # include <boost/test/unit_test.hpp> #endif /* Actually we couldn't test the work of the atomic operations across the * threads, but at least we can test the sanity of operations */ BOOST_AUTO_TEST_SUITE (BOOST_TEST_MODULE) BOOST_AUTO_TEST_CASE (patomic_general_test) { p_libsys_init (); (void) p_atomic_is_lock_free (); pint atomic_int = 0; p_atomic_int_set (&atomic_int, 10); BOOST_CHECK (p_atomic_int_add (&atomic_int, 5) == 10); BOOST_CHECK (p_atomic_int_get (&atomic_int) == 15); p_atomic_int_add (&atomic_int, -5); BOOST_CHECK (p_atomic_int_get (&atomic_int) == 10); p_atomic_int_inc (&atomic_int); BOOST_CHECK (p_atomic_int_get (&atomic_int) == 11); BOOST_CHECK (p_atomic_int_dec_and_test (&atomic_int) == FALSE); BOOST_CHECK (p_atomic_int_get (&atomic_int) == 10); BOOST_CHECK (p_atomic_int_compare_and_exchange (&atomic_int, 10, -10) == TRUE); BOOST_CHECK (p_atomic_int_get (&atomic_int) == -10); BOOST_CHECK (p_atomic_int_compare_and_exchange (&atomic_int, 10, 20) == FALSE); BOOST_CHECK (p_atomic_int_get (&atomic_int) == -10); p_atomic_int_inc (&atomic_int); BOOST_CHECK (p_atomic_int_get (&atomic_int) == -9); p_atomic_int_set (&atomic_int, 4); BOOST_CHECK (p_atomic_int_get (&atomic_int) == 4); BOOST_CHECK (p_atomic_int_xor ((puint *) &atomic_int, (puint) 1) == 4); BOOST_CHECK (p_atomic_int_get (&atomic_int) == 5); BOOST_CHECK (p_atomic_int_or ((puint *) &atomic_int, (puint) 2) == 5); BOOST_CHECK (p_atomic_int_get (&atomic_int) == 7); BOOST_CHECK (p_atomic_int_and ((puint *) &atomic_int, (puint) 1) == 7); BOOST_CHECK (p_atomic_int_get (&atomic_int) == 1); p_atomic_int_set (&atomic_int, 51); BOOST_CHECK (p_atomic_int_get (&atomic_int) == 51); for (pint i = 51; i > 1; --i) { BOOST_CHECK (p_atomic_int_dec_and_test (&atomic_int) == FALSE); BOOST_CHECK (p_atomic_int_get (&atomic_int) == (i - 1)); } BOOST_CHECK (p_atomic_int_dec_and_test (&atomic_int) == TRUE); BOOST_CHECK (p_atomic_int_get (&atomic_int) == 0); ppointer atomic_pointer = NULL; p_atomic_pointer_set (&atomic_pointer, PUINT_TO_POINTER (P_MAXSIZE)); BOOST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PUINT_TO_POINTER (P_MAXSIZE)); p_atomic_pointer_set (&atomic_pointer, PUINT_TO_POINTER (100)); BOOST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PUINT_TO_POINTER (100)); BOOST_CHECK (p_atomic_pointer_add (&atomic_pointer, (pssize) 100) == 100); BOOST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PUINT_TO_POINTER (200)); p_atomic_pointer_set (&atomic_pointer, PINT_TO_POINTER (4)); BOOST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PINT_TO_POINTER (4)); BOOST_CHECK (p_atomic_pointer_xor (&atomic_pointer, (psize) 1) == 4); BOOST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PINT_TO_POINTER (5)); BOOST_CHECK (p_atomic_pointer_or (&atomic_pointer, (psize) 2) == 5); BOOST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PINT_TO_POINTER (7)); BOOST_CHECK (p_atomic_pointer_and (&atomic_pointer, (psize) 1) == 7); BOOST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PINT_TO_POINTER (1)); BOOST_CHECK (p_atomic_pointer_compare_and_exchange (&atomic_pointer, PUINT_TO_POINTER (1), NULL) == TRUE); BOOST_CHECK (p_atomic_pointer_get (&atomic_pointer) == NULL); p_libsys_shutdown (); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>tests: Move atomic operations on new testing macros<commit_after>/* * Copyright (C) 2013-2017 Alexander Saprykin <xelfium@gmail.com> * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, see <http://www.gnu.org/licenses/>. */ #include "plibsys.h" #include "ptestmacros.h" /* Actually we couldn't test the work of the atomic operations across the * threads, but at least we can test the sanity of operations */ P_TEST_MODULE_INIT (); P_TEST_CASE_BEGIN (patomic_general_test) { p_libsys_init (); (void) p_atomic_is_lock_free (); pint atomic_int = 0; p_atomic_int_set (&atomic_int, 10); P_TEST_CHECK (p_atomic_int_add (&atomic_int, 5) == 10); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == 15); p_atomic_int_add (&atomic_int, -5); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == 10); p_atomic_int_inc (&atomic_int); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == 11); P_TEST_CHECK (p_atomic_int_dec_and_test (&atomic_int) == FALSE); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == 10); P_TEST_CHECK (p_atomic_int_compare_and_exchange (&atomic_int, 10, -10) == TRUE); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == -10); P_TEST_CHECK (p_atomic_int_compare_and_exchange (&atomic_int, 10, 20) == FALSE); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == -10); p_atomic_int_inc (&atomic_int); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == -9); p_atomic_int_set (&atomic_int, 4); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == 4); P_TEST_CHECK (p_atomic_int_xor ((puint *) &atomic_int, (puint) 1) == 4); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == 5); P_TEST_CHECK (p_atomic_int_or ((puint *) &atomic_int, (puint) 2) == 5); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == 7); P_TEST_CHECK (p_atomic_int_and ((puint *) &atomic_int, (puint) 1) == 7); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == 1); p_atomic_int_set (&atomic_int, 51); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == 51); for (pint i = 51; i > 1; --i) { P_TEST_CHECK (p_atomic_int_dec_and_test (&atomic_int) == FALSE); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == (i - 1)); } P_TEST_CHECK (p_atomic_int_dec_and_test (&atomic_int) == TRUE); P_TEST_CHECK (p_atomic_int_get (&atomic_int) == 0); ppointer atomic_pointer = NULL; p_atomic_pointer_set (&atomic_pointer, PUINT_TO_POINTER (P_MAXSIZE)); P_TEST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PUINT_TO_POINTER (P_MAXSIZE)); p_atomic_pointer_set (&atomic_pointer, PUINT_TO_POINTER (100)); P_TEST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PUINT_TO_POINTER (100)); P_TEST_CHECK (p_atomic_pointer_add (&atomic_pointer, (pssize) 100) == 100); P_TEST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PUINT_TO_POINTER (200)); p_atomic_pointer_set (&atomic_pointer, PINT_TO_POINTER (4)); P_TEST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PINT_TO_POINTER (4)); P_TEST_CHECK (p_atomic_pointer_xor (&atomic_pointer, (psize) 1) == 4); P_TEST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PINT_TO_POINTER (5)); P_TEST_CHECK (p_atomic_pointer_or (&atomic_pointer, (psize) 2) == 5); P_TEST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PINT_TO_POINTER (7)); P_TEST_CHECK (p_atomic_pointer_and (&atomic_pointer, (psize) 1) == 7); P_TEST_CHECK (p_atomic_pointer_get (&atomic_pointer) == PINT_TO_POINTER (1)); P_TEST_CHECK (p_atomic_pointer_compare_and_exchange (&atomic_pointer, PUINT_TO_POINTER (1), NULL) == TRUE); P_TEST_CHECK (p_atomic_pointer_get (&atomic_pointer) == NULL); p_libsys_shutdown (); } P_TEST_CASE_END () P_TEST_SUITE_BEGIN() { P_TEST_SUITE_RUN_CASE (patomic_general_test); } P_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "prune.hpp" namespace vg { constexpr size_t PRUNE_THREAD_BUFFER_SIZE = 128 * 1024; pair_hash_set<edge_t> find_edges_to_prune(const HandleGraph& graph, size_t k, size_t edge_max) { // Each thread collects edges to be deleted into a separate buffer. When the buffer grows // large enough, flush it into a shared hash set. pair_hash_set<edge_t> result; auto flush_buffer = [&result](std::vector<edge_t>& buffer) { #pragma omp critical (prune_flush) { for (const edge_t& edge : buffer) { result.insert(edge); } } buffer.clear(); }; // for each position on the forward and reverse of the graph std::vector<std::vector<edge_t>> buffers(get_thread_count()); graph.for_each_handle([&](const handle_t& h) { // for the forward and reverse of this handle // walk k bases from the end, so that any kmer starting on the node will be represented in the tree we build for (auto handle_is_rev : { false, true }) { //cerr << "###########################################" << endl; handle_t handle = handle_is_rev ? graph.flip(h) : h; list<walk_t> walks; // for each position in the node, set up a kmer with that start position and the node end or kmer length as the end position // determine next positions id_t handle_id = graph.get_id(handle); size_t handle_length = graph.get_length(handle); string handle_seq = graph.get_sequence(handle); for (size_t i = 0; i < handle_length; ++i) { pos_t begin = make_pos_t(handle_id, handle_is_rev, handle_length); pos_t end = make_pos_t(handle_id, handle_is_rev, min(handle_length, i+k)); walk_t walk = walk_t(offset(end)-offset(begin), begin, end, handle, 0); if (walk.length < k) { // are we branching over more than one edge? size_t next_count = 0; graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; }); graph.follow_edges(walk.curr, false, [&](const handle_t& next) { if (next_count > 1 && edge_max == walk.forks) { // our next step takes us over the max int tid = omp_get_thread_num(); buffers[tid].push_back(graph.edge_handle(walk.curr, next)); if (buffers[tid].size() >= PRUNE_THREAD_BUFFER_SIZE) { flush_buffer(buffers[tid]); } } else { walks.push_back(walk); auto& todo = walks.back(); todo.curr = next; if (next_count > 1) { ++todo.forks; } } }); } else { walks.push_back(walk); } } // now expand the kmers until they reach k while (!walks.empty()) { // first we check which ones have reached length k in the current handle; for each of these we run lambda and remove them from our list auto walks_end = walks.end(); for (list<walk_t>::iterator q = walks.begin(); q != walks_end; ++q) { auto& walk = *q; // did we reach our target length? if (walk.length >= k) { q = walks.erase(q); } else { id_t curr_id = graph.get_id(walk.curr); size_t curr_length = graph.get_length(walk.curr); bool curr_is_rev = graph.get_is_reverse(walk.curr); size_t take = min(curr_length, k-walk.length); walk.end = make_pos_t(curr_id, curr_is_rev, take); walk.length += take; if (walk.length < k) { // if not, we need to expand through the node then follow on size_t next_count = 0; graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; }); graph.follow_edges(walk.curr, false, [&](const handle_t& next) { if (next_count > 1 && edge_max == walk.forks) { // our next step takes us over the max int tid = omp_get_thread_num(); buffers[tid].push_back(graph.edge_handle(walk.curr, next)); if (buffers[tid].size() >= PRUNE_THREAD_BUFFER_SIZE) { flush_buffer(buffers[tid]); } } else { walks.push_back(walk); auto& todo = walks.back(); todo.curr = next; if (next_count > 1) { ++todo.forks; } } }); q = walks.erase(q); } else { // nothing, we'll remove it next time around } } } } } }, true); // Flush the buffers and return the result. for (std::vector<edge_t>& buffer : buffers) { flush_buffer(buffer); } return result; } } <commit_msg>Use hash sets as buffers<commit_after>#include "prune.hpp" namespace vg { constexpr size_t PRUNE_THREAD_BUFFER_SIZE = 128 * 1024; pair_hash_set<edge_t> find_edges_to_prune(const HandleGraph& graph, size_t k, size_t edge_max) { // Each thread collects edges to be deleted into a separate buffer. When the buffer grows // large enough, flush it into a shared hash set. pair_hash_set<edge_t> result; auto flush_buffer = [&result](pair_hash_set<edge_t>& buffer) { #pragma omp critical (prune_flush) { for (const edge_t& edge : buffer) { result.insert(edge); } } buffer.clear(); }; // for each position on the forward and reverse of the graph std::vector<pair_hash_set<edge_t>> buffers(get_thread_count()); graph.for_each_handle([&](const handle_t& h) { // for the forward and reverse of this handle // walk k bases from the end, so that any kmer starting on the node will be represented in the tree we build for (auto handle_is_rev : { false, true }) { //cerr << "###########################################" << endl; handle_t handle = handle_is_rev ? graph.flip(h) : h; list<walk_t> walks; // for each position in the node, set up a kmer with that start position and the node end or kmer length as the end position // determine next positions id_t handle_id = graph.get_id(handle); size_t handle_length = graph.get_length(handle); string handle_seq = graph.get_sequence(handle); for (size_t i = 0; i < handle_length; ++i) { pos_t begin = make_pos_t(handle_id, handle_is_rev, handle_length); pos_t end = make_pos_t(handle_id, handle_is_rev, min(handle_length, i+k)); walk_t walk = walk_t(offset(end)-offset(begin), begin, end, handle, 0); if (walk.length < k) { // are we branching over more than one edge? size_t next_count = 0; graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; }); graph.follow_edges(walk.curr, false, [&](const handle_t& next) { if (next_count > 1 && edge_max == walk.forks) { // our next step takes us over the max int tid = omp_get_thread_num(); buffers[tid].insert(graph.edge_handle(walk.curr, next)); if (buffers[tid].size() >= PRUNE_THREAD_BUFFER_SIZE) { flush_buffer(buffers[tid]); } } else { walks.push_back(walk); auto& todo = walks.back(); todo.curr = next; if (next_count > 1) { ++todo.forks; } } }); } else { walks.push_back(walk); } } // now expand the kmers until they reach k while (!walks.empty()) { // first we check which ones have reached length k in the current handle; for each of these we run lambda and remove them from our list auto walks_end = walks.end(); for (list<walk_t>::iterator q = walks.begin(); q != walks_end; ++q) { auto& walk = *q; // did we reach our target length? if (walk.length >= k) { q = walks.erase(q); } else { id_t curr_id = graph.get_id(walk.curr); size_t curr_length = graph.get_length(walk.curr); bool curr_is_rev = graph.get_is_reverse(walk.curr); size_t take = min(curr_length, k-walk.length); walk.end = make_pos_t(curr_id, curr_is_rev, take); walk.length += take; if (walk.length < k) { // if not, we need to expand through the node then follow on size_t next_count = 0; graph.follow_edges(walk.curr, false, [&](const handle_t& next) { ++next_count; }); graph.follow_edges(walk.curr, false, [&](const handle_t& next) { if (next_count > 1 && edge_max == walk.forks) { // our next step takes us over the max int tid = omp_get_thread_num(); buffers[tid].insert(graph.edge_handle(walk.curr, next)); if (buffers[tid].size() >= PRUNE_THREAD_BUFFER_SIZE) { flush_buffer(buffers[tid]); } } else { walks.push_back(walk); auto& todo = walks.back(); todo.curr = next; if (next_count > 1) { ++todo.forks; } } }); q = walks.erase(q); } else { // nothing, we'll remove it next time around } } } } } }, true); // Flush the buffers and return the result. for (pair_hash_set<edge_t>& buffer : buffers) { flush_buffer(buffer); } return result; } } <|endoftext|>
<commit_before>#include "quads.hpp" #include <cstddef> // for offsetof Quads::Quads() { glGenBuffers(1, &vertexAndTextureBuf); glGenBuffers(1, &transformBuf); glGenBuffers(1, &indexBuf); } RealQuadID vertexNumberToRealQuadID(unsigned i) { return RealQuadID{i / Quad::QUAD_COMPONENTS}; } unsigned realQuadIDToVertexNumber(RealQuadID id) { return id.value * Quad::QUAD_COMPONENTS; } IndexedQuadID indexNumberToIndexedQuadID(unsigned i) { return IndexedQuadID{i / Quads::INDEX_QUAD_COMPONENTS}; } RealQuadID Quads::addVertex(Quad q) { RealQuadID id = vertexNumberToRealQuadID(vertices.size()); vertices.insert( vertices.end(), std::begin(q.vertex), std::end(q.vertex)); return id; } IndexedQuadID Quads::addIndex(RealQuadID realID) { unsigned i = realQuadIDToVertexNumber(realID); unsigned elements [] = { i+0, i+1, i+3, i+1, i+2, i+3 }; IndexedQuadID id = indexNumberToIndexedQuadID(indices.size()); indices.insert( indices.end(), std::begin(elements), std::end(elements)); Quads::MatrixType mat; transforms.push_back(mat); return id; } unsigned Quads::vertexDataCount() const { return vertices.size(); } unsigned Quads::indexDataCount() const { return indices.size(); } unsigned Quads::transformDataCount() const { return transforms.size(); } unsigned Quads::vertexDataByteCount() const { return vertices.size() * sizeof(Quads::VertexType); } unsigned Quads::indexDataByteCount() const { return indices.size() * sizeof(Quads::IndexType); } unsigned Quads::transformDataByteCount() const { return transforms.size() * sizeof(Quads::MatrixType); } const Quads::VertexType * Quads::vertexData() const { return vertices.data(); } const Quads::IndexType * Quads::indexData() const { return indices.data(); } const Quads::MatrixType * Quads::transformData() const { return transforms.data(); } void Quads::uploadVertices() const { glBindBuffer(GL_ARRAY_BUFFER, vertexAndTextureBuf); glBufferData( GL_ARRAY_BUFFER, vertexDataByteCount(), vertexData(), GL_STATIC_DRAW); } void Quads::uploadIndices() const { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuf); glBufferData( GL_ELEMENT_ARRAY_BUFFER, indexDataByteCount(), indexData(), GL_STATIC_DRAW); } void Quads::uploadTransforms() const { glBindBuffer(GL_ARRAY_BUFFER, transformBuf); glBufferData( GL_ARRAY_BUFFER, transformDataByteCount(), transformData(), GL_STATIC_DRAW ); } void Quads::setupVertexFormat(GLuint location) const { glBindBuffer(GL_ARRAY_BUFFER, vertexAndTextureBuf); glVertexAttribPointer( location, Quads::VertexType::PositionComponents, GL_FLOAT, GL_FALSE, sizeof(Quads::VertexType), (GLvoid*)0 ); glEnableVertexAttribArray(location); } void Quads::setupTextureCoordinateFormat(GLuint location) const { glBindBuffer(GL_ARRAY_BUFFER, vertexAndTextureBuf); glVertexAttribPointer( location, Quads::VertexType::TextureComponents, GL_FLOAT, GL_FALSE, sizeof(Quads::VertexType), (GLvoid*) offsetof(Quads::VertexType, texture) ); glEnableVertexAttribArray(location); } void Quads::setupTransformFormat(GLuint location) const { glBindBuffer(GL_ARRAY_BUFFER, transformBuf); for(unsigned i = 0; i < 4; i++) { glVertexAttribPointer( location + i, 4, GL_FLOAT, GL_FALSE, sizeof(Quads::MatrixType), (GLvoid*) (i * sizeof(glm::vec4)) ); glEnableVertexAttribArray(location + i); glVertexAttribDivisor(location + i, 1); } } Quads::MatrixType & Quads::transform(IndexedQuadID id) { return transforms[id.value]; } void Quads::draw() const { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuf); glDrawElementsInstanced( GL_TRIANGLES, indexDataCount(), Quads::IndexTypeID, 0, transformDataCount() ); } <commit_msg>added assertion for sanity<commit_after>#include "quads.hpp" #include <cstddef> // for offsetof Quads::Quads() { glGenBuffers(1, &vertexAndTextureBuf); glGenBuffers(1, &transformBuf); glGenBuffers(1, &indexBuf); } RealQuadID vertexNumberToRealQuadID(unsigned i) { return RealQuadID{i / Quad::QUAD_COMPONENTS}; } unsigned realQuadIDToVertexNumber(RealQuadID id) { return id.value * Quad::QUAD_COMPONENTS; } IndexedQuadID indexNumberToIndexedQuadID(unsigned i) { return IndexedQuadID{i / Quads::INDEX_QUAD_COMPONENTS}; } RealQuadID Quads::addVertex(Quad q) { RealQuadID id = vertexNumberToRealQuadID(vertices.size()); vertices.insert( vertices.end(), std::begin(q.vertex), std::end(q.vertex)); return id; } IndexedQuadID Quads::addIndex(RealQuadID realID) { unsigned i = realQuadIDToVertexNumber(realID); unsigned elements [] = { i+0, i+1, i+3, i+1, i+2, i+3 }; IndexedQuadID id = indexNumberToIndexedQuadID(indices.size()); indices.insert( indices.end(), std::begin(elements), std::end(elements)); Quads::MatrixType mat; transforms.push_back(mat); assert(id.value == transforms.size() - 1); return id; } unsigned Quads::vertexDataCount() const { return vertices.size(); } unsigned Quads::indexDataCount() const { return indices.size(); } unsigned Quads::transformDataCount() const { return transforms.size(); } unsigned Quads::vertexDataByteCount() const { return vertices.size() * sizeof(Quads::VertexType); } unsigned Quads::indexDataByteCount() const { return indices.size() * sizeof(Quads::IndexType); } unsigned Quads::transformDataByteCount() const { return transforms.size() * sizeof(Quads::MatrixType); } const Quads::VertexType * Quads::vertexData() const { return vertices.data(); } const Quads::IndexType * Quads::indexData() const { return indices.data(); } const Quads::MatrixType * Quads::transformData() const { return transforms.data(); } void Quads::uploadVertices() const { glBindBuffer(GL_ARRAY_BUFFER, vertexAndTextureBuf); glBufferData( GL_ARRAY_BUFFER, vertexDataByteCount(), vertexData(), GL_STATIC_DRAW); } void Quads::uploadIndices() const { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuf); glBufferData( GL_ELEMENT_ARRAY_BUFFER, indexDataByteCount(), indexData(), GL_STATIC_DRAW); } void Quads::uploadTransforms() const { glBindBuffer(GL_ARRAY_BUFFER, transformBuf); glBufferData( GL_ARRAY_BUFFER, transformDataByteCount(), transformData(), GL_STATIC_DRAW ); } void Quads::setupVertexFormat(GLuint location) const { glBindBuffer(GL_ARRAY_BUFFER, vertexAndTextureBuf); glVertexAttribPointer( location, Quads::VertexType::PositionComponents, GL_FLOAT, GL_FALSE, sizeof(Quads::VertexType), (GLvoid*)0 ); glEnableVertexAttribArray(location); } void Quads::setupTextureCoordinateFormat(GLuint location) const { glBindBuffer(GL_ARRAY_BUFFER, vertexAndTextureBuf); glVertexAttribPointer( location, Quads::VertexType::TextureComponents, GL_FLOAT, GL_FALSE, sizeof(Quads::VertexType), (GLvoid*) offsetof(Quads::VertexType, texture) ); glEnableVertexAttribArray(location); } void Quads::setupTransformFormat(GLuint location) const { glBindBuffer(GL_ARRAY_BUFFER, transformBuf); for(unsigned i = 0; i < 4; i++) { glVertexAttribPointer( location + i, 4, GL_FLOAT, GL_FALSE, sizeof(Quads::MatrixType), (GLvoid*) (i * sizeof(glm::vec4)) ); glEnableVertexAttribArray(location + i); glVertexAttribDivisor(location + i, 1); } } Quads::MatrixType & Quads::transform(IndexedQuadID id) { return transforms[id.value]; } void Quads::draw() const { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuf); glDrawElementsInstanced( GL_TRIANGLES, indexDataCount(), Quads::IndexTypeID, 0, transformDataCount() ); } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 "ut_mtheme.h" #include "mtheme_p.h" #include <MApplication> #include <MGConfItem> #include <MLabel> #include <MScalableImage> #include <MTheme> #include <QEventLoop> #include <QtTest> #include <QString> #include <QProcess> #include <QSignalSpy> namespace { const char *KnownIconId = "meegotouch-combobox-indicator"; const char *UnknownIconId = "whatever"; }; void Ut_MTheme::initTestCase() { static int argc = 1; static char *appName = (char*) "./Ut_MTheme"; m_app = new MApplication(argc, &appName); while (MTheme::hasPendingRequests()) { usleep(10000); QCoreApplication::processEvents(); } m_theme = MTheme::instance(); } void Ut_MTheme::cleanupTestCase() { delete m_app; m_app = 0; } void Ut_MTheme::testStyle() { const MStyle *labelStyle1 = m_theme->style("MLabelStyle"); QVERIFY(labelStyle1 != 0); const MStyle *labelStyle2 = m_theme->style("MLabelStyle", QString(), QString(), QString(), M::Landscape); QVERIFY(labelStyle2 != 0); // Check overload behavior of MTheme::style() QCOMPARE(labelStyle1, labelStyle2); const MStyle *labelStyle3 = m_theme->style("MLabelStyle", "MyButton", "active", QString(), M::Landscape); QVERIFY(labelStyle3 != 0); // Loading of invalid styles is not supported, qFatal() is triggered in this case // const MStyle *invalidStyle = m_theme->style("InvalidStyle", "MyButton", "active", QString(), M::Landscape); // QVERIFY(invalidStyle == 0); m_theme->releaseStyle(labelStyle1); m_theme->releaseStyle(labelStyle2); m_theme->releaseStyle(labelStyle3); } void Ut_MTheme::testThemeChangeCompleted() { QSignalSpy spy(m_theme, SIGNAL(themeChangeCompleted())); MGConfItem themeNameItem("/meegotouch/theme/name"); const QString currentThemeName = themeNameItem.value().toString(); if (currentThemeName == QLatin1String("base")) { themeNameItem.set("blanco"); } else { themeNameItem.set("base"); } // Wait until the signal themeChangeCompleted() has been received QEventLoop eventLoop; connect(m_theme, SIGNAL(themeChangeCompleted()), &eventLoop, SLOT(quit())); QTimer::singleShot(30000, &eventLoop, SLOT(quit())); // fallback if themeChangeCompleted() is not send eventLoop.exec(); QCOMPARE(spy.count(), 1); // Reset theme again themeNameItem.set(currentThemeName); eventLoop.exec(); QCOMPARE(spy.count(), 2); } void Ut_MTheme::testPixmap() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *pixmap = m_theme->pixmap(KnownIconId); QVERIFY(pixmap != 0); if (MTheme::hasPendingRequests()) { QVERIFY(pixmap->size().isEmpty()); QCOMPARE(spy.count(), 0); } else { QVERIFY(!pixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); } QVERIFY(isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(pixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapWithSize() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *fixedSizePixmap = m_theme->pixmap(KnownIconId, QSize(100, 150)); QVERIFY(fixedSizePixmap != 0); QCOMPARE(fixedSizePixmap->size(), QSize(100, 150)); QCOMPARE(spy.count(), MTheme::hasPendingRequests() ? 0 : 1); QVERIFY(isIconCached(KnownIconId, fixedSizePixmap->size())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(fixedSizePixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testUnknownPixmap() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *unknownPixmap = m_theme->pixmap(UnknownIconId); QVERIFY(unknownPixmap != 0); if (MTheme::hasPendingRequests()) { QVERIFY(unknownPixmap->size().isEmpty()); QCOMPARE(spy.count(), 0); } else { QVERIFY(!unknownPixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); } QVERIFY(isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(unknownPixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(UnknownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCopy() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *pixmap = m_theme->pixmapCopy(KnownIconId); m_theme->cleanupGarbage(); QVERIFY(pixmap != 0); QVERIFY(!pixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCopyWithSize() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *fixedSizePixmap = m_theme->pixmapCopy(KnownIconId, QSize(100, 150)); m_theme->cleanupGarbage(); QVERIFY(fixedSizePixmap != 0); QCOMPARE(fixedSizePixmap->size(), QSize(100, 150)); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testUnknownPixmapCopy() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *unknownPixmap = m_theme->pixmapCopy(UnknownIconId); m_theme->cleanupGarbage(); QVERIFY(unknownPixmap != 0); QCOMPARE(unknownPixmap->size(), QSize(50, 50)); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCaching() { QCOMPARE(cachedIconCount(), 0); const QPixmap *pixmap = m_theme->pixmap(KnownIconId); QVERIFY(isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); const QPixmap *fixedSizePixmap = m_theme->pixmap(KnownIconId, QSize(100, 150)); QVERIFY(isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 2); const QPixmap *unknownPixmap = m_theme->pixmap(UnknownIconId); QVERIFY(isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 3); m_theme->releasePixmap(pixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 2); m_theme->releasePixmap(fixedSizePixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 1); m_theme->releasePixmap(unknownPixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testApplicationPixmapDirs() { const QPixmap *pixmap1; const QPixmap *pixmap2; m_theme->addPixmapDirectory(qApp->applicationDirPath()); QString pixmap1_id="ut_mtheme"; QString pixmap2_id="ut_mtheme_second"; /*! * We request to local pixmap (ut_mtheme folder) */ pixmap1 = m_theme->pixmap("ut_mtheme"); pixmap2 = m_theme->pixmap("ut_mtheme_second"); /*! * Checking if the pixmaps are different (expected) */ QVERIFY(pixmap1->toImage() != pixmap2->toImage()); QVERIFY(pixmap1->size() != pixmap2->size()); /*! * Releasing pixmaps */ m_theme->releasePixmap(pixmap1); m_theme->releasePixmap(pixmap2); /*! * We released but pixmap still in cached (no clean applied yet) */ QVERIFY(isIconCached(pixmap1_id, QSize())); QVERIFY(isIconCached(pixmap2_id, QSize())); /*! * Cleaning released pixmaps */ m_theme->cleanupGarbage(); /*! * The local pixmaps shouldn't be cached */ QCOMPARE(cachedIconCount(), 0); QVERIFY(!isIconCached(pixmap1_id, QSize())); QVERIFY(!isIconCached(pixmap2_id, QSize())); m_theme->clearPixmapDirectories(); } void Ut_MTheme::testScalableImage() { const MScalableImage *image = m_theme->scalableImage(KnownIconId, 1, 2, 3, 4); QVERIFY(image != 0); int left = -1; int right = -1; int top = -1; int bottom = -1; image->borders(&left, &right, &top, &bottom); QCOMPARE(left, 1); QCOMPARE(right, 2); QCOMPARE(top, 3); QCOMPARE(bottom, 4); const MScalableImage *unknownImage = m_theme->scalableImage(UnknownIconId, 1, 2, 3, 4); QVERIFY(unknownImage != 0); left = right = top = bottom = -1; unknownImage->borders(&left, &right, &top, &bottom); QCOMPARE(left, 1); QCOMPARE(right, 2); QCOMPARE(top, 3); QCOMPARE(bottom, 4); m_theme->releaseScalableImage(image); m_theme->releaseScalableImage(unknownImage); } void Ut_MTheme::testView() { MLabel label(0, 0); MWidgetView *view = m_theme->view(&label); QVERIFY(view != 0); } bool Ut_MTheme::isIconCached(const QString &id, const QSize &size) const { const QSize usedSize = size.isEmpty() ? QSize(0, 0) : size; MThemePrivate *d_ptr = m_theme->d_ptr; QHash<QString, CachedPixmap> pixmapIdentifiers = d_ptr->pixmapIdentifiers; QHashIterator<QString, CachedPixmap> it(pixmapIdentifiers); while (it.hasNext()) { it.next(); if (it.value().imageId == id) { const QString sizeString = QLatin1Char('_') + QString::number(usedSize.width()) + QLatin1Char('_') + QString::number(usedSize.height()); if (it.key().endsWith(sizeString)) { return true; } } } return false; } int Ut_MTheme::cachedIconCount() const { MThemePrivate *d_ptr = m_theme->d_ptr; return d_ptr->pixmapIdentifiers.count(); } void Ut_MTheme::waitForPendingThemeRequests() { if (MTheme::hasPendingRequests()) { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QEventLoop eventLoop; connect(m_theme, SIGNAL(pixmapRequestsFinished()), &eventLoop, SLOT(quit())); QTimer::singleShot(10000, &eventLoop, SLOT(quit())); // fallback if pixmapRequestsFinished() is not send eventLoop.exec(); QCOMPARE(spy.count(), 1); } } QTEST_APPLESS_MAIN(Ut_MTheme) <commit_msg>Fixes: NB#208559 - ut_mtheme fails RevBy: Armin Aberres Details: New logic for the Ut_Mtheme:testThemeChangeCompleted(), now the ut go through all the themes availables and switch to them. Finally it sets again the first one.<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 "ut_mtheme.h" #include "mtheme_p.h" #include <MApplication> #include <MGConfItem> #include <MLabel> #include <MScalableImage> #include <MTheme> #include <QEventLoop> #include <QtTest> #include <QString> #include <QProcess> namespace { const char *KnownIconId = "meegotouch-combobox-indicator"; const char *UnknownIconId = "whatever"; }; void Ut_MTheme::initTestCase() { static int argc = 1; static char *appName = (char*) "./Ut_MTheme"; m_app = new MApplication(argc, &appName); while (MTheme::hasPendingRequests()) { usleep(10000); QCoreApplication::processEvents(); } m_theme = MTheme::instance(); } QSettings *themeFile(const QString &theme) { // Determine whether this is a m theme: // step 1: we need to have index.theme file QDir themeDir(THEMEDIR); const QString themeIndexFileName = themeDir.absolutePath() + QDir::separator() + theme + QDir::separator() + "index.theme"; if (!QFile::exists(themeIndexFileName)) return NULL; // step 2: it needs to be a valid ini file QSettings *themeIndexFile = new QSettings(themeIndexFileName, QSettings::IniFormat); if (themeIndexFile->status() != QSettings::NoError) { delete themeIndexFile; return NULL; } // step 3: we need to have X-MeeGoTouch-Metatheme group in index.theme // remove the X-DUI-Metatheme statement again when duitheme is phased out. if ((!themeIndexFile->childGroups().contains(QString("X-MeeGoTouch-Metatheme"))) &&(!themeIndexFile->childGroups().contains(QString("X-DUI-Metatheme")))) { delete themeIndexFile; return NULL; } return themeIndexFile; } struct ThemeInfo { QString theme; QString themeName; QString themeIcon; }; QList<ThemeInfo> findAvailableThemes() { QList<ThemeInfo> themes; // find all directories under the theme directory QDir themeDir(THEMEDIR); const QFileInfoList directories = themeDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); foreach(const QFileInfo & dir, directories) { ThemeInfo info; const QSettings *themeIndexFile = themeFile(dir.baseName()); if (!themeIndexFile) continue; // check if this theme is visible if (!themeIndexFile->value("X-MeeGoTouch-Metatheme/X-Visible", true).toBool()) { delete themeIndexFile; continue; } info.theme = dir.baseName(); info.themeName = themeIndexFile->value("Desktop Entry/Name", "").toString(); info.themeIcon = themeIndexFile->value("X-MeeGoTouch-Metatheme/X-Icon", "").toString(); // remove this again, when duitheme is phased out if ( info.themeIcon.isEmpty() ) { info.themeIcon = themeIndexFile->value("X-DUI-Metatheme/X-Icon", ""). toString(); } // end remove // ok it's a valid theme. Add it to list of themes themes.append(info); delete themeIndexFile; } return themes; } void Ut_MTheme::cleanupTestCase() { delete m_app; m_app = 0; } void Ut_MTheme::testStyle() { const MStyle *labelStyle1 = m_theme->style("MLabelStyle"); QVERIFY(labelStyle1 != 0); const MStyle *labelStyle2 = m_theme->style("MLabelStyle", QString(), QString(), QString(), M::Landscape); QVERIFY(labelStyle2 != 0); // Check overload behavior of MTheme::style() QCOMPARE(labelStyle1, labelStyle2); const MStyle *labelStyle3 = m_theme->style("MLabelStyle", "MyButton", "active", QString(), M::Landscape); QVERIFY(labelStyle3 != 0); // Loading of invalid styles is not supported, qFatal() is triggered in this case // const MStyle *invalidStyle = m_theme->style("InvalidStyle", "MyButton", "active", QString(), M::Landscape); // QVERIFY(invalidStyle == 0); m_theme->releaseStyle(labelStyle1); m_theme->releaseStyle(labelStyle2); m_theme->releaseStyle(labelStyle3); } void Ut_MTheme::testThemeChangeCompleted() { QList<ThemeInfo> themes = findAvailableThemes(); MGConfItem themeNameItem("/meegotouch/theme/name"); QSignalSpy themeChange(m_theme, SIGNAL(themeChangeCompleted())); QEventLoop eventLoop; const QString initialTheme = themeNameItem.value().toString(); connect(m_theme, SIGNAL(themeChangeCompleted()), &eventLoop, SLOT(quit())); //This time should be same as: THEME_CHANGE_TIMEOUT at mthemedaemon (3 seconds) QTimer::singleShot(3000, &eventLoop, SLOT(quit())); for (int i = 0; i < themes.size(); i++) { //We set every theme available except the current one if (m_theme->currentTheme() != themes[i].theme) { themeNameItem.set(themes[i].theme); QVERIFY(themeNameItem.value().toString() == themes[i].theme); eventLoop.exec(); } } //Coming back to the initial theme themeNameItem.set(initialTheme); eventLoop.exec(); QVERIFY(themeNameItem.value().toString() == initialTheme); //After all we should have so many signals as themes installed due to we go through all the themes QCOMPARE(themeChange.count(), themes.size()); } void Ut_MTheme::testPixmap() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *pixmap = m_theme->pixmap(KnownIconId); QVERIFY(pixmap != 0); if (MTheme::hasPendingRequests()) { QVERIFY(pixmap->size().isEmpty()); QCOMPARE(spy.count(), 0); } else { QVERIFY(!pixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); } QVERIFY(isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(pixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapWithSize() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *fixedSizePixmap = m_theme->pixmap(KnownIconId, QSize(100, 150)); QVERIFY(fixedSizePixmap != 0); QCOMPARE(fixedSizePixmap->size(), QSize(100, 150)); QCOMPARE(spy.count(), MTheme::hasPendingRequests() ? 0 : 1); QVERIFY(isIconCached(KnownIconId, fixedSizePixmap->size())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(fixedSizePixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testUnknownPixmap() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); const QPixmap *unknownPixmap = m_theme->pixmap(UnknownIconId); QVERIFY(unknownPixmap != 0); if (MTheme::hasPendingRequests()) { QVERIFY(unknownPixmap->size().isEmpty()); QCOMPARE(spy.count(), 0); } else { QVERIFY(!unknownPixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); } QVERIFY(isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); waitForPendingThemeRequests(); // Release icon m_theme->releasePixmap(unknownPixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(UnknownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCopy() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *pixmap = m_theme->pixmapCopy(KnownIconId); m_theme->cleanupGarbage(); QVERIFY(pixmap != 0); QVERIFY(!pixmap->size().isEmpty()); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCopyWithSize() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *fixedSizePixmap = m_theme->pixmapCopy(KnownIconId, QSize(100, 150)); m_theme->cleanupGarbage(); QVERIFY(fixedSizePixmap != 0); QCOMPARE(fixedSizePixmap->size(), QSize(100, 150)); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testUnknownPixmapCopy() { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QPixmap *unknownPixmap = m_theme->pixmapCopy(UnknownIconId); m_theme->cleanupGarbage(); QVERIFY(unknownPixmap != 0); QCOMPARE(unknownPixmap->size(), QSize(50, 50)); QCOMPARE(spy.count(), 1); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testPixmapCaching() { QCOMPARE(cachedIconCount(), 0); const QPixmap *pixmap = m_theme->pixmap(KnownIconId); QVERIFY(isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 1); const QPixmap *fixedSizePixmap = m_theme->pixmap(KnownIconId, QSize(100, 150)); QVERIFY(isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 2); const QPixmap *unknownPixmap = m_theme->pixmap(UnknownIconId); QVERIFY(isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 3); m_theme->releasePixmap(pixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(KnownIconId, QSize())); QCOMPARE(cachedIconCount(), 2); m_theme->releasePixmap(fixedSizePixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(KnownIconId, QSize(100, 150))); QCOMPARE(cachedIconCount(), 1); m_theme->releasePixmap(unknownPixmap); m_theme->cleanupGarbage(); QVERIFY(!isIconCached(UnknownIconId, QSize())); QCOMPARE(cachedIconCount(), 0); } void Ut_MTheme::testApplicationPixmapDirs() { const QPixmap *pixmap1; const QPixmap *pixmap2; m_theme->addPixmapDirectory(qApp->applicationDirPath()); QString pixmap1_id="ut_mtheme"; QString pixmap2_id="ut_mtheme_second"; /*! * We request to local pixmap (ut_mtheme folder) */ pixmap1 = m_theme->pixmap("ut_mtheme"); pixmap2 = m_theme->pixmap("ut_mtheme_second"); /*! * Checking if the pixmaps are different (expected) */ QVERIFY(pixmap1->toImage() != pixmap2->toImage()); QVERIFY(pixmap1->size() != pixmap2->size()); /*! * Releasing pixmaps */ m_theme->releasePixmap(pixmap1); m_theme->releasePixmap(pixmap2); /*! * We released but pixmap still in cached (no clean applied yet) */ QVERIFY(isIconCached(pixmap1_id, QSize())); QVERIFY(isIconCached(pixmap2_id, QSize())); /*! * Cleaning released pixmaps */ m_theme->cleanupGarbage(); /*! * The local pixmaps shouldn't be cached */ QCOMPARE(cachedIconCount(), 0); QVERIFY(!isIconCached(pixmap1_id, QSize())); QVERIFY(!isIconCached(pixmap2_id, QSize())); m_theme->clearPixmapDirectories(); } void Ut_MTheme::testScalableImage() { const MScalableImage *image = m_theme->scalableImage(KnownIconId, 1, 2, 3, 4); QVERIFY(image != 0); int left = -1; int right = -1; int top = -1; int bottom = -1; image->borders(&left, &right, &top, &bottom); QCOMPARE(left, 1); QCOMPARE(right, 2); QCOMPARE(top, 3); QCOMPARE(bottom, 4); const MScalableImage *unknownImage = m_theme->scalableImage(UnknownIconId, 1, 2, 3, 4); QVERIFY(unknownImage != 0); left = right = top = bottom = -1; unknownImage->borders(&left, &right, &top, &bottom); QCOMPARE(left, 1); QCOMPARE(right, 2); QCOMPARE(top, 3); QCOMPARE(bottom, 4); m_theme->releaseScalableImage(image); m_theme->releaseScalableImage(unknownImage); } void Ut_MTheme::testView() { MLabel label(0, 0); MWidgetView *view = m_theme->view(&label); QVERIFY(view != 0); } bool Ut_MTheme::isIconCached(const QString &id, const QSize &size) const { const QSize usedSize = size.isEmpty() ? QSize(0, 0) : size; MThemePrivate *d_ptr = m_theme->d_ptr; QHash<QString, CachedPixmap> pixmapIdentifiers = d_ptr->pixmapIdentifiers; QHashIterator<QString, CachedPixmap> it(pixmapIdentifiers); while (it.hasNext()) { it.next(); if (it.value().imageId == id) { const QString sizeString = QLatin1Char('_') + QString::number(usedSize.width()) + QLatin1Char('_') + QString::number(usedSize.height()); if (it.key().endsWith(sizeString)) { return true; } } } return false; } int Ut_MTheme::cachedIconCount() const { MThemePrivate *d_ptr = m_theme->d_ptr; return d_ptr->pixmapIdentifiers.count(); } void Ut_MTheme::waitForPendingThemeRequests() { if (MTheme::hasPendingRequests()) { QSignalSpy spy(m_theme, SIGNAL(pixmapRequestsFinished())); QEventLoop eventLoop; connect(m_theme, SIGNAL(pixmapRequestsFinished()), &eventLoop, SLOT(quit())); QTimer::singleShot(10000, &eventLoop, SLOT(quit())); // fallback if pixmapRequestsFinished() is not send eventLoop.exec(); QCOMPARE(spy.count(), 1); } } QTEST_APPLESS_MAIN(Ut_MTheme) <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <boost/tokenizer.hpp> #include <vector> #include <queue> #include <stdio.h> #include <cstring> #include <sys/wait.h> #include <sys/types.h> using namespace std; using namespace boost; class Connectors //abstract base class so we can dynamically call run { public: virtual ~Connectors() {} virtual int run(int state) = 0; }; class Semicolon : public Connectors { private: vector<char *> vctr; public: Semicolon(vector<string> v) : vctr(50) //constructor creates char* vector { //which stores one command+params vctr.reserve(v.size()); //in a semicolon object for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //makes sure the command ends with a null char } virtual ~Semicolon() { unsigned sz = vctr.size(); for (unsigned i = 0; i < sz; ++i) { vctr.pop_back(); } } //so execvp can determine the end virtual int run(int state) { char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { state = -1; return state; } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if we're in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = waitpid(c_pid, &status, 0)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //returns the state accordingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; class And : public Connectors { private: vector<char *> vctr; public: And(vector<string> v) : vctr(50) { vctr.reserve(v.size()); //store one command+param of type And for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //end with null char } virtual ~And() { unsigned sz = vctr.size(); for (unsigned i = 0; i < sz; ++i) { vctr.pop_back(); } } virtual int run(int state) { if (state != 1) //return if the previous command failed { return state; } char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { state = -1; return state; } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if we're in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = waitpid(c_pid, &status, 0)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //outputs the state accordingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; class Or : public Connectors { private: vector<char *> vctr; public: Or(vector<string> v) : vctr(50) //stores one command+params of type Or { vctr.reserve(v.size()); for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //end with null } virtual ~Or() { unsigned sz = vctr.size(); for (unsigned i = 0; i < sz; ++i) { vctr.pop_back(); } } virtual int run(int state) { if (state != 0) //return if the previous command succeeded { return state; } char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { state = -1; return state; } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if we're in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = waitpid(c_pid, &status, 0)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //outputs the state accodingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; int main() { int w = 0; while (w == 0) { // extra credit part char *username; int host; if ((username = getlogin()) != NULL) // get the username { char name[101]; int len = 100; if ((host = gethostname(name, len)) == 0) // get the hostname { cout << username << "@" << name << "$ "; } else { cout << "$ "; //outputs terminal $ } } else { cout << "$ "; } string input; getline(cin, input); //gets user input //containers we'll use for storage vector< vector<string> > v; vector<string> t; vector<Connectors*> objects; queue<string> q; int column = 0; //creates tokenizer and char separator to parse input typedef tokenizer<char_separator<char> > tokenizer; char_separator<char> sep(" ", ";#|&()"); tokenizer tokens(input, sep); bool lastVal = 0; bool firstVal = 0; //checks for placement of connectors for (tokenizer::iterator check = tokens.begin(); check != tokens.end(); ++check) { if (check == tokens.begin()) { if ((*check == "|") || (*check == "&") || (*check == ";")) { firstVal = 1; } } tokenizer::iterator count = check; ++count; if (count == tokens.end()) { if ((*check == "|") || (*check == "&")) { lastVal = 1; } } } //loops again if the input begins or ends with a connector if (firstVal == 1) { cout << "beginning of input cannot be a connector" << endl; continue; } if (lastVal == 1) { cout << "end of input cannot be a connector" << endl; continue; } bool flag = 0; //flag to check when to start a new column bool wrong = 0; //holds commands in a 2d vector //pushes commands into 2d vector and pushes connectors into a queue for (tokenizer::iterator itr = tokens.begin(); itr != tokens.end(); ++itr) { tokenizer::iterator temp = itr; if (*itr == ";") { ++temp; if (temp != tokens.end()) { if (*temp == *itr) { cout << "cannot have multiple semicolons" << endl; wrong = 1; break; } } q.push(*itr); column = column + 1; flag = 0; } else if ((*itr == "|") || (*itr == "&")) { ++temp; if (*temp != *itr) { cout << "cannot enter single connector" << endl; wrong = 1; break; } ++temp; if (*temp == *itr) { cout << "cannot enter 3+ connector" << endl; wrong = 1; break; } q.push(*itr); //pushes connector into queue column = column + 1; //increments column flag = 0; ++itr; //extra increments itr to not test second connector in pair } else if (*itr == "#") { break; //if there's a comment, break out of loop } else { if (*itr == "(") { v.push_back(t); v.at(column).push_back(*itr); column = column + 1; flag = 0; continue; } else if (*itr == ")") { column = column + 1; v.push_back(t); v.at(column).push_back(*itr); column = column + 1; flag = 0; continue; } else if (!flag) { v.push_back(t); //starts a new column v.at(column).push_back(*itr); flag = 1; } else { //push value into position v.at(column).push_back(*itr); } } } //checks the contents of v //for (unsigned i = 0; i < v.size(); ++i) //{ //for (unsigned j = 0; j < v.at(i).size(); ++j) //{ //cout << v.at(i).at(j) << " / "; //} //} //loops if wrong amt of connectors are entered if (wrong == 1) { continue; } //this part of the code creates a temp vector current which holds //a single command+param chunk at a time //then determines the connector previous to the command its told to run //it then creates the corresponding connector class type object //and pushes the new object into a vector of Connectors pointers bool first = 1; bool pflag = 0; string ptype = ""; vector<string> r; vector < vector<string> > paren; int col = 0; queue<string> pqu; vector<string> current; for (unsigned i = 0; i < v.size(); ++i) { for (unsigned j = 0; j < v.at(i).size(); ++j) { current.push_back(v.at(i).at(j)); } if (current.at(0) == "(") { first = 0; pflag = 1; ptype = q.front(); q.pop(); continue; } if (!q.empty() && first != 1) { if (pflag) { if (current.at(0) == ")") { pflag = 0; if (ptype == ";") { objects.push_back(new Psemicolon(paren, pqu)); } if (ptype == "&") { objects.push_back(new Pand(paren, pqu)); } if (ptype == "|") { objects.push_back(new Por(paren, pqu)); } paren.clear(); while (!pqu.empty()) { pqu.pop(); } } else { paren.push_back(r); for (unsigned k = 0; k < current.size(); ++k) { paren.at(col).push_back(current.at(k)); } col = col + 1; pqu.push(q.front()); q.pop(); } continue; } if (q.front() == ";") { objects.push_back(new Semicolon(current)); q.pop(); } if (q.front() == "|") { objects.push_back(new Or(current)); q.pop(); } if (q.front() == "&") { objects.push_back(new And(current)); q.pop(); } } if (first == 1) { objects.push_back(new Semicolon(current)); first = 0; } current.clear(); } int beg = 0; int durr = 0; //this loop goes through the object vector and calls run on each //object, dynamically calling the run of the class type //cout << "Size: " << objects.size() << endl; for (unsigned i = 0; i < objects.size(); ++i) { //cout << "Curr size: " << objects.size() << endl; durr = objects.at(i)->run(beg); //cout << "State after run: " << durr << endl; //check for if exit is called if (durr == -1) { break; } beg = durr; } //deletes the dynamically allocated memory Connectors *p; for (vector<Connectors*>::iterator ptr = objects.begin(); ptr != objects.end(); ++ptr) { p = *ptr; delete p; } p = NULL; //makes sure to end program if exit is called if (durr == -1) { break; } } return 0; } <commit_msg>fixed error in mai with queue<commit_after>#include <iostream> #include <string> #include <boost/tokenizer.hpp> #include <vector> #include <queue> #include <stdio.h> #include <cstring> #include <sys/wait.h> #include <sys/types.h> using namespace std; using namespace boost; class Connectors //abstract base class so we can dynamically call run { public: virtual ~Connectors() {} virtual int run(int state) = 0; }; class Semicolon : public Connectors { private: vector<char *> vctr; public: Semicolon(vector<string> v) : vctr(50) //constructor creates char* vector { //which stores one command+params vctr.reserve(v.size()); //in a semicolon object for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //makes sure the command ends with a null char } virtual ~Semicolon() { unsigned sz = vctr.size(); for (unsigned i = 0; i < sz; ++i) { vctr.pop_back(); } } //so execvp can determine the end virtual int run(int state) { char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { state = -1; return state; } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if we're in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = waitpid(c_pid, &status, 0)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //returns the state accordingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; class And : public Connectors { private: vector<char *> vctr; public: And(vector<string> v) : vctr(50) { vctr.reserve(v.size()); //store one command+param of type And for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //end with null char } virtual ~And() { unsigned sz = vctr.size(); for (unsigned i = 0; i < sz; ++i) { vctr.pop_back(); } } virtual int run(int state) { if (state != 1) //return if the previous command failed { return state; } char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { state = -1; return state; } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if we're in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = waitpid(c_pid, &status, 0)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //outputs the state accordingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; class Or : public Connectors { private: vector<char *> vctr; public: Or(vector<string> v) : vctr(50) //stores one command+params of type Or { vctr.reserve(v.size()); for (unsigned i = 0; i < v.size(); ++i) { vctr[i] = const_cast<char*>(v[i].c_str()); } vctr.push_back(NULL); //end with null } virtual ~Or() { unsigned sz = vctr.size(); for (unsigned i = 0; i < sz; ++i) { vctr.pop_back(); } } virtual int run(int state) { if (state != 0) //return if the previous command succeeded { return state; } char **pointer = &vctr[0]; //points to vctr we'll use for execvp string ex = "exit"; string p = pointer[0]; if (p == ex) // check if the command entered is exit { state = -1; return state; } pid_t c_pid, pid; int status; c_pid = fork(); if (c_pid < 0) //checks if fork failed { perror("fork failed"); state = 0; return state; } else if (c_pid == 0) //if we're in the child, call execvp { execvp(pointer[0], pointer); perror("execvp failed"); exit(127); } else //if in the parent, wait for child to terminate { //checks if wait fails if ((pid = waitpid(c_pid, &status, 0)) < 0) { perror("wait failed"); state = 0; return state; } //checks whether the child succeeded or not //outputs the state accodingly if (status == 0) { state = 1; //if it succeeded, set the state to true return state; } else { state = 0; return state; } } return 0; } }; int main() { int w = 0; while (w == 0) { // extra credit part char *username; int host; if ((username = getlogin()) != NULL) // get the username { char name[101]; int len = 100; if ((host = gethostname(name, len)) == 0) // get the hostname { cout << username << "@" << name << "$ "; } else { cout << "$ "; //outputs terminal $ } } else { cout << "$ "; } string input; getline(cin, input); //gets user input //containers we'll use for storage vector< vector<string> > v; vector<string> t; vector<Connectors*> objects; queue<string> q; int column = 0; //creates tokenizer and char separator to parse input typedef tokenizer<char_separator<char> > tokenizer; char_separator<char> sep(" ", ";#|&()"); tokenizer tokens(input, sep); bool lastVal = 0; bool firstVal = 0; //checks for placement of connectors for (tokenizer::iterator check = tokens.begin(); check != tokens.end(); ++check) { if (check == tokens.begin()) { if ((*check == "|") || (*check == "&") || (*check == ";")) { firstVal = 1; } } tokenizer::iterator count = check; ++count; if (count == tokens.end()) { if ((*check == "|") || (*check == "&")) { lastVal = 1; } } } //loops again if the input begins or ends with a connector if (firstVal == 1) { cout << "beginning of input cannot be a connector" << endl; continue; } if (lastVal == 1) { cout << "end of input cannot be a connector" << endl; continue; } bool flag = 0; //flag to check when to start a new column bool wrong = 0; //holds commands in a 2d vector //pushes commands into 2d vector and pushes connectors into a queue for (tokenizer::iterator itr = tokens.begin(); itr != tokens.end(); ++itr) { tokenizer::iterator temp = itr; if (*itr == ";") { ++temp; if (temp != tokens.end()) { if (*temp == *itr) { cout << "cannot have multiple semicolons" << endl; wrong = 1; break; } } q.push(*itr); column = column + 1; flag = 0; } else if ((*itr == "|") || (*itr == "&")) { ++temp; if (*temp != *itr) { cout << "cannot enter single connector" << endl; wrong = 1; break; } ++temp; if (*temp == *itr) { cout << "cannot enter 3+ connector" << endl; wrong = 1; break; } q.push(*itr); //pushes connector into queue column = column + 1; //increments column flag = 0; ++itr; //extra increments itr to not test second connector in pair } else if (*itr == "#") { break; //if there's a comment, break out of loop } else { if (*itr == "(") { v.push_back(t); v.at(column).push_back(*itr); column = column + 1; flag = 0; continue; } else if (*itr == ")") { column = column + 1; v.push_back(t); v.at(column).push_back(*itr); column = column + 1; flag = 0; continue; } else if (!flag) { v.push_back(t); //starts a new column v.at(column).push_back(*itr); flag = 1; } else { //push value into position v.at(column).push_back(*itr); } } } //checks the contents of v //for (unsigned i = 0; i < v.size(); ++i) //{ //for (unsigned j = 0; j < v.at(i).size(); ++j) //{ //cout << v.at(i).at(j) << " / "; //} //} //loops if wrong amt of connectors are entered if (wrong == 1) { continue; } //this part of the code creates a temp vector current which holds //a single command+param chunk at a time //then determines the connector previous to the command its told to run //it then creates the corresponding connector class type object //and pushes the new object into a vector of Connectors pointers bool first = 1; bool pflag = 0; string ptype = ""; vector<string> r; vector < vector<string> > paren; int col = 0; queue<string> pqu; vector<string> current; for (unsigned i = 0; i < v.size(); ++i) { for (unsigned j = 0; j < v.at(i).size(); ++j) { current.push_back(v.at(i).at(j)); } if (current.at(0) == "(") { first = 0; pflag = 1; ptype = q.front(); q.pop(); continue; } if (!q.empty() && first != 1) { if (pflag == 1) { if (current.at(0) == ")") { pflag = 0; if (ptype == ";") { //objects.push_back(new Psemicolon(paren, pqu)); } if (ptype == "&") { //objects.push_back(new Pand(paren, pqu)); } if (ptype == "|") { //objects.push_back(new Por(paren, pqu)); } paren.clear(); while (!pqu.empty()) { pqu.pop(); } } else { paren.push_back(r); for (unsigned k = 0; k < current.size(); ++k) { paren.at(col).push_back(current.at(k)); } col = col + 1; pqu.push(q.front()); q.pop(); } continue; } if (q.front() == ";") { objects.push_back(new Semicolon(current)); } if (q.front() == "|") { objects.push_back(new Or(current)); } if (q.front() == "&") { objects.push_back(new And(current)); } q.pop(); } if (first == 1) { objects.push_back(new Semicolon(current)); first = 0; } current.clear(); } int beg = 0; int durr = 0; //this loop goes through the object vector and calls run on each //object, dynamically calling the run of the class type //cout << "Size: " << objects.size() << endl; for (unsigned i = 0; i < objects.size(); ++i) { //cout << "Curr size: " << objects.size() << endl; durr = objects.at(i)->run(beg); //cout << "State after run: " << durr << endl; //check for if exit is called if (durr == -1) { break; } beg = durr; } //deletes the dynamically allocated memory Connectors *p; for (vector<Connectors*>::iterator ptr = objects.begin(); ptr != objects.end(); ++ptr) { p = *ptr; delete p; } p = NULL; //makes sure to end program if exit is called if (durr == -1) { break; } } return 0; } <|endoftext|>
<commit_before>#pragma once #include <vector> #include <fstream> #include <iostream> #include "concurrentqueue.h" #include "camera.hpp" #include "light.hpp" #include "object.hpp" #include "color.hpp" #include "utility.hpp" #include "ray.hpp" class Scene { public: struct { unsigned thread_worker = std::thread::hardware_concurrency(); unsigned trace_depth = 10; float trace_bias = 1e-4; Color environment_color = Color::GRAY; } config; private: const Camera* camera; std::vector<const Light*> lights; std::vector<const Object*> objects; Color* frame; Color trace(const Ray &ray, float refractive_index = 1, unsigned depth = 0) const { auto color = config.environment_color; if (depth > config.trace_depth) { return color; } float distance = std::numeric_limits<float>::max(); const Object* object = nullptr; const Light* light = nullptr; for (auto &o : objects) { float length = o->intersect(ray); if (length < distance) { distance = length; object = o; } } for (auto &l : lights) { float length = l->intersect(ray); if (length < distance) { distance = length; light = l; } } if (light != nullptr) { return light->color; } if (object == nullptr) { return color; } auto point = ray.source + ray.direction * distance; auto normal = object->get_normal(point); for (auto &l : lights) { auto illuminate = l->illuminate(point + normal * config.trace_bias, objects); // diffusive shading if (object->material.k_diffusive > 0) { float dot = std::max(.0f, normal.dot(-illuminate.direction)); color += object->material.k_diffusive * illuminate.intensity * dot; } // specular shading (phong's model) if (object->material.k_specular > 0) { auto reflective_direction = ray.direction.reflect(normal); float dot = std::max(.0f, ray.direction.dot(reflective_direction)); color += object->material.k_specular * illuminate.intensity * powf(dot, 20.f); } } // reflection if (object->material.k_reflective > 0) { float k_diffuse_reflect = 0; if (k_diffuse_reflect > 0 && depth < 2) { // Vector RP = ray.direction.reflect(normal); // Vector RN1 = Vector(RP.z, RP.y, -RP.x); // Vector RN2 = RP.det(RN1); // Color c(0, 0, 0); // for (int i = 0; i < 128; ++i) { // float len = randf() * k_diffuse_reflect; // float angle = static_cast<float>(randf() * 2 * M_PI); // float xoff = len * cosf(angle), yoff = len * sinf(angle); // Vector R = (RP + RN1 * xoff + RN2 * yoff * k_diffuse_reflect).normalize(); // Ray ray_reflect(point + R * config.trace_bias, R); // c += object->material.k_reflective * trace(ray_reflect, refractive_index, depth + 1); // } // color += c / 128.; } else { auto reflective_direction = ray.direction.reflect(normal); auto reflective_ray = Ray(point + reflective_direction * config.trace_bias, reflective_direction); color += object->material.k_reflective * trace(reflective_ray, refractive_index, depth + 1); } } // refraction if (object->material.k_refractive > 0) { auto refractive_direction = ray.direction.refract(normal, refractive_index / object->material.k_refractive_index); if (refractive_direction != Vector::ZERO) { auto refractive_ray = Ray(point + refractive_direction * config.trace_bias, refractive_direction); color += object->material.k_refractive * trace(refractive_ray, object->material.k_refractive_index, depth + 1); } } return color * object->get_color(point); } public: Scene(const Camera* camera) { this->camera = camera; this->frame = new Color[camera->height * camera->width]; } void add(const Light* light) { lights.push_back(light); } void add(const Object* object) { objects.push_back(object); } void render() { auto start = std::chrono::high_resolution_clock::now(); std::cerr << "start rendering with " << config.thread_worker << " thread workers"; moodycamel::ConcurrentQueue<std::pair<int, int> > queue; for (int y = 0; y < camera->height; ++y) for (int x = 0; x < camera->width; ++x) queue.enqueue(std::make_pair(x, y)); std::atomic<unsigned> counter(0); std::vector<std::thread> workers; for (int i = 0; i < config.thread_worker; ++i) { auto render = [&] { for (std::pair<unsigned, unsigned> item; queue.try_dequeue(item); ++counter) { auto x = item.first, y = item.second; auto ray = camera->ray(x, y); frame[y * camera->width + x] = trace(ray); } }; workers.push_back(std::thread(render)); } for (unsigned i; (i = counter.load()) < camera->width * camera->height; ) { auto now = std::chrono::high_resolution_clock::now(); std::cerr << "\rrendered " << i << "/" << camera->width * camera->height << " pixels with " << config.thread_worker << " thread workers" << " in " << (now - start).count() / 1e9 << " seconds"; std::this_thread::sleep_for(std::chrono::milliseconds(50)); } for (auto &worker : workers) { worker.join(); } auto now = std::chrono::high_resolution_clock::now(); std::cerr << std::endl << "done in " << (now - start).count() / 1e9 << " seconds" << std::endl; } void save(const std::string &name) const { std::ofstream ofs(name, std::ios::out | std::ios::binary); ofs << "P6\n" << camera->width << " " << camera->height << "\n255\n"; for (unsigned i = 0; i < camera->height * camera->width; ++i) { ofs << static_cast<char>(clamp(frame[i].x, 0, 1) * 255) << static_cast<char>(clamp(frame[i].y, 0, 1) * 255) << static_cast<char>(clamp(frame[i].z, 0, 1) * 255); } ofs.close(); } };<commit_msg>fix ambient shading<commit_after>#pragma once #include <vector> #include <fstream> #include <iostream> #include "concurrentqueue.h" #include "camera.hpp" #include "light.hpp" #include "object.hpp" #include "color.hpp" #include "utility.hpp" #include "ray.hpp" class Scene { public: struct { unsigned thread_worker = std::thread::hardware_concurrency(); unsigned trace_depth = 10; float trace_bias = 1e-4; Color environment_color = Color::GRAY; } config; private: const Camera* camera; std::vector<const Light*> lights; std::vector<const Object*> objects; Color* frame; Color trace(const Ray &ray, float refractive_index = 1, unsigned depth = 0) const { if (depth > config.trace_depth) { return config.environment_color; } float distance = std::numeric_limits<float>::max(); const Object* object = nullptr; const Light* light = nullptr; for (auto &o : objects) { float length = o->intersect(ray); if (length < distance) { distance = length; object = o; } } for (auto &l : lights) { float length = l->intersect(ray); if (length < distance) { distance = length; light = l; } } if (light != nullptr) { return light->color; } if (object == nullptr) { return config.environment_color; } auto color = Color::ZERO; auto point = ray.source + ray.direction * distance; auto normal = object->get_normal(point); for (auto &l : lights) { auto illuminate = l->illuminate(point + normal * config.trace_bias, objects); // diffusive shading if (object->material.k_diffusive > 0) { float dot = std::max(.0f, normal.dot(-illuminate.direction)); color += object->material.k_diffusive * illuminate.intensity * dot; } // specular shading (phong's model) if (object->material.k_specular > 0) { auto reflective_direction = ray.direction.reflect(normal); float dot = std::max(.0f, ray.direction.dot(reflective_direction)); color += object->material.k_specular * illuminate.intensity * powf(dot, 20.f); } } // reflection if (object->material.k_reflective > 0) { float k_diffuse_reflect = 0; if (k_diffuse_reflect > 0 && depth < 2) { // Vector RP = ray.direction.reflect(normal); // Vector RN1 = Vector(RP.z, RP.y, -RP.x); // Vector RN2 = RP.det(RN1); // Color c(0, 0, 0); // for (int i = 0; i < 128; ++i) { // float len = randf() * k_diffuse_reflect; // float angle = static_cast<float>(randf() * 2 * M_PI); // float xoff = len * cosf(angle), yoff = len * sinf(angle); // Vector R = (RP + RN1 * xoff + RN2 * yoff * k_diffuse_reflect).normalize(); // Ray ray_reflect(point + R * config.trace_bias, R); // c += object->material.k_reflective * trace(ray_reflect, refractive_index, depth + 1); // } // color += c / 128.; } else { auto reflective_direction = ray.direction.reflect(normal); auto reflective_ray = Ray(point + reflective_direction * config.trace_bias, reflective_direction); color += object->material.k_reflective * trace(reflective_ray, refractive_index, depth + 1); } } // refraction if (object->material.k_refractive > 0) { auto refractive_direction = ray.direction.refract(normal, refractive_index / object->material.k_refractive_index); if (refractive_direction != Vector::ZERO) { auto refractive_ray = Ray(point + refractive_direction * config.trace_bias, refractive_direction); color += object->material.k_refractive * trace(refractive_ray, object->material.k_refractive_index, depth + 1); } } return config.environment_color + color * object->get_color(point); } public: Scene(const Camera* camera) { this->camera = camera; this->frame = new Color[camera->height * camera->width]; } void add(const Light* light) { lights.push_back(light); } void add(const Object* object) { objects.push_back(object); } void render() { auto start = std::chrono::high_resolution_clock::now(); std::cerr << "start rendering with " << config.thread_worker << " thread workers"; moodycamel::ConcurrentQueue<std::pair<int, int> > queue; for (int y = 0; y < camera->height; ++y) for (int x = 0; x < camera->width; ++x) queue.enqueue(std::make_pair(x, y)); std::atomic<unsigned> counter(0); std::vector<std::thread> workers; for (int i = 0; i < config.thread_worker; ++i) { auto render = [&] { for (std::pair<unsigned, unsigned> item; queue.try_dequeue(item); ++counter) { auto x = item.first, y = item.second; auto ray = camera->ray(x, y); frame[y * camera->width + x] = trace(ray); } }; workers.push_back(std::thread(render)); } for (unsigned i; (i = counter.load()) < camera->width * camera->height; ) { auto now = std::chrono::high_resolution_clock::now(); std::cerr << "\rrendered " << i << "/" << camera->width * camera->height << " pixels with " << config.thread_worker << " thread workers" << " in " << (now - start).count() / 1e9 << " seconds"; std::this_thread::sleep_for(std::chrono::milliseconds(50)); } for (auto &worker : workers) { worker.join(); } auto now = std::chrono::high_resolution_clock::now(); std::cerr << std::endl << "done in " << (now - start).count() / 1e9 << " seconds" << std::endl; } void save(const std::string &name) const { std::ofstream ofs(name, std::ios::out | std::ios::binary); ofs << "P6\n" << camera->width << " " << camera->height << "\n255\n"; for (unsigned i = 0; i < camera->height * camera->width; ++i) { ofs << static_cast<char>(clamp(frame[i].x, 0, 1) * 255) << static_cast<char>(clamp(frame[i].y, 0, 1) * 255) << static_cast<char>(clamp(frame[i].z, 0, 1) * 255); } ofs.close(); } };<|endoftext|>
<commit_before>/* * ============================================================================ * Filename: slave.hxx * Description: Slave side implementation for flihabi network * Version: 1.0 * Created: 04/26/2015 02:40:40 AM * Revision: none * Compiler: gcc * Author: Rafael Gozlan, rafael.gozlan@epita.fr * Organization: Flihabi * ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <iostream> #include <string> #include "slave.hh" #include "listener.hh" // PUBLIC METHODS Slave::Slave() { std::string ip = getServerAddress(); connectToServer(ip, CONNECTION_PORT); } std::string Slave::getBytecode() { return ""; } void Slave::send_bytecode(std::string bytecode) { bytecode = ""; } // PRIVATE METHODS std::string Slave::getServerAddress() { Socket *s = listen(BROADCAST_PORT); close(s->sockfd); return s->ip; } void Slave::connectToServer(std::string ip, int port) { int sockfd, numbytes; char buf[100]; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; std::cout << "Trying to connect to " << ip << " " << port << std::endl; if ((rv = getaddrinfo(ip.c_str(), std::to_string(port).c_str(), &hints, &servinfo)) != 0) { fprintf(stderr, "Slave: getaddrinfo: %s\n", gai_strerror(rv)); return; } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("Slave: failed to get socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("Slave: failed to connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); printf("Slave: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure printf("Slave: connecting to %s\n", s); if (send(sockfd, CONNECTION_MSG, strlen(CONNECTION_MSG), 0) == -1) perror("Slave: sending Hello!"); printf("Slave: connecting to %s\n", s); if ((numbytes = recv(sockfd, buf, 100-1, 0)) == -1) { perror("Slave: failed to recv the connection msg"); exit(1); } buf[numbytes] = '\0'; printf("Slave: received '%s'\n",buf); sockfd_ = sockfd; } <commit_msg>Add bytecode receiver<commit_after>/* * ============================================================================ * Filename: slave.hxx * Description: Slave side implementation for flihabi network * Version: 1.0 * Created: 04/26/2015 02:40:40 AM * Revision: none * Compiler: gcc * Author: Rafael Gozlan, rafael.gozlan@epita.fr * Organization: Flihabi * ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <iostream> #include <string> #include "slave.hh" #include "listener.hh" // PUBLIC METHODS Slave::Slave() { std::string ip = getServerAddress(); connectToServer(ip, CONNECTION_PORT); } std::string Slave::getBytecode() { int nbRecv; char buf[MAX_BYTECODE_LEN]; std::cout << "Slave: Waiting for bytecode..." << std::endl; if ((nbRecv = recv(sockfd_, buf, MAX_BYTECODE_LEN-1, 0)) == -1) { perror("Slave: failed to recv bytecode"); exit(1); } buf[nbRecv] = '\0'; std::cout << "Slave: received: " << std::string(buf) << std::endl; return std::string(buf); } void Slave::send_bytecode(std::string bytecode) { bytecode = ""; } // PRIVATE METHODS std::string Slave::getServerAddress() { Socket *s = listen(BROADCAST_PORT); close(s->sockfd); return s->ip; } void Slave::connectToServer(std::string ip, int port) { int sockfd, numbytes; char buf[100]; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; std::cout << "Trying to connect to " << ip << " " << port << std::endl; if ((rv = getaddrinfo(ip.c_str(), std::to_string(port).c_str(), &hints, &servinfo)) != 0) { fprintf(stderr, "Slave: getaddrinfo: %s\n", gai_strerror(rv)); return; } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("Slave: failed to get socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("Slave: failed to connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); printf("Slave: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure // Sending msg to initiate dialog if (send(sockfd, CONNECTION_MSG, strlen(CONNECTION_MSG), 0) == -1) perror("Slave: sending Hello!"); // Receiving ACK if ((numbytes = recv(sockfd, buf, 100-1, 0)) == -1) { perror("Slave: failed to recv the connection msg"); exit(1); } buf[numbytes] = '\0'; printf("Slave: received '%s'\n",buf); if (std::string(buf) == CONNECTION_MSG) printf("Slave: ACK"); sockfd_ = sockfd; } <|endoftext|>
<commit_before>#include <taichi/common/util.h> #include <taichi/common/task.h> #include <taichi/visual/gui.h> #include "sound.h" TC_NAMESPACE_BEGIN constexpr int n = 30; constexpr real room_size = 10.0_f; constexpr real dx = room_size / n; constexpr real c = 340; constexpr real alpha = 0.001; Array3D<real> p, q, r; void advance(real dt) { std::swap(p.data, q.data); std::swap(q.data, r.data); r.reset_zero(); constexpr real inv_dx2 = pow<2>(1.0_f / dx); for (int i = 1; i < n - 1; i++) { for (int j = 1; j < n - 1; j++) { for (int k = 1; k < n - 1; k++) { real laplacian_p = inv_dx2 * (p[i - 1][j][k] + p[i][j - 1][k] + p[i + 1][j][k] + p[i][j + 1][k] + p[i][j][k + 1] + p[i][j][k - 1] - 6 * p[i][j][k]); real laplacian_q = inv_dx2 * (q[i - 1][j][k] + q[i][j - 1][k] + q[i + 1][j][k] + q[i][j + 1][k] + q[i][j][k + 1] + q[i][j][k - 1] - 6 * q[i][j][k]); r[i][j][k] = 2 * q[i][j][k] + (c * c * dt * dt + c * alpha * dt) * laplacian_q - p[i][j][k] - c * alpha * dt * laplacian_p; } } } } auto sound = []() { int window_size = 800; int scale = window_size / n; q.initialize(Vector3i(n)); p = r = q; GUI gui("Sound simulation", Vector2i(window_size)); real t = 0, dt = (std::sqrt(alpha * alpha + dx * dx / 3) - alpha) / c; // p[n / 2][n / 2] = std::sin(t); FILE *f = fopen("data/wave.txt", "r"); WaveFile wav_file("output.wav"); dt = 1_f / 44100; TC_P(dt); r[n / 2][n / 2][n / 2] = 1; for (int T = 0; T < 1000; T++) { for (int i = 0; i < 5; i++) { real left, right; fscanf(f, "%f%f", &left, &right); advance(dt); // r[n / 4][n / 2] = (left + right) / 65536.0; t += dt; wav_file.add_sound(dt, r[n / 4 + 4][n / 2][n / 2]); // wav_file.add_sound(dt, std::sin(t * 10000)); } for (int i = 0; i < window_size; i++) { for (int j = 0; j < window_size; j++) { auto c = p[i / scale][j / scale][n / 2]; gui.get_canvas().img[i][j] = Vector3(c + 0.5_f); } } gui.update(); if (T % 100 == 0) wav_file.flush(); } }; TC_REGISTER_TASK(sound); TC_NAMESPACE_END <commit_msg>ABC seems working<commit_after>#include <taichi/common/util.h> #include <taichi/common/task.h> #include <taichi/visual/gui.h> #include "sound.h" TC_NAMESPACE_BEGIN constexpr int n = 100; constexpr real room_size = 10.0_f; constexpr real dx = room_size / n; constexpr real c = 340; constexpr real alpha = 0.00000; Array3D<real> p, q, r; void advance(real dt) { std::swap(p.data, q.data); std::swap(q.data, r.data); r.reset_zero(); constexpr real inv_dx2 = pow<2>(1.0_f / dx); for (int i = 1; i < n - 2; i++) { for (int j = 1; j < n - 1; j++) { for (int k = 1; k < n - 1; k++) { real laplacian_p = inv_dx2 * (p[i - 1][j][k] + p[i][j - 1][k] + p[i + 1][j][k] + p[i][j + 1][k] + p[i][j][k + 1] + p[i][j][k - 1] - 6 * p[i][j][k]); real laplacian_q = inv_dx2 * (q[i - 1][j][k] + q[i][j - 1][k] + q[i + 1][j][k] + q[i][j + 1][k] + q[i][j][k + 1] + q[i][j][k - 1] - 6 * q[i][j][k]); r[i][j][k] = 2 * q[i][j][k] + (c * c * dt * dt + c * alpha * dt) * laplacian_q - p[i][j][k] - c * alpha * dt * laplacian_p; } } } auto lambda = c * dt / dx; auto inv_lambda = 1.0_f / lambda; for (int i = n - 2; i < n - 1; i++) { for (int j = 1; j < n - 1; j++) { for (int k = 1; k < n - 1; k++) { auto scale = lambda * lambda / (1 + 2 * lambda); r[i][j][k] = scale * ((2 * inv_lambda * inv_lambda + 4 * inv_lambda - 6 - 4 * lambda) * q[i][j][k] - (inv_lambda * inv_lambda + 2 * inv_lambda) * p[i][j][k] + p[i + 1][j][k] - p[i - 1][j][k] + 2 * q[i - 1][j][k] + (1 + lambda) * (q[i][j + 1][k] + q[i][j - 1][k] + q[i][j][k + 1] + q[i][j][k - 1])); q[i + 1][j][k] = p[i + 1][j][k] + q[i - 1][j][k] - p[i - 1][j][k] - 2 * inv_lambda * (r[i][j][k] + p[i][j][k] - 2 * q[i][j][k]) + lambda * (q[i][j + 1][k] + q[i][j - 1][k] + q[i][j][k + 1] + q[i][j][k - 1] - 4 * q[i][j][k]); } } } } auto sound = []() { int window_size = 800; int scale = window_size / n; q.initialize(Vector3i(n)); p = r = q; GUI gui("Sound simulation", Vector2i(window_size)); real t = 0, dt = (std::sqrt(alpha * alpha + dx * dx / 3) - alpha) / c; // p[n / 2][n / 2] = std::sin(t); FILE *f = fopen("data/wave.txt", "r"); WaveFile wav_file("output.wav"); dt = 1_f / 44100; TC_P(dt); for (int T = 0; T < 1000; T++) { for (int i = 0; i < 5; i++) { real left, right; fscanf(f, "%f%f", &left, &right); advance(dt); r[n / 2][n / 2][n / 2] = std::sin(std::min(t * 2000, 12 * pi)); // r[n / 4][n / 2] = (left + right) / 65536.0; t += dt; wav_file.add_sound(dt, r[n / 4 + 4][n / 2][n / 2]); // wav_file.add_sound(dt, std::sin(t * 10000)); } for (int i = 0; i < window_size; i++) { for (int j = 0; j < window_size; j++) { auto c = p[i / scale][j / scale][n / 2]; gui.get_canvas().img[i][j] = Vector3(c + 0.5_f); } } gui.update(); if (T % 100 == 0) wav_file.flush(); } }; TC_REGISTER_TASK(sound); TC_NAMESPACE_END <|endoftext|>
<commit_before>#include <map> #include <vector> #include <string> #include <iomanip> #include <iostream> #include <fstream> #include <algorithm> #include <set> #include "table.hpp" #include "expression.hpp" #include "simple_ra.hpp" using namespace RelationalAlgebra; const Schema& Table::getSchema() const { return schema; } size_t Table::size() const { return table.size(); } bool Table::is_union_compatible(const Tuple& t) const { bool valid = t.size() == schema.size(); auto it = t.begin(); auto jt = schema.begin(); for (; jt != schema.end() && it != t.end(); ++jt, ++it) { valid = valid &&(it -> getType() == jt -> second); if (!valid) return false; } return true; } bool Table::is_union_compatible(const Table& t) const { return is_union_compatible(t.getSchema()); } bool Table::is_union_compatible(const Schema& s) const { bool valid = s.size() == schema.size(); for (auto it = s.begin(), jt = schema.begin(); jt != schema.end() && it != s.end(); ++jt, ++it) { valid = valid &&(it -> second == jt -> second); if (!valid) return false; } return true; } Tuple Table::operator [] (size_t idx) const { if (idx >= table.size()) throw std::runtime_error("Index is too large."); auto it = table.begin(); while (idx--) ++it; return *it; } Table Table::operator + (const Table& t) { if (t.size() == 0) return(*this); if (!is_union_compatible(t)) throw std::runtime_error("Incompatible Schema"); table.insert(t.begin(), t.end()); return(*this); } void Table::operator += (const Tuple& t) { if (!is_union_compatible(t)) throw std::runtime_error("Incompatible Schema"); table.insert(t); } Table Table::operator - (const Table& t) { if (t.size() == 0) return(*this); if (!is_union_compatible(t)) throw std::runtime_error("Incompatible Schema"); for (auto& row : t) table.erase(row); return(*this); } Table Table::operator * (const Table& t) { if (t.size() == 0) { table.clear(); schema.clear(); } else { for (auto& a : schema) { for (auto& b : t.getSchema()) { if (a.first == b.first) throw std::runtime_error("Invalid operation on tables. Column name " + a.first + " is same!"); } } for (auto& s : t.getSchema()) { schema.push_back(s); } Tuple temp; TableArray new_table; for (auto& row : table) { for (auto& row2 : t) { temp = row; temp.insert(temp.end(), row2.begin(), row2.end()); new_table.insert(temp); } } table = new_table; } return(*this); } Table Table::select(Predicate* p) { TableArray new_table; for (auto& row : table) { if (p->eval(schema, row)) new_table.insert(row); } table = new_table; return(*this); } Table Table::project(const std::vector< std::string >& col_names) { std::vector< size_t > keep_indices; #ifdef DEBUG std::cout << "Current schema: "; for (auto& a: schema) { std::cout << a.first << " "; } std::cout << std::endl; std::cout << "Columns to project: "; for (auto& a: col_names) { std::cout << a << " "; } std::cout << std::endl; #endif for (size_t i = 0; i < schema.size(); i++) { for (auto& b : col_names) { if (b == schema[i].first) { keep_indices.push_back(i); } } } for (size_t i = 0; i < keep_indices.size(); i++) { for (size_t j = i + 1; j < keep_indices.size(); j++) { if (keep_indices[i] == keep_indices[j]) { throw std::runtime_error("Invalid operation. Can't project same column twice!"); } } } #ifdef DEBUG for (auto a : keep_indices) { std::cout << a << " "; } std::cout << std::endl; #endif if (keep_indices.empty()) { schema.clear(); table.clear(); } else { size_t key = 0, len = schema.size(); for (size_t i = 0; i < len; i++) { if (std::find(keep_indices.begin(), keep_indices.end(), i) == keep_indices.end()) { schema.erase(schema.begin() + i - key++); } } // Delete the unecessary columns from the table Tuple temp; TableArray new_table; for (auto& row : table) { temp = row; key = 0; for (size_t i = 0; i < len; i++) { if (std::find(keep_indices.begin(), keep_indices.end(), i) == keep_indices.end()) { temp.erase(temp.begin() + i - key++); } } new_table.insert(temp); } table = new_table; } return(*this); } Table Table::rename(const std::vector< std::string >& new_names) { for (size_t i = 0 ; i < new_names.size() && i < schema.size(); i++) schema[i].first = new_names[i]; return(*this); } Table Table::min(const std::string& col) const { if (table.empty()) throw std::runtime_error("Empty table."); size_t idx = 0; for (auto& cols : schema) { if (cols.first == col) { break; } idx++; } Cell min_elem(table.begin() -> operator [](idx)); for (auto& rows : table) { if (rows[idx] < min_elem) min_elem = rows[idx]; } Schema s; Tuple t; t.push_back(min_elem); s.push_back(std::make_pair("MIN(" + col + ")", min_elem.getType())); Table result(s); result += t; return result; } Table Table::max(const std::string& col) const { if (table.empty()) throw std::runtime_error("Empty table."); size_t idx = 0; for (auto& cols : schema) { if (cols.first == col) { break; } idx++; } Cell max_elem(table.begin() -> operator [](idx)); for (auto& rows : table) { if (rows[idx] > max_elem) max_elem = rows[idx]; } Schema s; Tuple t; t.push_back(max_elem); s.push_back(std::make_pair("MAX(" + col + ")", max_elem.getType())); Table result(s); result += t; return result; } Table Table::sum(const std::string& col) const { if (table.empty()) throw std::runtime_error("Empty table."); size_t idx = 0; for (auto& cols : schema) { if (cols.first == col) { break; } idx++; } Cell c; if (schema[idx].second == DataType::String) throw std::runtime_error("Invalid operation on data type string."); else if (schema[idx].second == DataType::Integer) { c = Cell(0); for (auto& rows : table) { c = c.getVal().i + rows[idx].getVal().i; } } else if (schema[idx].second == DataType::Float) { c = Cell(0.0f); for (auto& rows : table) { c = c.getVal().f + rows[idx].getVal().f; } } else throw std::runtime_error("Unexpected type of cell."); Schema s; Tuple t; t.push_back(c); s.push_back(std::make_pair("SUM(" + col + ")", c.getType())); Table result(s); result += t; return result; } Table Table::avg(const std::string& col) const { if (table.empty()) throw std::runtime_error("Empty table."); size_t idx = 0; for (auto& cols : schema) { if (cols.first == col) { break; } idx++; } Cell c; if (schema[idx].second == DataType::String) throw std::runtime_error("Invalid operation on data type string."); else if (schema[idx].second == DataType::Integer) { c = Cell(0); for (auto& rows : table) { c = c.getVal().i + rows[idx].getVal().i; } c = Cell((float)((float)c.getVal().i / table.size())); } else if (schema[idx].second == DataType::Float) { c = Cell(0.0f); for (auto& rows : table) { c = c.getVal().f + rows[idx].getVal().f; } c = Cell((float)(c.getVal().f / table.size())); } else throw std::runtime_error("Unexpected type of cell."); Schema s; Tuple t; t.push_back(c); s.push_back(std::make_pair("AVG(" + col + ")", c.getType())); Table result(s); result += t; return result; } Table Table::aggregate(const AggregateOperation& a, const std::string& col_name) const { if (a == AggregateOperation::Min) return min(col_name); else if (a == AggregateOperation::Min) return max(col_name); else if (a == AggregateOperation::Sum) return sum(col_name); else if (a == AggregateOperation::Avg) return avg(col_name); else if (a == AggregateOperation::Count) return count(col_name); else throw std::runtime_error("Unexpected and unidentified aggregate operation type."); } Table Table::count(const std::string& col) const { std::map<Cell, size_t> count_map; size_t idx = 0; for (auto& cols : schema) { if (cols.first == col) { break; } idx++; } for (auto& rows : table) { if (count_map.find(rows[idx]) == count_map.end()) { count_map[rows[idx]] = 0; } else { count_map[rows[idx]] += 1; } } Schema s; s.push_back(std::make_pair("VALUE", schema[idx].second)); s.push_back(std::make_pair("COUNT(" + col + ")", DataType::Integer)); Table result(s); for (auto& a : count_map) { Tuple t; t.push_back(a.first); t.push_back(Cell((int) a.second)); result += t; } return result; } void Table::print(void) const { if (table.empty()) { std::cout << "Empty table." << std::endl; return; } std::vector< size_t > column_lengths; size_t temp; size_t i = 0; for (auto& col : schema) { size_t len = col.first.length(); for (auto& row : table) { temp = row[i].show().length(); if (temp > len) len = temp; } column_lengths.push_back(len); ++i; } size_t row_len = 0; for (auto& a : column_lengths) row_len += a; row_len += column_lengths.size() + 1; for (size_t i = 0; i < row_len; i++) std::cout << "-"; std::cout << std::endl; i = 0; std::cout << "|"; for (auto& a : schema) { std::cout << std::setw((int) column_lengths[i]) << a.first << "|"; ++i; } std::cout << std::endl; for (size_t i = 0; i < row_len; i++) std::cout << "-"; std::cout << std::endl; for (auto& a : table) { i = 0; std::cout << "|"; for (auto& b : a) { std::cout << std::setw((int) column_lengths[i]) << b.show() << "|"; ++i; } std::cout << std::endl; } for (size_t i = 0; i < row_len; i++) std::cout << "-"; std::cout << std::endl; } <commit_msg>Fixed minor bugs<commit_after>#include <map> #include <vector> #include <string> #include <iomanip> #include <iostream> #include <fstream> #include <algorithm> #include <set> #include "table.hpp" #include "expression.hpp" #include "simple_ra.hpp" using namespace RelationalAlgebra; const Schema& Table::getSchema() const { return schema; } size_t Table::size() const { return table.size(); } bool Table::is_union_compatible(const Tuple& t) const { bool valid = t.size() == schema.size(); auto it = t.begin(); auto jt = schema.begin(); for (; jt != schema.end() && it != t.end(); ++jt, ++it) { valid = valid &&(it -> getType() == jt -> second); if (!valid) return false; } return true; } bool Table::is_union_compatible(const Table& t) const { return is_union_compatible(t.getSchema()); } bool Table::is_union_compatible(const Schema& s) const { bool valid = s.size() == schema.size(); for (auto it = s.begin(), jt = schema.begin(); jt != schema.end() && it != s.end(); ++jt, ++it) { valid = valid &&(it -> second == jt -> second); if (!valid) return false; } return true; } Tuple Table::operator [] (size_t idx) const { if (idx >= table.size()) throw std::runtime_error("Index is too large."); auto it = table.begin(); while (idx--) ++it; return *it; } Table Table::operator + (const Table& t) { if (t.size() == 0) return(*this); if (!is_union_compatible(t)) throw std::runtime_error("Incompatible Schema"); table.insert(t.begin(), t.end()); return(*this); } void Table::operator += (const Tuple& t) { if (!is_union_compatible(t)) throw std::runtime_error("Incompatible Schema"); table.insert(t); } Table Table::operator - (const Table& t) { if (t.size() == 0) return(*this); if (!is_union_compatible(t)) throw std::runtime_error("Incompatible Schema"); for (auto& row : t) table.erase(row); return(*this); } Table Table::operator * (const Table& t) { if (t.size() == 0) { table.clear(); schema.clear(); } else { for (auto& a : schema) { for (auto& b : t.getSchema()) { if (a.first == b.first) throw std::runtime_error("Invalid operation on tables. Column name " + a.first + " is same!"); } } for (auto& s : t.getSchema()) { schema.push_back(s); } Tuple temp; TableArray new_table; for (auto& row : table) { for (auto& row2 : t) { temp = row; temp.insert(temp.end(), row2.begin(), row2.end()); new_table.insert(temp); } } table = new_table; } return(*this); } Table Table::select(Predicate* p) { TableArray new_table; for (auto& row : table) { if (p->eval(schema, row)) new_table.insert(row); } table = new_table; return(*this); } Table Table::project(const std::vector< std::string >& col_names) { std::vector< size_t > keep_indices; #ifdef DEBUG std::cout << "Current schema: "; for (auto& a: schema) { std::cout << a.first << " "; } std::cout << std::endl; std::cout << "Columns to project: "; for (auto& a: col_names) { std::cout << a << " "; } std::cout << std::endl; #endif for (size_t i = 0; i < schema.size(); i++) { for (auto& b : col_names) { if (b == schema[i].first) { keep_indices.push_back(i); } } } for (size_t i = 0; i < keep_indices.size(); i++) { for (size_t j = i + 1; j < keep_indices.size(); j++) { if (keep_indices[i] == keep_indices[j]) { throw std::runtime_error("Invalid operation. Can't project same column twice!"); } } } #ifdef DEBUG for (auto a : keep_indices) { std::cout << a << " "; } std::cout << std::endl; #endif if (keep_indices.empty()) { schema.clear(); table.clear(); } else { size_t key = 0, len = schema.size(); for (size_t i = 0; i < len; i++) { if (std::find(keep_indices.begin(), keep_indices.end(), i) == keep_indices.end()) { schema.erase(schema.begin() + i - key++); } } // Delete the unecessary columns from the table Tuple temp; TableArray new_table; for (auto& row : table) { temp = row; key = 0; for (size_t i = 0; i < len; i++) { if (std::find(keep_indices.begin(), keep_indices.end(), i) == keep_indices.end()) { temp.erase(temp.begin() + i - key++); } } new_table.insert(temp); } table = new_table; } return(*this); } Table Table::rename(const std::vector< std::string >& new_names) { for (size_t i = 0 ; i < new_names.size() && i < schema.size(); i++) schema[i].first = new_names[i]; return(*this); } Table Table::min(const std::string& col) const { if (table.empty()) throw std::runtime_error("Empty table."); size_t idx = 0; for (auto& cols : schema) { if (cols.first == col) { break; } idx++; } Cell min_elem(table.begin() -> operator [](idx)); for (auto& rows : table) { if (rows[idx] < min_elem) min_elem = rows[idx]; } Schema s; Tuple t; t.push_back(min_elem); s.push_back(std::make_pair("MIN(" + col + ")", min_elem.getType())); Table result(s); result += t; return result; } Table Table::max(const std::string& col) const { if (table.empty()) throw std::runtime_error("Empty table."); size_t idx = 0; for (auto& cols : schema) { if (cols.first == col) { break; } idx++; } Cell max_elem(table.begin() -> operator [](idx)); for (auto& rows : table) { if (rows[idx] > max_elem) max_elem = rows[idx]; } Schema s; Tuple t; t.push_back(max_elem); s.push_back(std::make_pair("MAX(" + col + ")", max_elem.getType())); Table result(s); result += t; return result; } Table Table::sum(const std::string& col) const { if (table.empty()) throw std::runtime_error("Empty table."); size_t idx = 0; for (auto& cols : schema) { if (cols.first == col) { break; } idx++; } Cell c; if (schema[idx].second == DataType::String) throw std::runtime_error("Invalid operation on data type string."); else if (schema[idx].second == DataType::Integer) { c = Cell(0); for (auto& rows : table) { c = c.getVal().i + rows[idx].getVal().i; } } else if (schema[idx].second == DataType::Float) { c = Cell(0.0f); for (auto& rows : table) { c = c.getVal().f + rows[idx].getVal().f; } } else throw std::runtime_error("Unexpected type of cell."); Schema s; Tuple t; t.push_back(c); s.push_back(std::make_pair("SUM(" + col + ")", c.getType())); Table result(s); result += t; return result; } Table Table::avg(const std::string& col) const { if (table.empty()) throw std::runtime_error("Empty table."); size_t idx = 0; for (auto& cols : schema) { if (cols.first == col) { break; } idx++; } Cell c; if (schema[idx].second == DataType::String) throw std::runtime_error("Invalid operation on data type string."); else if (schema[idx].second == DataType::Integer) { c = Cell(0); for (auto& rows : table) { c = c.getVal().i + rows[idx].getVal().i; } c = Cell((float)((float)c.getVal().i / table.size())); } else if (schema[idx].second == DataType::Float) { c = Cell(0.0f); for (auto& rows : table) { c = c.getVal().f + rows[idx].getVal().f; } c = Cell((float)(c.getVal().f / table.size())); } else throw std::runtime_error("Unexpected type of cell."); Schema s; Tuple t; t.push_back(c); s.push_back(std::make_pair("AVG(" + col + ")", c.getType())); Table result(s); result += t; return result; } Table Table::aggregate(const AggregateOperation& a, const std::string& col_name) const { if (a == AggregateOperation::Min) return min(col_name); else if (a == AggregateOperation::Max) return max(col_name); else if (a == AggregateOperation::Sum) return sum(col_name); else if (a == AggregateOperation::Avg) return avg(col_name); else if (a == AggregateOperation::Count) return count(col_name); else throw std::runtime_error("Unexpected and unidentified aggregate operation type."); } Table Table::count(const std::string& col) const { std::map<Cell, size_t> count_map; size_t idx = 0; for (auto& cols : schema) { if (cols.first == col) { break; } idx++; } for (auto& rows : table) { if (count_map.find(rows[idx]) == count_map.end()) { count_map[rows[idx]] = 1; } else { count_map[rows[idx]] += 1; } } Schema s; s.push_back(std::make_pair("VALUE", schema[idx].second)); s.push_back(std::make_pair("COUNT(" + col + ")", DataType::Integer)); Table result(s); for (auto& a : count_map) { Tuple t; t.push_back(a.first); t.push_back(Cell((int) a.second)); result += t; } return result; } void Table::print(void) const { if (table.empty()) { std::cout << "Empty table." << std::endl; return; } std::vector< size_t > column_lengths; size_t temp; size_t i = 0; for (auto& col : schema) { size_t len = col.first.length(); for (auto& row : table) { temp = row[i].show().length(); if (temp > len) len = temp; } column_lengths.push_back(len); ++i; } size_t row_len = 0; for (auto& a : column_lengths) row_len += a; row_len += column_lengths.size() + 1; for (size_t i = 0; i < row_len; i++) std::cout << "-"; std::cout << std::endl; i = 0; std::cout << "|"; for (auto& a : schema) { std::cout << std::setw((int) column_lengths[i]) << a.first << "|"; ++i; } std::cout << std::endl; for (size_t i = 0; i < row_len; i++) std::cout << "-"; std::cout << std::endl; for (auto& a : table) { i = 0; std::cout << "|"; for (auto& b : a) { std::cout << std::setw((int) column_lengths[i]) << b.show() << "|"; ++i; } std::cout << std::endl; } for (size_t i = 0; i < row_len; i++) std::cout << "-"; std::cout << std::endl; } <|endoftext|>